PyQt lineEdit is empty when called from another sc

2019-08-11 05:38发布

问题:

This is my mainscript which calls some generated UI and defines a few functions:

import uifile

from PyQt5 import QtWidgets
import sys

class App(QtWidgets.QMainWindow, uifile.Ui_MyWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.btn_clickMe.clicked.connect(self.some_function)
        return
    def some_function(self):
        import otherpyscript
    def input_user(self):
        user = self.lineEdit_username.text()
        return user

def main():
    app = QtWidgets.QApplication(sys.argv)
    form = App()
    form.show()
    app.exec_()


if __name__ == '__main__':
    main()

This is the other script where I call the function from mainscript:

...
import mainscript

print("The user input from your other script is: " + mainscript.App().input_user())

I'm trying to get mainscript.App().input_user() to not show up as empty (the default for PyQt).

回答1:

EDIT:

On second thoughts, the right approach depends on how mainscript is used. If it is used as the start-up script, it will not be initially imported, which then complicates things when it comes to accessing its globals later on.

A better approach is to have a very simple start-up script that only has this in it:

# mainscript
if __name__ == '__main__':
    from mainmodule import main
    main()

The mainmodule would then look like this:

# mainmodule
import sys
from PyQt5 import QtWidgets
import uifile

class App(QtWidgets.QMainWindow, uifile.Ui_MyWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.btn_clickMe.clicked.connect(self.some_function)
    def some_function(self):
        import othermodule
        othermodule.print_user()
    def input_user(self):
        user = self.lineEdit_username.text()
        return user

form = None

def main_window():
    return form

def main():
    global form
    app = QtWidgets.QApplication(sys.argv)
    form = App()
    form.show()
    app.exec_()

And othermodule would look like this:

# othermodule
import mainmodule

def print_user():
    print("user input: " + mainmodule.main_window().input_user())


标签: python pyqt5