0

我在“DataClass”中有主窗口。如何在另一个类(HelloClass)中创建小部件

测试.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()
4

1 回答 1

1

你不能有两个类,你不应该从onQMainWindow继承。如果您将 parent 设置为 label ,则将其设置为 your which is your 。QMainWindowHelloClassDataClassQMainWindow

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 文件,然后使用 command 创建 .py 文件pyuic4 your.ui -o ui_your.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
于 2013-02-04T15:59:00.960 回答