layout_10.py 2.7 KB

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