windows_1.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import sys
  2. from random import randint
  3. from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QWidget, QInputDialog, QLineEdit, QLabel
  4. class AnotherWindow(QWidget):
  5. """
  6. This "window" is a Qwidget. If it has no parent, it
  7. will appear as a free-floating window.
  8. """
  9. def __init__(self):
  10. super().__init__()
  11. layout = QVBoxLayout()
  12. self.label = QLabel("Another Window %d" % randint(0, 100))
  13. layout.addWidget(self.label)
  14. self.setLayout(layout)
  15. class MainWindow(QMainWindow):
  16. def __init__(self):
  17. super().__init__()
  18. self.w = None # No external window yet
  19. self.setWindowTitle("My App")
  20. layout = QVBoxLayout()
  21. self.button = QPushButton("Press me for a dialog!")
  22. self.button.clicked.connect(self.show_new_window)
  23. layout.addWidget(self.button)
  24. container = QWidget()
  25. container.setLayout(layout)
  26. self.setCentralWidget(container)
  27. def show_new_window(self, is_checked):
  28. print("Button clicked!", is_checked)
  29. if self.w is None:
  30. self.w = AnotherWindow()
  31. self.w.show()
  32. else:
  33. self.w.close()
  34. self.w = None # Discard reference, close window.
  35. app = QApplication(sys.argv)
  36. window = MainWindow()
  37. window.show()
  38. app.exec_()