将qtDesigner与python无缝结合使用

2024-04-24 16:50:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找一种更好的方法来处理使用qtDesigner连接到python后端的前端。我发现的所有方法都有以下形式:

  1. 在designer中生成GUI
  2. 使用pyuic输出到python代码(通常使用-x选项)
  3. 在此输出文件中写入后端代码

这种方法不容易维护或编辑。任何时候你改变用户界面,它都会完全破坏工作流程:你必须重新转换,生成一个新文件,将文件恢复到原来的位置,然后最终回到正轨。这需要大量的手动复制粘贴代码,这是一种在多个级别上引发错误的邀请(新生成的文件布局可能不同,粘贴时手动修复名称更改等)。如果不小心,也可能会丢失工作,因为您可能会意外地覆盖文件并破坏后端代码。在

而且,这不会使用qtDesigner中的任何控件,比如Signal/SlotAction编辑器。它们一定是为了什么而来的,但我找不到一种方法来实际地将这些函数用于调用后端函数。在

有没有更好的方法来处理这个问题,可能使用qtDesigner的特性?在


Tags: 文件方法函数代码编辑选项gui手动
2条回答

您不必在输出文件中添加代码:

如果你拿主页.py'由PYUIC生成,包含QMainWindow,由QtDesigner设置/Puic生成的名称将为Ui_Home(),您的主代码可以是:

from home import Ui_Home
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class window_home(QMainWindow):
   def __init__(self, parent=None):
       QMainWindow.__init__(self, parent)        
       #set up the user interface from Designer
       self.ui = Ui_Home()
       self.ui.setupUi(parent)
       #then do anything as if you were in your output file, for example setting an image for a QLabel named "label" (using QtDesigner) at the root QMainWindow :
       self.ui.label.setPixmap(QPixmap("./pictures/log.png"))

def Home():
    f=QMainWindow()
    c=window_home(f)
    f.show()
    r=qApp.exec_()
if __name__=="__main__":
    qApp=QApplication(sys.argv)
    Home()

我发现了一个更简洁的方法来处理这个问题,它根本不需要在每次编辑之后进行抢先转换。取而代之的是.ui文件本身,所以您需要做的就是重新启动程序本身来更新设计。在

import sys
import os
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic

path = os.path.dirname(__file__) #uic paths from itself, not the active dir, so path needed
qtCreatorFile = "XXXXX.ui" #Ui file name, from QtDesigner, assumes in same folder as this .py

Ui_MainWindow, QtBaseClass = uic.loadUiType(path + qtCreatorFile) #process through pyuic

class MyApp(QMainWindow, Ui_MainWindow): #gui class
    def __init__(self):
        #The following sets up the gui via Qt
        super(MyApp, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #set up callbacks
        self.ui.NAME OF CONTROL.ACTION.connect(self.test)

    def test(self):
        #Callback Function


if __name__ == "__main__":
    app = QApplication(sys.argv) #instantiate a QtGui (holder for the app)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

请注意,这是Qt5。Qt5和Qt4不兼容API,所以Qt4中的情况会有点不同(可能更早)。在

相关问题 更多 >