我在'DataClass'中有主窗口。如何在另一个类(HelloClass)中创建小部件
test.py
import sys
import label
from PyQt4 import QtGui, QtCore
class DataClass(QtGui.QMainWindow):
def __init__(self):
super(DataClass, self).__init__()
self.window()
def window(self):
ex=label.HelloClass(self)
ex.print_label()
def main():
app = QtGui.QApplication(sys.argv)
ob=DataClass()
ob.show()
sys.exit(app.exec_())
if __name__=='__main__':
main()
这是'label.py'文件:
import sys
from PyQt4 import QtGui, QtCore
class HelloClass(QtGui.QMainWindow):
def print_label(self):
self.la=QtGui.QLabel("hello",self)
self.la.move(300,100)
self.la.show()
import sys
from PyQt4 import QtGui, QtCore
class HelloClass(QtGui.QMainWindow):
def print_label(self):
self.la=QtGui.QLabel("hello",self)
self.la.move(300,100)
self.la.show()
答案 0 :(得分:1)
您不能拥有两个QMainWindow
课程,您不应该继承QMainWindow
上的HelloClass
。如果您要将父级设置为标签,请将其设为DataClass
,即QMainWindow
。
class HelloClass(object):
def print_label(self, parent):
self.la = QtGui.QLabel("hello", parent)
self.la.move(300, 100)
self.la.show()
class DataClass(QtGui.QMainWindow):
def __init__(self):
super(DataClass, self).__init__()
self.window()
def window(self):
ex = label.HelloClass()
ex.print_label(self)
但说实话,使用PyQt创建GUI的最佳方法是使用QtDesigner。使用QtDesigner创建.ui文件,然后使用命令pyuic4 your.ui -o ui_your.py
创建.py文件。
- 更新 -
使用QtDesigner创建的gui的控制器类如下所示:
from ui_objects import Ui_Objects # this is class created with QtDesigner, name of class is a 'Ui_' + name of main Object in QtDesigner
class Objects(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.ui = Ui_Objects()
self.ui.setupUi(self)
# then you can add your own code, in example connect your own methods to actions for widgets