我希望有人能帮我解决Qt designer的问题。我试图从调用GUI文件的类外部修改GUI元素。我已经设置了显示程序结构的示例代码。我的目标是在主程序(或其他类)中使用func2来更改主窗口的状态栏。
from PyQt4 import QtCore, QtGui
from main_gui import Ui_Main
from about_gui import Ui_About
#main_gui and about_gui are .py files generated by designer and pyuic
class StartQT4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Main()
self.ui.setupUi(self)
self.ui.actionMyaction.triggered.connect(self.func1)
#Signals go here, and call this class's methods, which call other methods.
#I can't seem to call other methods/functions directly, and these won't take arguments.
def func1(self):
#Referenced by the above code. Can interact with other classes/functions.
self.ui.statusbar.showMessage("This works!")
def func2(self):
StartQT4.ui.statusbar.showMessage("This doesn't work!")
#I've tried many variations of the above line, with no luck.
#More classes and functions not directly-related to the GUI go here; ie the most of the program.
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())我正在尝试让func2正常工作,因为我不希望我的整个程序都在StartQT4类之下。我尝试过这一行的许多变体,但似乎不能从这个类的外部访问GUI项。我也尝试过发送信号,但仍然不能得到正确的语法。
这可能是我的结构是假的,这就是为什么我发布了大部分内容。本质上,我有一个由Designer创建的.py文件,以及导入它的主程序文件。主程序文件有一个启动GUI的类(每个单独的窗口都有一个类)。它在这个类中有信号,调用这个类中的方法。这些方法调用我的主程序或我创建的其他类中的函数。程序的最后有if __name__ == "__main__"代码,用来启动图形用户界面。这个结构是假的吗?我在网上读过很多教程,都是不同的,或者已经过时了。
发布于 2013-04-14 23:07:38
您的func1方法是一种可行的方法--因为ui是StartQT4类中的一个字段,所以您应该只在同一个类中直接操作它的数据。在一个类中拥有一个小部件的所有用户界面功能并没有错-如果代码中只有两个类,这不是一个大问题,但是有几个类直接引用字段对于维护来说是潜在的噩梦(如果更改statusbar小部件的名称呢?)。
但是,如果您真的想从func2编辑它,那么您需要将StartQT4对象的引用传递给它,因为您需要指定需要更改窗口的哪个实例的状态栏消息。
def func2(qtWnd): # Self should go here if func2 is beloning to some class, if not, then it is not necessary
qtWnd.ui.statusbar.showMessage("This should work now!")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
func2(myapp)
sys.exit(app.exec_())https://stackoverflow.com/questions/16000361
复制相似问题