PySide6 GUI 编程(21):QFormLayout的简单用法

2024-07-30 21:56:19 浏览数 (1)

示例代码

代码语言:python代码运行次数:0复制
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QApplication, QComboBox, QFormLayout, QLabel, QLineEdit, QMainWindow, QPushButton, QSpinBox, QWidget


class MyFormWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('FormLayout')
        self.form_layout = QFormLayout()
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText('input your name')
        self.name_input.returnPressed.connect(self.handle_name)
        self.color = QComboBox()
        self.color.addItems(QColor.colorNames()[:5])
        self.color.currentTextChanged.connect(self.handle_color)
        self.age = QSpinBox()
        self.age.setRange(18, 25)
        self.age.valueChanged.connect(self.handle_age)
        self.msg_label = QLabel()
        self.button = QPushButton('Confirm')
        self.button.clicked.connect(self.handle_button)
        self.form_layout.addRow('Name', self.name_input)
        self.form_layout.addRow('Color', self.color)
        self.form_layout.addRow('Age', self.age)
        self.form_layout.addRow(self.msg_label)
        self.form_layout.addRow(self.button)

        container = QWidget()
        container.setLayout(self.form_layout)
        self.setCentralWidget(container)

    def handle_name(self):
        if not str.isalnum(self.name_input.text()):
            self.msg_label.setText(f'invalid name: {self.name_input.text()}, should be alpha and numbers')
        else:
            self.name_input.setEnabled(False)

    def handle_color(self, color_name: str):
        self.msg_label.setText(f'now you chose color: {color_name}')
        self.color.setEnabled(False)

    def handle_age(self, age: int):
        self.msg_label.setText(f'now you chose age to: {age}')
        self.age.setEnabled(False)

    def handle_button(self):
        self.name_input.setEnabled(False)
        self.color.setEnabled(False)
        self.age.setEnabled(False)
        if len(self.name_input.text()) <= 0 or not str.isalnum(self.name_input.text()):
            self.msg_label.setText('invalid name')
            self.name_input.setEnabled(True)
            self.color.setEnabled(True)
            self.age.setEnabled(True)
            return
        self.msg_label.setText(
            f'Your Name: {self.name_input.text()}, '
            f'Your Color: {self.color.currentText()}, '
            f'Your Age: {self.age.value()}')


if __name__ == '__main__':
    app = QApplication()
    ins = MyFormWidget()
    ins.show()
    app.exec()
表单样式的代码结构表单样式的代码结构

运行效果

样式效果样式效果
表单样式提交演示表单样式提交演示

0 人点赞