Qt TreeWidget 的 QHeader 中的多个 widget

问题描述 投票:0回答:1

我想在树小部件的标题内添加多个按钮和标签。
这就是我想要的:wireframe。 这是我到目前为止所尝试的:

from PySide2 import QtWidgets, QtCore
import sys


class Header(QtWidgets.QHeaderView):
    def __init__(self, orientation, parent=None):
        super(Header, self).__init__(orientation, parent)

        self.layout_header = QtWidgets.QHBoxLayout()
        self.button = QtWidgets.QPushButton('Button text')
        self.button_2 = QtWidgets.QPushButton('Button text')
        self.label = QtWidgets.QLabel('label')
        self.layout_header.addWidget(self.button)
        self.layout_header.addWidget(self.button_2)
        self.layout_header.addWidget(self.label)
        self.setLayout(self.layout_header)


class TreeWidget(QtWidgets.QTreeWidget):
    def __init__(self, parent=None):
        super(TreeWidget, self).__init__(parent)
        item0 = QtWidgets.QTreeWidgetItem(["Item 0"])
        item1 = QtWidgets.QTreeWidgetItem(["Item 1"])
        self.addTopLevelItem(item0)
        self.addTopLevelItem(item1)
        self.createHeader()

    def createHeader(self):
        header = Header(QtCore.Qt.Horizontal, self)
        self.setHeader(header)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = TreeWidget()
    w.show()
    sys.exit(app.exec_())

我没有任何错误,但效果不佳。甚至可以这样做吗?
谢谢你

python qt pyqt pyside
1个回答
0
投票

正如 musicamante 所说,我需要声明最小高度才能看到它。
答案:

from PySide6 import QtWidgets, QtCore
import sys


class Header(QtWidgets.QHeaderView):
    def __init__(self, orientation, parent=None):
        super(Header, self).__init__(orientation, parent)

        self.layout_header = QtWidgets.QHBoxLayout()
        self.button = QtWidgets.QPushButton('Button text')
        self.button_2 = QtWidgets.QPushButton('Button text')
        self.label = QtWidgets.QLabel('label')
        self.layout_header.addWidget(self.button)
        self.layout_header.addWidget(self.button_2)
        self.layout_header.addWidget(self.label)
        self.setMinimumHeight(50)
        self.setLayout(self.layout_header)


class TreeWidget(QtWidgets.QTreeWidget):
    def __init__(self, parent=None):
        super(TreeWidget, self).__init__(parent)
        item0 = QtWidgets.QTreeWidgetItem(["Item 0"])
        item1 = QtWidgets.QTreeWidgetItem(["Item 1"])
        self.addTopLevelItem(item0)
        self.addTopLevelItem(item1)
        self.createHeader()

    def createHeader(self):
        header = Header(QtCore.Qt.Horizontal, self)
        self.setHeader(header)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = TreeWidget()
    w.show()
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.