问:
I nearly finished my application, when the customer asked if I could implement some kind of login form on application startup.
So far I have designed the UI, and tinkered about the actual execution. Username and password are irrelevant for now.
我最近完成了程序,而客户要求在程序启动时,实现一个登录窗体。
因此我设计了UI,并且粗略的实现了执行。这里,用户名和密码是不相干的。
Login form is shown. If correct username and password are entered, then main window is shown and working. But, the login form stays active, and if I close it, the main window will also close.
登录窗体显示。如果输入正确的用户名和密码。主窗体显示,而且工作。但是登录窗口仍然显示,如果关闭它,则主窗体也关闭了。
class Login(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=Ui_dlgLogovanje()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.buttonLogin, QtCore.SIGNAL("clicked()"), self.doLogin)
def doLogin(self):
name = str(self.ui.lineKorisnik.text())
passwd = str(self.ui.lineSifra.text())
if name == "john" and passwd =="doe":
self.runIt()
else:
QtGui.QMessageBox.warning(self, 'Greška',
"Bad user or password", QtGui.QMessageBox.Ok)
def runIt(self):
myprogram = Window()
myprogram.showMaximized() #myprogram is
class Window(QtGui.QMainWindow):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
if __name__=="__main__":
program = QtGui.QApplication(sys.argv)
myprogram = Window()
if Login().exec_() == QtGui.QDialog.Accepted:
sys.exit(program.exec_())
答:
A QDialog has its own event loop, so it can be run separately from the main application.
So you just need to check the dialog's return code to decide whether the main application should be run or not.
QDialgo有自己事件循环,所以它可以独立于主程序运行。
所以你需要检查dialog的返回值,以决定是否运行主程序。
from PyQt4 import QtGui
class Login(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.textName = QtGui.QLineEdit(self)
self.textPass = QtGui.QLineEdit(self)
self.buttonLogin = QtGui.QPushButton('Login', self)
self.buttonLogin.clicked.connect(self.handleLogin)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.textName)
layout.addWidget(self.textPass)
layout.addWidget(self.buttonLogin)
def handleLogin(self):
if (self.textName.text() == 'foo' and
self.textPass.text() == 'bar'):
self.accept() #关键
else:
QtGui.QMessageBox.warning(
self, 'Error', 'Bad user or password')
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
if Login().exec_() == QtGui.QDialog.Accepted:
window = Window()
window.show()
sys.exit(app.exec_())