首页 > 解决方案 > 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()

标签: pythonpython-3.xpyqtpyqt5

解决方案


在您的主窗口中,创建一个允许您设置名称 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)

推荐阅读