将qtDesigner与python无缝结合使用
我一直在寻找一种更好的方法来使用连接到python后端的qtDesigner制作的前端。我找到的所有方法都有以下形式:将qtDesigner与python无缝结合使用,python,qt-designer,Python,Qt Designer,我一直在寻找一种更好的方法来使用连接到python后端的qtDesigner制作的前端。我找到的所有方法都有以下形式: 在designer中制作GUI 使用pyuic输出到python代码(通常使用-x选项) 在此输出文件中写入后端代码 这种方法不容易维护或编辑。任何时候你改变用户界面,它都会完全破坏工作流程:你必须重新转换,生成一个新文件,将该文件修复回原来的位置,然后最终回到正轨。这需要大量手动复制粘贴代码,这会在多个级别上引发错误(新生成的文件布局可能不同,粘贴时手动修复名称更改等)。如果
-x
选项)信号/插槽
和操作
编辑器。这些必须在这里的东西,但我找不到一种方法来实际指导这些调用后端函数
是否有更好的方法来处理此问题,可以使用qtDesigner的功能?您不必在输出文件中添加代码: 如果您使用PYUIC生成的“home.py”,其中包含一个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中会有一些不同(可能更早)。您不编辑输出文件,而是将其导入主文件中。如果我这样做,我将在
窗口中作为方法执行所有后端函数。
?是(或取消调用它的函数)