| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import sys
- from PyQt5.QtWidgets import (
- QMainWindow,
- QFormLayout,
- QLineEdit,
- QSpinBox,
- QComboBox,
- QWidget,
- QApplication,
- QLabel,
- QAction,
- QToolBar,
- QStatusBar,
- )
- class MyWindow(QMainWindow):
- def __init__(self):
- super().__init__()
- self.setWindowTitle('My App')
- layout = QFormLayout()
- # Dictionary to store the form data
- self.data = {
- "name": "Johnina Smith",
- "age": 10,
- "icecream": "Vanilla",
- }
- self.name = QLineEdit()
- self.name.setText(self.data["name"])
- self.name.textChanged.connect(self.handle_name_changed)
- self.age = QSpinBox()
- self.age.setRange(0, 200)
- self.age.setValue(self.data["age"])
- self.age.valueChanged.connect(self.handle_age_changed)
- self.icecream = QComboBox()
- self.icecream.addItems(["Vanilla", "Strawberry", "Chocolate"])
- self.icecream.setCurrentText(self.data["icecream"])
- self.icecream.currentTextChanged.connect(self.handle_icecream_changed)
- layout.addRow("Name", self.name)
- layout.addRow("Age", self.age)
- layout.addRow("Favorite icecream", self.icecream)
- # Empty label to show error message
- self.error = QLabel()
- layout.addWidget(self.error)
- toolbar = QToolBar("My main toolbar")
- widget = QWidget()
- widget.setLayout(layout)
- self.setCentralWidget(widget)
- toolbar.toggleViewAction().setEnabled(False)
- self.addToolBar(toolbar)
- button_action = QAction("Your button", self)
- button_action.setStatusTip("This is your button")
- button_action.triggered.connect(self.onMyToolBarButtonClick)
- button_action.setCheckable(True)
- toolbar.addAction(button_action)
- self.setStatusBar(QStatusBar(self))
- def handle_name_changed(self, name):
- self.data["name"] = name
- print(self.data)
- self.validate()
- def handle_age_changed(self, age):
- self.data["age"] = age
- print(self.data)
- self.validate()
- def handle_icecream_changed(self, icecream):
- self.data["icecream"] = icecream
- print(self.data)
- self.validate()
- def validate(self):
- if self.data["age"] > 10 and self.data["icecream"] == "Chocolate":
- self.error.setText(
- "People over 10 aren't allowed chocolate ice cream")
- return
- if self.data["age"] > 100:
- self.error.setText("Did you send a telegram?")
- return
- self.error.setText("")
- def onMyToolBarButtonClick(self, is_checked):
- print("click", is_checked)
- app = QApplication(sys.argv)
- window = MyWindow()
- window.show()
- sys.exit(app.exec_())
|