我正在使用与Qtable小部件相关的类,但它未在QMainWindow中显示

问题描述

我无法在App类(即QMainWindow内部)中显示DataEntryForm类。非常感谢。

#QWidget,包含要显示的QTableWidget的小部件

class DataEntryForm(QWidget):
    def __int__(self):
        super().__init__()

        self.item = 0
        self.data = {"Phone L": 50.5}

        # leftside
        self.table = QTableWidget()
        self.table.setColumnCount(2)
        self.table.setHorizontalHeaderLabels('Descriptions','Price')
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.layout = QHBoxLayout()
        self.layout.addWidget(self.table,50)
        self.setLayout(self.layout)

#QMainWindow,我想在此类中显示“数据输入表单”类。

class App(QMainWindow):
    def __init__(self,widget):
        super().__init__()
        self.title = 'Hello,world!'
        self.setWindowTitle(self.title)
        self.resize(1200,600)
        self.menuBar = self.menuBar()
        self.fileMenu = self.menuBar.addMenu('File')

        # export to csv file action
        exportAction = QAction('Export to csv',self)
        exportAction.setShortcut('Ctrl+E')

        self.setWindowIcon(QIcon('data-analysis_icon-icons.com_52842.ico'))
        # exportAction.triggered.connect

        # exit Action
        exitAction = QAction('Exit',self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.triggered.connect(lambda: app.quit())

        self.fileMenu.addAction(exportAction)
        self.fileMenu.addAction(exitAction)





if __name__ == '__main__':
    app = QApplication(sys.argv)
    x = DataEntryForm()
    ex = App(x)
    ex.show()
    sys.exit(app.exec_())

解决方法

QMainWindow是QWidget的一种特殊类型,它使用central widget来显示其主要内容。在正确创建DataEntryForm的实例时,您只是将其添加为主窗口构造函数中的参数,但是对此却无所事事。

要使用该小部件,请使用setCentralWidget()

class App(QMainWindow):
    def __init__(self,widget):
        super().__init__()
        self.setCentralWidget(widget)
        # ...

提示:避免为不同类型的类和实例使用相似的名称; app是QApplication的实例App是QMainWindow类。使用与该类不同且更相关的内容,例如“ MainWindow”。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...