【问题标题】:Detect when "X" button is clicked检测何时单击“X”按钮
【发布时间】:2019-12-23 02:05:50
【问题描述】:

我创建了一个登录窗口,在用户输入正确的密码之前,该窗口将一直存在,如果用户按下右上角的“X”按钮,该窗口应该会消失。但是,即使用户输入了错误的密码,窗口也会消失。

代码:

class Login(QDialog):
    def __init__(self,parent=None):
        super(Login, self).__init__(parent)

        self.grid = QGridLayout(self)
        self.setGeometry(650, 350, 400, 150)
        self.setFixedSize(400, 150)

        self.UserLabels = QLabel(self)
        self.UserLabels.setText('Login Number:')
        self.grid.addWidget(self.UserLabels, 0, 0, 1, 1)

        self.textName = QLineEdit(self)
        self.grid.addWidget(self.textName, 0, 1, 1, 2)

        self.buttonLogin = QPushButton('Submit', self)
        self.buttonLogin.clicked.connect(self.closeGUI)
        self.grid.addWidget(self.buttonLogin, 2, 0, 1, 3)

        finish = QAction("Quit", self)
        finish.triggered.connect(self.closeWin)

    def closeGUI(self):
        self.close()
        return str(self.textName.text())

    def closeWin(self):
        self.close()
        return 1

def handleLogin():
    flag = 0
    while flag == 0:
        edit_params__QD = Login()
        edit_params__QD.exec_()
        if edit_params__QD.result() == 0:
            password = edit_params__QD.closeGUI()
            if password == '6':
                flag = 1
            else:
                flag = 0
        if edit_params__QD.closeWin() == 1:
            flag = 1

if __name__ == '__main__':
    app = QApplication(sys.argv)
    handleLogin()

【问题讨论】:

  • 您可以按照这里的three_pineapples 答案处理事件:stackoverflow.com/questions/24532043/…
  • 这些都不能解决我想做的事情。当输入不正确时,我希望窗口继续打开。但是,如果用户单击“X”,则销毁该窗口。现在,它只会破坏窗口。

标签: python events pyqt qdialog


【解决方案1】:

试试看:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *


class MainWindow(QMainWindow):

    windowList = []                                          

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('Main interface')
        self.showMaximized()
        # Create Menu Bar
        self.createMenus()

    def createMenus(self):
        # Create login action
        self.printAction1 = QAction(self.tr("Entrance"), self)
        self.printAction1.triggered.connect(self.on_printAction1_triggered)
        # Create exit action
        self.printAction2 = QAction(self.tr("Exit"), self)
        self.printAction2.triggered.connect(self.on_printAction2_triggered)
        # Create menu, add actions
        self.printMenu = self.menuBar().addMenu(self.tr("Entrance and Exit"))
        self.printMenu.addAction(self.printAction1)
        self.printMenu.addAction(self.printAction2)

    # Step 1: Login
    def on_printAction1_triggered(self):
        self.close()
        dialog = LoginDialog()
        if  dialog.exec_()==QDialog.Accepted:
            the_window = MainWindow()
            self.windowList.append(the_window)          # ! It is important !
            the_window.show()

    def on_printAction2_triggered(self):
        self.close()

    # Interface close event
    def closeEvent(self, event):
        print("The End")


class LoginDialog(QDialog):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('Login interface')
        self.resize(250, 200)
        self.setFixedSize(self.width(), self.height())
        self.setWindowFlags(Qt.WindowCloseButtonHint)

        # Configure UI controls
        self.frame = QFrame(self)
        self.frame.resize(250, 200)
        self.verticalLayout = QVBoxLayout(self.frame)

        self.lineEdit_account = QLineEdit()
        self.lineEdit_account.setPlaceholderText("Please enter nickName (admin)")
        self.verticalLayout.addWidget(self.lineEdit_account)

        self.lineEdit_password = QLineEdit()
        self.lineEdit_password.setPlaceholderText("Please enter your password (admin)")
        self.verticalLayout.addWidget(self.lineEdit_password)

        self.pushButton_enter = QPushButton()
        self.pushButton_enter.setText("OK")
        self.verticalLayout.addWidget(self.pushButton_enter)

        self.pushButton_quit = QPushButton()
        self.pushButton_quit.setText("Cancel")
        self.verticalLayout.addWidget(self.pushButton_quit)

        # bindings button Event
        self.pushButton_enter.clicked.connect(self.on_pushButton_enter_clicked)
        self.pushButton_quit.clicked.connect(QCoreApplication.instance().quit)

    def on_pushButton_enter_clicked(self):
        # Check nickName
        if self.lineEdit_account.text() != "admin":
            return

        # Check password
        if self.lineEdit_password.text() != "admin":
            return

        # Close the dialog and return 1 when checking
        self.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)

    dialog = LoginDialog()

    if  dialog.exec_()==QDialog.Accepted:
        the_window = MainWindow()
        the_window.show()
        sys.exit(app.exec_())

【讨论】:

    【解决方案2】:

    这里给出了一个更完整的示例,展示了如何编写登录对话框:


    但是,在您自己的示例中,您应该注意不必处理关闭事件,因为“X”按钮会自动 将对话框的结果设置为Rejected。相反,您只需在单击提交按钮时将结果设置为Accepted。然后您可以检查exec_() 的返回值,看看用户做了什么。

    这是您的脚本的重写:

    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
    
    class Login(QDialog):
        def __init__(self,parent=None):
            super(Login, self).__init__(parent)
    
            self.grid = QGridLayout(self)
            self.setGeometry(650, 350, 400, 150)
            self.setFixedSize(400, 150)
    
            self.UserLabels = QLabel(self)
            self.UserLabels.setText('Login Number:')
            self.grid.addWidget(self.UserLabels, 0, 0, 1, 1)
    
            self.textName = QLineEdit(self)
            self.grid.addWidget(self.textName, 0, 1, 1, 2)
    
            self.buttonLogin = QPushButton('Submit', self)
            self.buttonLogin.clicked.connect(self.accept)
            self.grid.addWidget(self.buttonLogin, 2, 0, 1, 3)
    
        def password(self):
            return self.textName.text()
    
    def handleLogin():
        result = None
        login = Login()
        while result is None:
            if login.exec_() == QDialog.Accepted:
                password = login.password()
                if password == '6':
                    result = True
            else:
                result = False
        return result
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        if handleLogin():
            print('logged in')
        else:
            print('cancelled')
    

    【讨论】:

    • 也可以覆盖exec_(),直接使用if super(Login, self).exec_(): return self.textName.text()返回密码,类似于QInputDialog静态方法。
    • @musicamante 是的,我只是想解释一下 OP 的代码出了什么问题,并展示了如何简化逻辑。我通常会写一个登录对话框something like this
    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多