Accesing PyQt Gui elements from another file
I am learning PyQt and coming from webdesign, so excuse this question that must have very obvious answer.So I am building a PyQt application and I w开发者_StackOverflow中文版ould like to spread methods to several files to correspond different parts of GUI. How can I access textbox locating in fileA.py from fileB.py. :
#fileA.py
import sys
from PyQt4 import QtGui, QtCore
from gui1 import Ui_MainWindow
import fileB
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
#This works all fine
def pressed():
window.plainTextEdit.appendPlainText("Hello")
window.pushButton.pressed.connect(pressed)
window.button2.pressed.connect(fileB.func3)
sys.exit(app.exec_())
Now, in this file I would like to use textbox from fileA.py
#fileB.py
import fileA
#How do I access window.plainTextEdit from fileA.py
def func3():
print "hello"
fileA.window.plainTextEdit.appendPlainText("Hello")
What am I doing wrong? What would be best way to spread functionality to multiple files if not this?
Thank you for taking time to read this.
You can take advantage of Python's class inheritance, like so:
fileA.py:
import sys
from PyQt4 import QtGui, QtCore
from gui1 import Ui_MainWindow
import fileB
class MyApp(fileB.MyApp, QtGui.QMainWindow):
def __init__(self):
self.MyMethod()
# Should print 'foo'
fileB.py:
import sys
from PyQt4 import QtGui, QtCore
from gui1 import Ui_MainWindow
class MyApp(QtGui.QMainWindow):
def MyMethod(self):
print 'foo'
Well, first off, the code under if __name__ == "__main__"
will never be run when you are importing fileA.py
, and so fileA.window
does not exist. That's what it should do: run only when __name__
is "__main__"
, i.e. run as a top-level program. Instead, you should import fileA.py
, create the QApplication
and window
again, then access window.plainTextEdit
. However, this creates a very tight coupling between the code, as you are directly accessing a widget in MyApp
from fileB
. It might be better if instead, you expose a method in MyApp
that appends to the text box instead of having fileB.py
do it directly. So you may want to think about what you want to do and how to structure your program.
Of course, you don't have to structure your code that way; you could simply do
window = MyApp()
window.plainTextEdit.appendPlainText("Hello")
in fileB
if you wanted.
精彩评论