这个问题在这里已有答案:
我正在将登录窗口连接到主窗口,但我需要将登录用户名传递给下一个窗口,注意它们位于不同的类中。
我的代码如下:
FROM_CLASS, _ = loadUiType(path.join(path.dirname(__file__), "Main_rfi-design2.ui"))
FROM_CLASS2, _ = loadUiType(path.join(path.dirname(__file__), "login_rfi.ui"))
class Login(QMainWindow, FROM_CLASS2):
def __init__(self, parent=None):
super(Login, self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.btn_login.clicked.connect(self.handel_login)
self.window2 = None
def __init__(self, parent=None):
super(Login, self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.btn_login.clicked.connect(self.handel_login)
self.window2 = None
def handel_login(self):
self.db = pymysql.connect(host="localhost", user="root", passwd="", db="db_co")
self.cur = self.db.cursor()
self.user_name = self.lineEdit.text()
self.password = self.lineEdit_16.text()
sql = '''SELECT user_name FROM users'''
self.cur.execute(sql)
users = self.cur.fetchall()
users = [i for sub in users for i in sub]
sql2 = '''SELECT pass FROM users'''
self.cur.execute(sql2)
pass1 = self.cur.fetchall()
pass1 = [i for sub in pass1 for i in sub]
if self.user_name in users:
user_index = users.index(self.user_name)
if self.password == pass1[user_index]:
self.window2 = Main()
# self.window2 = Main(Login.return_username())
self.close()
self.window2.show()
else:
self.label.setText('Please check User Name or Password...')
else:
self.label.setText('User name dose not exist...')
print('Current user is: ' + self.user_name)
class Main(QMainWindow, FROM_CLASS):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
# To start applaying functions:
self.initUI()
self.handel_button()
在主窗口中,创建一个setter函数,允许您设置名称String。根据需要从登录窗口调用/调用它(假设主窗口创建登录窗口并为子项提供对自身的引用)。如果您希望将登录结果传递给新窗口,只要主窗口创建相关的后续/子窗口,这也将起作用。
以下代码(我尚未验证其功能并可能需要更改)应该让您开始:
# in Main class:
def setName(n):
if n is not None and len(n) > 0: # Check might not be required if you're OK with empty names
self.name = n
# in function that creates login Window, create the login window with a reference
# window creation might already take a "parent" param, in which case you're all set.
createLoginWindow(requiredParams, main=self)
# in LoginWindow init/constructor:
self.mainWindow = main
# When name changes:
self.mainWindow.setName(name)