layout_10.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import sys
  2. from PyQt5.QtWidgets import (
  3. QMainWindow, QFormLayout,
  4. QLineEdit, QSpinBox,
  5. QComboBox, QWidget,
  6. QApplication, QLabel,
  7. QAction, QToolBar,
  8. QStatusBar,
  9. )
  10. class MyWindow(QMainWindow):
  11. def __init__(self):
  12. super().__init__()
  13. self.setWindowTitle('My App')
  14. layout = QFormLayout()
  15. # Dictionary to store the form data
  16. self.data = {
  17. "name": "Johnina Smith",
  18. "age": 10,
  19. "icecream": "Vanilla",
  20. }
  21. self.name = QLineEdit()
  22. self.name.setText(self.data["name"])
  23. self.name.textChanged.connect(self.handle_name_changed)
  24. self.age = QSpinBox()
  25. self.age.setRange(0, 200)
  26. self.age.setValue(self.data["age"])
  27. self.age.valueChanged.connect(self.handle_age_changed)
  28. self.icecream = QComboBox()
  29. self.icecream.addItems(["Vanilla", "Strawberry", "Chocolate"])
  30. self.icecream.setCurrentText(self.data["icecream"])
  31. self.icecream.currentTextChanged.connect(self.handle_icecream_changed)
  32. layout.addRow("Name", self.name)
  33. layout.addRow("Age", self.age)
  34. layout.addRow("Favorite icecream", self.icecream)
  35. # Empty label to show error message
  36. self.error = QLabel()
  37. layout.addWidget(self.error)
  38. toolbar = QToolBar("My main toolbar")
  39. widget = QWidget()
  40. widget.setLayout(layout)
  41. self.setCentralWidget(widget)
  42. toolbar.toggleViewAction().setEnabled(False)
  43. self.addToolBar(toolbar)
  44. button_action = QAction("Your button", self)
  45. button_action.setStatusTip("This is your button")
  46. button_action.triggered.connect(self.onMyToolBarButtonClick)
  47. button_action.setCheckable(True)
  48. toolbar.addAction(button_action)
  49. self.setStatusBar(QStatusBar(self))
  50. def handle_name_changed(self, name):
  51. self.data["name"] = name
  52. print(self.data)
  53. self.validate()
  54. def handle_age_changed(self, age):
  55. self.data["age"] = age
  56. print(self.data)
  57. self.validate()
  58. def handle_icecream_changed(self, icecream):
  59. self.data["icecream"] = icecream
  60. print(self.data)
  61. self.validate()
  62. def validate(self):
  63. if self.data["age"] > 10 and self.data["icecream"] == "Chocolate":
  64. self.error.setText("People over 10 aren't allowed chocolate ice cream")
  65. return
  66. if self.data["age"] > 100:
  67. self.error.setText("Did you send a telegram?")
  68. return
  69. self.error.setText("")
  70. def onMyToolBarButtonClick(self, is_checked):
  71. print("click", is_checked)
  72. app = QApplication(sys.argv)
  73. window = MyWindow()
  74. window.show()
  75. sys.exit(app.exec_())