pythonlayoutpyqtpysideqtablewidget

PySide Custom widget doesn't auto fit in QTableWidget


I am trying to create a custom widget RangeSpinBox. The widget doesn't auto fit in a QTableWidget like in the image attached below.

enter image description here

import sys
from PySide import QtGui


class RangeSpinBox(QtGui.QWidget):
    def __init__(self, *args, **kwargs):
        super(RangeSpinBox, self).__init__(*args, **kwargs)

        self.__minimum = 0
        self.__maximum = 100

        main_layout = QtGui.QHBoxLayout()

        self.__minimum_spin_box = QtGui.QSpinBox()
        self.__range_label = QtGui.QLabel('-')
        self.__maximum_spin_box = QtGui.QSpinBox()

        main_layout.addWidget(self.__minimum_spin_box)
        main_layout.addWidget(self.__range_label)
        main_layout.addWidget(self.__maximum_spin_box)

        self.setLayout(main_layout)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    spin_box = RangeSpinBox()
    table_widget = QtGui.QTableWidget()
    table_widget.setColumnCount(2)
    table_widget.setRowCount(1)
    table_widget.setCellWidget(0, 0, spin_box)
    table_widget.setCellWidget(0, 1, QtGui.QSpinBox())
    table_widget.show()
    app.exec_()

Solution

  • You need to remove the default margins on the layout, and also change the size-policy on the spin-boxes to expand in both directions:

            main_layout = QtGui.QHBoxLayout()
            main_layout.setContentsMargins(0, 0, 0, 0)
    
            size_policy = QtGui.QSizePolicy(
                QtGui.QSizePolicy.MinimumExpanding,
                QtGui.QSizePolicy.MinimumExpanding)
    
            self.__minimum_spin_box = QtGui.QSpinBox()
            self.__minimum_spin_box.setSizePolicy(size_policy)
            self.__range_label = QtGui.QLabel('-')
            self.__maximum_spin_box = QtGui.QSpinBox()
            self.__maximum_spin_box.setSizePolicy(size_policy)