我一直在寻找一种更好的方法来使用使用连接到python后端的qtDesigner制作的前端。我发现的所有方法都有以下形式:
-x选项)这种方法不容易维护或编辑。当您更改UI时,它完全破坏了工作流:您必须重新转换,生成一个新文件,将该文件修复回原来的位置,然后最终回到正轨上。这需要大量的手工复制粘贴代码,这是对多个级别错误的邀请(新生成的文件布局可能不一样,在粘贴时手动修复名称更改,等等)。如果不小心,也可能会丢失工作,因为您可能会意外地覆盖文件并销毁后端代码。
而且,这不使用qtDesigner中的任何控件,比如Signal/Slot和Action编辑器。它们一定是为了什么而出现的,但我无法找到一种方法来真正地引导这些函数调用后端函数。
是否有更好的方法来处理这个问题,可能使用qtDesigner的特性?
发布于 2018-04-18 14:37:25
我找到了一种更简洁的方法来处理这个问题,它根本不需要在每次编辑之后进行抢占式转换。相反,它使用.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中会有一些不同(可能也会更早)。
发布于 2018-04-17 18:39:30
您不必将代码添加到输出文件中:
如果您接受由PYUIC生成的“home.py”,其中包含由QtDesigner/ Puic生成的名称设置为Ui_Home()的QMainWindow,则您的主要代码可能是:
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()https://stackoverflow.com/questions/49884903
复制相似问题