Accessing GUI elements from outside GUI class in PyQt

落花浮王杯 提交于 2019-12-05 21:52:01

As I said in the answer you linked to: it is always a mistake to edit the module generated by pyuic. It is meant to be a static module that you import into your main program.

Also, the current structure of your program looks backwards. The main script should be at the top level, and all the modules should be in a package below it. This will ensure that you don't need to do any weird sys.path manipulations to import your own modules. Here is what the structure should look like:

program
    |_  main.py
    |_  package
        |_  __init__.py
        |_  app.py
        |_  gui.py
        |_  utils.py

Your main.py script should be very simple, and look like this:

if __name__ == '__main__':

    import sys
    from package import app

    sys.exit(app.run())

It is very important to do things this way, because the path of this script will become the first entry in sys.path. This means you can then do from package import xxx in any other module in your program, and the imports will always work correctly.

The app module should look like this:

import sys
from PyQt4 import QtCore, QtGui
from package.gui import Ui_MainWindow
from package import utils

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.MyPushButton.clicked.connect(self.download_click)

    def download_click(self):
        self.MyTextArea.textCursor().insertHtml('Hello World!')
        url = str(self.MyTextField.text())
        utils.some_func(url)

def run():    
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    return app.exec_()

Note that I've moved the edits you made to your gui module into the app module. The MainWindow class will pull in all the widgets you added in Qt Designer, and they will become attributes of the class instance. So once you've rearranged your program, you should re-generate the gui module using pyuic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!