PySide Custom小部件不能自动适合QTableWidget

时间:2016-08-14 10:10:35

标签: python qt pyqt4 pyside pyqt5

我正在尝试创建自定义窗口小部件RangeSpinBox。小部件不会自动适合QTableWidget,如下图所示。

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_()

1 个答案:

答案 0 :(得分:1)

您需要删除布局上的默认边距,并更改旋转框上的尺寸政策以向两个方向展开:

        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)