PyQt type()和itemAt()返回不同的东西

时间:2018-03-22 05:59:58

标签: python pyqt pyqt5

我试图为我的PyQt应用设置单元测试,但我遇到了意外情况。

基本上,layout.itemAt()返回的项目类型与添加到布局中的项目不同,我很好奇。

这是我的示例代码:

from PyQt5 import QtWidgets


class MainWindow(QtWidgets.QDialog):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.layout = QtWidgets.QVBoxLayout()
        self.table = QtWidgets.QTableWidget()
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

        print(type(self.table))
        print(type(self.layout.itemAt(0)))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()

运行此操作后,type(self.table)会按预期返回<class 'PyQt5.QtWidgets.QTableWidget'>,但type(self.layout.itemAt(0)) - 仍然是表格项目 - 会返回<class 'PyQt5.QtWidgets.QWidgetItem'>,我可以&#39 ;弄清楚为什么他们会有所不同。

2 个答案:

答案 0 :(得分:0)

继承QLayout QBoxLayoutQGridLayoutQFormLayoutQStackedLayout的类作为其主要元素QLayoutItem(在您的case QWidgetItem)这是一个可以处理其他QLayoutQWidget几何的类,也就是使用方法itemAt()返回的对象。

如果您想获取小部件,则必须使用widget()QLayoutItem方法:

from PyQt5 import QtWidgets


class MainWindow(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.layout = QtWidgets.QVBoxLayout()
        self.table = QtWidgets.QTableWidget()
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)
        assert(self.table == self.layout.itemAt(0).widget())

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    form = MainWindow()
    form.show()
    sys.exit(app.exec_())

答案 1 :(得分:0)

该对象类型是窗口小部件和布局在添加项目时创建的布局之间的中间位置(请参阅here)。使用self.layout.itemAt(0).widget()获取原始小部件!

相关问题