ฉันทำงานกับแอปพลิเคชัน PyQt4 และนี่คือสิ่งที่ฉันมี:
import sys
from PyQt4 import QtGui, QtCore
class PasswordPrompt(QtGui.QWidget):
def __init__(self):
super(PasswordPrompt, self).__init__()
self.initUi()
def initUi(self):
self.setFixedSize(500, 75)
self.setWindowTitle('Please enter the password...')
self.prompt = QtGui.QLineEdit(self)
self.btn = QtGui.QPushButton('Enter', self)
self.btn.clicked.connect(self.btnClicked)
self.hbox = QtGui.QHBoxLayout()
self.hbox.addWidget(self.prompt)
self.hbox.addWidget(self.btn)
self.vbox = QtGui.QVBoxLayout()
self.vbox.addLayout(self.hbox)
self.vbox2 = QtGui.QVBoxLayout()
self.vbox2.addSpacing(300)
self.hbox2 = QtGui.QHBoxLayout()
self.hbox2.addSpacing(150)
self.vbox2.addLayout(self.hbox2)
self.vbox.addLayout(self.vbox2)
self.setLayout(self.vbox)
self.center()
self.show()
def btnClicked(self):
pw = self.prompt.text()
if pw == "password":
print("Permission granted!")
self.close()
mw = MainWindow()
else:
print("Permissed denied!")
self.prompt.clear()
self.warningText = QtGui.QLabel('That is the wrong password!', self)
self.hbox2.addWidget(self.warningText)
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.initUi()
def initUi(self):
self.setWindowTitle('Main Menu')
self.setFixedSize(1000, 800)
self.show()
def main():
application = QtGui.QApplication(sys.argv)
p = PasswordPrompt()
sys.exit(application.exec())
if __name__=='__main__':
main()
ปัญหาของฉันเกิดขึ้นเมื่อฉันพยายามสร้าง mw ของคลาส Main Window ด้วยเหตุผลบางอย่าง มันจะทำ MainWindow.initui() แล้วปิดทันที ฉันคิดว่ามันเกี่ยวข้องกับฟังก์ชัน main() และวัตถุ QApplication วิธีที่ดีที่สุดในการเขียนโค้ดหลายหน้าต่างและแก้ไขปัญหานี้คืออะไร เดิมทีฉันกำลังจะสร้างคลาสต่อหน้าต่าง: passwordPrompt, MainMenu ฯลฯ จากนั้นสร้างอินสแตนซ์ของแต่ละคลาสเพื่อโหลดหน้าต่างใหม่ แต่อย่างที่คุณเห็นว่ามันไม่ทำงาน