简体   繁体   中英

PyQt lineEdit is empty when called from another script

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).

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM