Guest User

Untitled

a guest
Jul 30th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. How to communicate or switch between two windows in PyQt4..?
  2. class MainWindow():
  3.  
  4. def login():
  5. loginDialog = LoginDialog()
  6.  
  7. # this is modal. wait for it to close
  8. if loginDialog.exec_():
  9. # dialog was accepted. check its values and maybe:
  10. self.show()
  11.  
  12. else:
  13. # maybe reshow the login dialog if they rejected it?
  14. loginDialog.exec_()
  15.  
  16.  
  17. if __name__ == "__main__":
  18.  
  19. app = QApp
  20. win = MainWindow()
  21. win.login()
  22. app.exec_()
  23.  
  24. import sys
  25. from PyQt4 import QtGui, QtCore
  26.  
  27. class LoginDialog(QtGui.QDialog):
  28. def __init__(self, parent=None):
  29. super(LoginDialog, self).__init__(parent)
  30.  
  31. self.username = QtGui.QLineEdit()
  32. self.password = QtGui.QLineEdit()
  33. loginLayout = QtGui.QFormLayout()
  34. loginLayout.addRow("Username", self.username)
  35. loginLayout.addRow("Password", self.password)
  36.  
  37. self.buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
  38. self.buttons.accepted.connect(self.check)
  39. self.buttons.rejected.connect(self.reject)
  40.  
  41. layout = QtGui.QVBoxLayout()
  42. layout.addLayout(loginLayout)
  43. layout.addWidget(self.buttons)
  44. self.setLayout(layout)
  45.  
  46. def check(self):
  47. if str(self.password.text()) == "12345": # do actual login check
  48. self.accept()
  49. else:
  50. pass # or inform the user about bad username/password
  51.  
  52.  
  53. class MainWindow(QtGui.QMainWindow):
  54. def __init__(self, parent=None):
  55. super(MainWindow, self).__init__(parent)
  56.  
  57. self.label = QtGui.QLabel()
  58. self.setCentralWidget(self.label)
  59.  
  60. def setUsername(self, username):
  61. # do whatever you want with the username
  62. self.username = username
  63. self.label.setText("Username entered: %s" % self.username)
  64.  
  65.  
  66. if __name__ == "__main__":
  67. app = QtGui.QApplication(sys.argv)
  68.  
  69. login = LoginDialog()
  70. if not login.exec_(): # 'reject': user pressed 'Cancel', so quit
  71. sys.exit(-1)
  72.  
  73. # 'accept': continue
  74. main = MainWindow()
  75. main.setUsername(login.username.text()) # get the username, and supply it to main window
  76. main.show()
  77.  
  78. sys.exit(app.exec_())
Add Comment
Please, Sign In to add comment