前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PySide6 GUI 编程(9):QComboBox的使用

PySide6 GUI 编程(9):QComboBox的使用

原创
作者头像
bowenerchen
修改2024-07-22 09:26:59
1971
修改2024-07-22 09:26:59
举报
文章被收录于专栏:编码视界

基本使用

静态选项

代码语言:python
代码运行次数:0
复制
from datetime import datetime

from PySide6.QtWidgets import QApplication, QComboBox, QLabel, QMainWindow, QVBoxLayout, QWidget


class MyCombobox(QMainWindow):
    def __init__(self):
        super().__init__()

        self.my_label_item = QLabel()
        self.my_label_index = QLabel()
        self.current_time = QLabel()

        self.my_combobox = QComboBox()
        self.my_combobox.addItems(['aes-cbc', 'aes-gcm', 'aes-ofb', 'rsa-2048', 'rsa-4096', 'ecc'])
        self.my_combobox.currentTextChanged.connect(self.text_changed)
        self.my_combobox.currentIndexChanged.connect(self.index_changed)

        self.my_label_item.setText(
            'now, current item: {}'.format(
                self.my_combobox.currentText()))

        self.my_label_index.setText(
            'now, current index: {}'.format(
                self.my_combobox.currentIndex()))

        self.current_time.setText(
            datetime.now().strftime('%Y-%m-%d %H:%M:%S %z')
        )

        layout = QVBoxLayout()
        layout.addWidget(self.my_label_item)
        layout.addWidget(self.my_label_index)
        layout.addWidget(self.current_time)
        layout.addWidget(self.my_combobox)

        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)

    def text_changed(self, data: str):
        self.my_label_item.setText('chose item: {}'.format(data))

    def index_changed(self, index: int):
        self.my_label_index.setText('chose index: {}'.format(index))
        self.current_time.setText(
            datetime.now().strftime('%Y-%m-%d %H:%M:%S %z')
        )


if __name__ == '__main__':
    app = QApplication()
    ins = MyCombobox()
    ins.show()
    app.exec()

运行效果

静态选项运行效果
静态选项运行效果

编辑列表

代码语言:python
代码运行次数:0
复制
from datetime import datetime

from PySide6.QtWidgets import QApplication, QComboBox, QLabel, QMainWindow, QVBoxLayout, QWidget


class MyCombobox(QMainWindow):
    def __init__(self):
        super().__init__()

        self.my_label_item = QLabel()
        self.my_label_index = QLabel()
        self.current_time = QLabel()

        self.my_combobox = QComboBox()
        self.my_combobox.addItems(['aes-cbc', 'aes-gcm', 'aes-ofb', 'rsa-2048', 'rsa-4096', 'ecc'])
        self.my_combobox.currentTextChanged.connect(self.text_changed)
        self.my_combobox.currentIndexChanged.connect(self.index_changed)
        self.my_combobox.editTextChanged.connect(self.edit_text_changed)

        self.my_combobox.setMaxCount(100)  # 可以存储的最大项数
        self.my_combobox.setMaxVisibleItems(10)  # 每次下拉时最大的展示项数

        # 当设置为True时,用户可以在下拉列表的文本框中输入文本
        # 而不仅仅是从列表中选择现有的项
        # 这允许用户输入一个可能不在当前列表中的值
        self.my_combobox.setEditable(True)

        # 无论 QComboBox 是否可编辑,都可以使用此方法设置当前显示在编辑框中的文本
        # 使用 setEditText 可以快速设置 QComboBox 显示的文本,而不需要用户从列表中选择
        self.my_combobox.setEditText('edit text here')

        self.my_label_item.setText(
            'now, current item: {}'.format(
                self.my_combobox.currentText()))

        self.my_label_index.setText(
            'now, current index: {}'.format(
                self.my_combobox.currentIndex()))

        self.current_time.setText(
            datetime.now().strftime('%Y-%m-%d %H:%M:%S %z')
        )

        layout = QVBoxLayout()
        layout.addWidget(self.my_label_item)
        layout.addWidget(self.my_label_index)
        layout.addWidget(self.current_time)
        layout.addWidget(self.my_combobox)

        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)

    def text_changed(self, data: str):
        self.my_label_item.setText('chose item: {}'.format(data))

    def index_changed(self, index: int):
        self.my_label_index.setText('chose index: {}'.format(index))
        self.current_time.setText(
            datetime.now().strftime('%Y-%m-%d %H:%M:%S %z')
        )

    def edit_text_changed(self, data: str):
        self.my_label_item.setText('edit text changed to: {}'.format(data))


if __name__ == '__main__':
    app = QApplication()
    ins = MyCombobox()
    ins.show()
    app.exec()

运行效果

可编辑的列表
可编辑的列表

macOS 上 Placeholder 失效问题

在 macOS 系统上,QComboBox 的 setPlaceholderText 方法可能不会按预期工作,因为 macOS 的用户界面指南通常不支持在组合框中使用占位符文本。

核心代码设置
核心代码设置

测试代码

代码语言:python
代码运行次数:0
复制
from PySide6.QtWidgets import QApplication, QComboBox, QVBoxLayout, QWidget


def main():
    app = QApplication([])

    # 创建一个QWidget作为主窗口
    window = QWidget()
    layout = QVBoxLayout(window)

    # 创建一个QComboBox实例
    comboBox = QComboBox()
    comboBox.setEditable(True)  # 使下拉列表可编辑

    # 添加一些选项
    comboBox.addItems(["选项1", "选项2", "选项3"])

    # 设置占位符文本
    # 在 macOS 系统上,QComboBox 的 setPlaceholderText 方法可能不会按预期工作
    # 因为 macOS 的用户界面指南通常不支持在组合框中使用占位符文本
    # Qt 的某些版本可能没有完全支持在 macOS 上为 QComboBox 显示占位符文本
    comboBox.setPlaceholderText("请选择或输入一个选项")

    # 将QComboBox添加到布局中
    layout.addWidget(comboBox)

    # 显示窗口
    window.show()

    # 启动应用程序
    app.exec()


if __name__ == "__main__":
    main()

运行效果

可编辑的列表不展示占位符
可编辑的列表不展示占位符

当不设置可编辑与默认列表元素时

注释掉可编辑能力
注释掉可编辑能力
不可下拉的列表
不可下拉的列表

当不可编辑且仅有默认元素时

仅有默认元素
仅有默认元素
仅展示默认元素
仅展示默认元素

QComboBox 插入规则设置

插入规则的可选值

代码语言:python
代码运行次数:0
复制
    class InsertPolicy(enum.Enum):

        NoInsert                 : QComboBox.InsertPolicy = ... # 0x0
        InsertAtTop              : QComboBox.InsertPolicy = ... # 0x1
        InsertAtCurrent          : QComboBox.InsertPolicy = ... # 0x2
        InsertAtBottom           : QComboBox.InsertPolicy = ... # 0x3
        InsertAfterCurrent       : QComboBox.InsertPolicy = ... # 0x4
        InsertBeforeCurrent      : QComboBox.InsertPolicy = ... # 0x5
        InsertAlphabetically     : QComboBox.InsertPolicy = ... # 0x6

按照字母顺序自动排序的插入规则

代码语言:python
代码运行次数:0
复制
from PySide6.QtWidgets import QApplication, QComboBox, QMainWindow


class MyComboBox(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('ComboBox设置写入策略')

        my_box = QComboBox()
        my_box.addItems(['a', 'b', 'c'])
        my_box.setEditable(True)
        my_box.setMaxCount(26)
        my_box.setInsertPolicy(QComboBox.InsertPolicy.InsertAlphabetically)
        self.setCentralWidget(my_box)


if __name__ == '__main__':
    app = QApplication()
    ins = MyComboBox()
    ins.show()
    app.exec()

运行效果

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本使用
    • 静态选项
      • 运行效果
        • 编辑列表
          • 运行效果
          • macOS 上 Placeholder 失效问题
            • 测试代码
              • 运行效果
                • 当不设置可编辑与默认列表元素时
                  • 当不可编辑且仅有默认元素时
                  • QComboBox 插入规则设置
                    • 插入规则的可选值
                      • 按照字母顺序自动排序的插入规则
                        • 运行效果
                        领券
                        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档