python - Pyqt5:将名称表单登录传递给主窗口
问题描述
我将登录窗口连接到主窗口,但我需要将登录用户名传递到下一个窗口,注意它们在不同的类中。
我的代码如下:
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()
解决方案
在您的主窗口中,创建一个允许您设置名称 String 的 setter 函数。根据需要从登录窗口调用/调用它(假设主窗口创建登录窗口并为子窗口提供对其自身的引用)。如果您想将登录结果传递到新窗口,这也将起作用,前提是主窗口创建相关的后续/子窗口。
以下代码(我尚未验证其功能性,可能需要更改)应该可以帮助您入门:
# 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)
推荐阅读
- amazon-redshift - 使用 Boto3 设置 Redshift 集群可见性
- r - 当所有括号看起来都匹配时,R中的“不匹配的左括号”错误
- react-native - 你能把一个对象放在一个数组中,而这个数组又在另一个对象中吗?
- javascript - 如何在反应中将外部样式表应用于 iframe 子组件
- c# - 我必须创建随机数骰子
- javascript - 如何直接从异步函数返回对象?
- forms - 如何从 Drupal 8 中的“select2”类型的多个字段中检索数据
- mysql - DDEV 通过 SSH 隧道从登台服务器连接到 MySQL 数据库返回:无法分配请求的地址
- python - 如何修复 TypeError:只能将列表(而不是“str”)连接到列表?
- c++ - 带类的动态分配