Tur*_*ute 3 python qt pyqt qt-designer
我希望有人能帮助我解决 Qt 设计师的问题。我正在尝试从调用 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_())
Run Code Online (Sandbox Code Playgroud)
我正在努力开始func2工作,因为我不希望我的整个程序都在 StartQT4 类下。我已经尝试了该行的许多变体,但似乎无法从此类之外访问 GUI 项目。我也尝试过发送信号,但仍然无法获得正确的语法。
我的结构可能是假的,这就是我发布大部分内容的原因。本质上,我有一个.py由设计器创建的文件,以及导入它的主程序文件。主程序文件有一个类来启动 GUI(以及每个单独窗口的类)。它在这个类中有信号,调用类中的方法。这些方法从我的主程序或我创建的其他类中调用函数。程序末尾有if __name__ == "__main__"启动 GUI 的代码。这个结构是假的吗?我在网上读过很多教程,要么都是不同的,要么是过时的。
您的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_())
Run Code Online (Sandbox Code Playgroud)