本文共 2824 字,大约阅读时间需要 9 分钟。
最近在学习pyqt5编程,需要使用自定义控件,定义了一个setGroup的类,继承自QWidget。在AutoMainWin类中实例化setGroup类,期望在QMainWindow上显示setGroup的内容,发现自定义的类setGroup并不能显示。把setGroup类作为主窗口在__name__ == '__main__'中实例化,发现也不能正常显示。确定是自定义控件的问题,而不是放在AutoMainWin中才不能显示的。排查setGroup类内容,最终发现是因为缺少了self.setLayout(self.Hbox)。附代码如下:
#!import sysimport serialfrom PyQt5.QtWidgets import *from PyQt5.QtCore import *from PyQt5.QtGui import *class SetWin(QWidget): def __init__(self): super(SetWin, self).__init__() self.initUI() def initUI(self): comNum = ['Com1', 'Com2', 'Com3', 'Com4'] self.setGeometry(200, 200, 100, 150) self.setWindowTitle('Set Com Port') self.sltPortLB = QLabel('Select Com Port') self.sltPort = QComboBox() self.sltPort.addItems(comNum) vbox = QVBoxLayout() vbox.addWidget(self.sltPortLB) vbox.addWidget(self.sltPort) vbox.addStretch(1) self.setLayout(vbox) self.setWindowModality(Qt.ApplicationModal) self.show() print('init setwin')class setGroup(QWidget): def __init__(self): super(setGroup, self).__init__() self.grp = QGroupBox() self.grp.setTitle('Set Com Port') self.sltlb = QLabel('Select Port') self.startbtn = QPushButton('Start') self.combx = QComboBox() self.combx.addItem('Com1') self.HboxSlt = QHBoxLayout() self.HboxSlt.addWidget(self.sltlb) self.HboxSlt.addWidget(self.combx) self.HboxSlt.addStretch(1) self.Vbox = QVBoxLayout() self.Vbox.addLayout(self.HboxSlt) self.Vbox.addWidget(self.startbtn) self.grp.setLayout(self.Vbox) self.Hbox = QHBoxLayout() self.Hbox.addWidget(self.grp) self.Hbox.addStretch(1) self.setLayout(self.Hbox) print('set group')class AutoMainWin(QMainWindow): def __init__(self): super(AutoMainWin, self).__init__() self.initUI() def initUI(self): self.setGeometry(100, 100, 640, 480) self.setWindowTitle('test tool') comAction = QAction(QIcon('set.png'), 'Set Com', self) comAction.setShortcut('Ctrl+T') comAction.triggered.connect(self.openSetWin) self.toolbar = self.addToolBar('Set') self.toolbar.addAction(comAction) self.toolbar.setIconSize(QSize(42, 36)) lb = QLabel('name1') setgrp = setGroup() self.Vbox = QVBoxLayout() self.Vbox.addWidget(setgrp) self.Vbox.addWidget(lb) self.Vbox.addStretch(1) #self.setLayout(self.Vbox) wgt = QWidget() wgt.setLayout(self.Vbox) self.setCentralWidget(wgt) def openSetWin(self): self.setwin = SetWin() print('set window')if __name__ == '__main__': app = QApplication(sys.argv) gAutoMain = AutoMainWin() gAutoMain.show() sys.exit(app.exec_())
转载地址:http://zjmii.baihongyu.com/