如何生成Taurusdesigner或Qt下创建的GUI的Python代码?

如何生成Taurusdesigner或Qt下创建的GUI的Python代码?,python,qt,user-interface,pyqt4,Python,Qt,User Interface,Pyqt4,首先让我告诉你,我对Qt和Python都是新手 我正在使用Qt(Taurusdesigner)创建我的GUI。 启动Qt(Taurusdesigner)后,我使用以下方法为该特定GUI生成python代码: taurusuic4 -x -o file.py file.ui or pyuic4 -x -o file.py file.ui 在命令行上执行此命令后,我可以生成python文件,但自动生成的类如下所示: class MainWindow(object): def setupUi

首先让我告诉你,我对Qt和Python都是新手

我正在使用Qt(Taurusdesigner)创建我的GUI。 启动Qt(Taurusdesigner)后,我使用以下方法为该特定GUI生成python代码:

taurusuic4 -x -o file.py file.ui
or
pyuic4 -x -o file.py file.ui
在命令行上执行此命令后,我可以生成python文件,但自动生成的类如下所示:

class MainWindow(object):
    def setupUi(self, MainWindow):
当我在谷歌上搜索任何帮助时,我发现这个类写得像:

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
我将如何使用Qt(Taurusdesigner)生成第二类文件

为什么我的类和为在互联网上提供帮助而编写的类之间存在语法差异。 请帮忙。
提前感谢。

setupUI
\uuuu init\uuu
是类
主窗口的两种方法。对于一个类,可以有任意数量的方法,您可以按照自己喜欢的顺序排列它们

总是有一个
\uuuu init\uuuu
方法,它被称为构造函数。当您创建对象时(例如,当您执行
myWindow=MainWindow()
时),将调用此方法。它通常放在开头,因为它将首先被调用。特别是对于QT,您必须使用
super
调用父级构造函数

setupUI
是由设计师创建的方法,用于处理布局等问题。应该在构造函数中调用它

您的代码应该如下所示:

class MainWindow(object):
    def setupUi(self, MainWindow):
        #code made by the designer

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        #some code

   def another_method(self):
        #some more code

taurusuic4/pyuic4
生成的ui模块应该导入到主应用程序中。您不需要使用
-x
选项,显然您应该选择比“文件”更好的模块名称:

您的主应用程序模块应如下所示:

from PyQt4.QtGui import QMainWindow
from mainwindow import Ui_MainWindow

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.handleButton)

    def handleButton(self):
        print('Hello World!')
这种方法意味着来自Qt(Taurus)Designer的所有小部件最终都会成为
MainWindow
类的属性。另一种方法是将ui元素放在单独的命名空间中:

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.handleButton)

如果您对类、对象和方法感到困惑,我建议您阅读一篇教程
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.handleButton)