从GUI类外访问GUI元素

3

我希望有人能帮我解决一个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项目。我也尝试发送信号,但仍然无法获得正确的语法。

可能我的结构是虚假的,这就是为什么我发布了大部分代码的原因。本质上,我有一个由设计师创建的.py文件和我的主程序文件,后者导入它。主程序文件有一个类来启动GUI(每个单独窗口也有一个类)。此类中有信号,调用该类中的方法。这些方法调用我的主程序或我创建的其他类的函数。程序的结尾有if __name__ == "__main__"代码,用于启动GUI。这种结构是否虚假?我已经阅读了许多在线教程,它们都不同或过时。

1个回答

5

您的func1方法是可行的 - 因为uiStartQT4类中的一个字段,所以您应该仅在同一类中直接操作其数据。如果您的代码中只有两个类,则将所有用户界面功能放在一个小部件中的一个类中并不是什么大问题,但是如果有多个类直接引用字段,则可能会导致维护方面的噩梦(如果您更改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_())

谢谢。您描述引用类的<i>实例</i>的答案解决了我的问题。将func2中的“StartQT4”替换为“myapp”解决了问题。 - Turtles Are Cute
1
我也采纳了你的建议,将实例作为参数传递。 - Turtles Are Cute

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接