通过按钮将qt上的两个不同的小部件与python连接在一起

2022-01-18 00:00:00 python pyqt qt4 qt widget

问题描述

我想知道如何将两个小部件连接在一起.我在 QtDesigner 上创建了两个小部件,一个是登录页面,另一个是主菜单.我想连接它们,这样当登录成功时,用户将被重定向到主窗口,并且登录小部件将自动关闭.有谁知道怎么做?

I was wondering how to connect two widgets together. I have two widgets i created on QtDesigner, one being a Login page, and another being a Main Menu. I want to connect them so that when the Login is successful, the user will be redirected to the Main Window, and the Login widget will close automatically. Does anyone know how to do this?

PS.我有主菜单的代码并在单独的 .py 文件中登录

PS. I have the code for the main menu and login in separate .py files


解决方案

你可以这样做:

在您的 QApp 中,首先创建一个包含登录小部件的对话框并执行该对话框.根据结果​​,要么(如果登录失败)退出应用程序(或重新提示用户登录),要么(如果登录成功)实例化主窗口并显示它.

In your QApp create first a dialogue containing the login widget and execute the dialogue. Depending on the result, either (if login failed) quit the application (or reprompt the user for login), or (if login succeeded) instantiate the main window and show it.

或者:实例化并显示主窗口.立即显示与登录小部件的应用程序模式对话.根据结果​​,恢复操作或退出应用程序.

Or: Instantiate and show the main window. Immediately show an application-modal dialogue with the login widget. Depending on the result, either resume operation or quit the application.

这里是一些代码的片段,提示用户登录并对照数据库进行检查.登录对话框在另一个文件中定义为 DlgLogin.

Here a snippet from some code, that prompts the user for login and checks it against a DB. The login dialogue is defined as DlgLogin in another file.

#many imports
from theFileContainingTheLoginDialogue import DlgLogin

class MainWindow (QtGui.QMainWindow):
    def __init__ (self, parent = None):
        super (MainWindow, self).__init__ ()
        self.ui = Ui_MainWindow ()
        self.ui.setupUi (self)
        dlg = DlgLogin (self)
        if (dlg.exec_ () == DlgLogin.Accepted):
            #check here whether you accept or reject the credentials
            self.database = Database (*dlg.values)
            if not self.database.check (): sys.exit (0)
        else:
            sys.exit (0)
        self.mode = None

对话类如下(有两个用于凭据的行编辑小部件):

The dialogue class is the following (having two line-edit-widgets for the credentials):

from PyQt4 import QtGui
from dlgLoginUi import Ui_dlgLogin

class DlgLogin (QtGui.QDialog):
    def __init__ (self, parent = None):
        super (DlgLogin, self).__init__ ()
        self.ui = Ui_dlgLogin ()
        self.ui.setupUi (self)

    @property
    def values (self):
        return [self.ui.edtUser.text (), self.ui.edtPassword.text () ]

应用程序本身读取:

#! /usr/bin/python3.3

import sys
from PyQt4 import QtGui
from mainWindow import MainWindow

def main():
    app = QtGui.QApplication (sys.argv)
    m = MainWindow ()
    m.show ()
    sys.exit (app.exec_ () )

if __name__ == '__main__':
    main ()

相关文章