专业的编程技术博客社区

网站首页 > 博客文章 正文

6.8 PyQt5控件介绍【下拉框控件】-QComboBox

baijin 2024-10-24 08:48:57 博客文章 19 ℃ 0 评论

1.QComboBox简介

PyQt5中QComboBox控件用来创建下拉框选项的控件。呈现下拉选项列表数据供用户来选择。

2.QComboBox案例

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QLabel, QComboBox

class QComBoxDemo(QWidget):
    def __init__(self):
        super(QComBoxDemo, self).__init__()
        self.init_ui()

    def init_ui(self):
        h_layout = QHBoxLayout(self)
        self.resize(300, 200)

        self.label = QLabel('请选择')
        self.com_box = QComboBox()
        self.com_box.addItem('Python')  # 下拉框添加选项,添加单个选项
        self.com_box.addItems(['Java', 'C++', 'Go', 'C#'])  # 批量添加选项,支持列表方式
        self.com_box.currentIndexChanged.connect(self.select_changed)  # 绑定索引变化事件,此方法给事件自动传入一个变化的索引参数

        h_layout.addWidget(self.label)
        h_layout.addWidget(self.com_box)

    def select_changed(self, i):
        self.label.setText(self.com_box.currentText())  # 设置label内容,currentText获取当前下拉框选中的内容
        print(f'当前选择,索引:{i} => {self.com_box.itemText(i)}')  # itemText(i)按索引获取下拉框选项文本
        for n in range(self.com_box.count()):  # count()获取所有索引
            print(f'索引:{n} => {self.com_box.itemText(n)}')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QComBoxDemo()
    w.show()
    sys.exit(app.exec())

3.运行结果

4.常用方法

方法

描述

addItem(text)

添加下拉选项

addItems(list)

从列表中添加选项

itemText(index)

获取指定索引的选项文本

setItemText(index,text)

修改指定索引的选项文本内容

setMaxCount(int)

设置最大选项数量

setMaxVisibleItems(int count)

设置最大可见选项数

maxVisibleItems()

返回最大可见选项数

currentText()

返回选中的选项文本

currentIndex()

返回当前选中的项目的索引

setCurrentIndex(index)

设置指定索引为当前选项

removeItem()

删除指定索引的选项

isEditable()

返回是否可编辑

setEditable(bool)

设置是否可编辑

findText(text: str, flags: [Qt.MatchFlags, Qt.MatchFlag] )

用于在组合框中查找指定的文本,并返回该文本对应的索引值。如果未找到指定的文本,则返回 -1。 常见Qt.MatchFlags 列表: Qt.MatchExactly:完全匹配 Qt.MatchContains:文本包含要查找的字符串 Qt.MatchStartsWith:查找的文本以指定字符串开头 Qt.MatchEndsWith:查找的文本以指定字符串结尾 Qt.MatchCaseSensitive:区分大小写进行匹配 Qt.MatchRegExp:将查找的字符串作为正则表达式进行匹配 Qt.MatchWildcard:允许使用通配符进行匹配(如 * 和 ?) Qt.MatchFixedString:查找时将字符串视为固定字符串,不进行正则表达式或通配符匹配 Qt.MatchRecursive:递归匹配,主要用于查找树形结构中的项

setView()

设置选项的视图: QListView():列表视图 QTableView():表格视图 QTreeView():树视图

insertItem(index: int, text: str)

在指定位置插入一个项目

insertItems(index: int, texts: Iterable[str])

在指定位置批量插入项目

view()

获取选项的视图

count()

返回下拉框中的总选项数目

clear()

情况所有项目

5.常用信号

方法

描述

currentIndexChanged(int index)

当下拉选项的索引发生改变时触发

currentTextChanged(str text)

当前项的文本发生变化时,触发此信号

highlighted(int index)

鼠标移动到下拉选项时触发

activated(int index)

当一个选项被激活时触发信号

editTextChanged(str text)

当可编辑选项的文本发生变化时触发



本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表