其他分享
首页 > 其他分享> > 第19天 | 28天学会PyQt5,列表选择,你选西施还是杨玉环?

第19天 | 28天学会PyQt5,列表选择,你选西施还是杨玉环?

作者:互联网

列表框QComboBox是一个集按钮和下拉选项于一体的控件,是提供给用户选择的一种机制。选项被放置在一个下拉列表中,绑定的事件,在用户选择之后触发。列表框比单选按钮占据较少的空间,当选项的数目相对少的时候,列表框是一个好的选择。

QComboBox控件常用的事件类型如下表所示:

事件类型

描述

Activated

用户选中一个下拉选项时触发事件

currentIndexChanged

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

highlighted

选中一个已经选中的下拉选项时,触发事件

列表框QComboBox常用的方法如下表所示:

方法

描述

addItem()

添加一个下拉选项

addItems()

添加多个下拉选项

currentText()

返回选中选项的文本

currentIndex()

返回选中项的索引,传给itemText(i)可获取对应的选项文本

count()

获取下拉选项集合中的数目

setItemText(int index,

text)

修改选项内容用方法

clear()

清空下拉选项集合中的所有选项

程序清单:combobox.py

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, 
  QVBoxLayout, QComboBox


# 继承QWidget
class ComboBoxWidget(QWidget):

    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # 生成QComboBox对象
        combobox = QComboBox(self)
        combobox.setFixedSize(160, 20)
        combobox.move(50, 50)
        # 添加单个项目
        combobox.addItem("西施")
        # 添加多个项目
        combobox.addItems(["貂蝉", "杨玉环", "王昭君"])
        # 选中一个下拉选项时触发
        combobox.activated.connect(self.activate)
        combobox.currentIndexChanged.connect(self.selectchange)
        combobox.highlighted.connect(self.highlighte)
        # 调整窗口大小
        self.resize(900, 500)
        # 窗口居中
        self.center()
        # 窗口标题
        self.setWindowTitle("列表框应用")
        # 显示窗口
        self.show()

    def activate(self):
        sender = self.sender()
        # currentText() 返回选中选项的文本
        print(sender.currentText())

    def selectchange(self, i):
        print(i)

    def highlighte(self):
        sender = self.sender()

        print(sender.currentText())

    # 实现居中
    def center(self):
        f = self.frameGeometry()
        c = QDesktopWidget().availableGeometry().center()
        f.moveCenter(c)
        self.move(f.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = ComboBoxWidget()
    sys.exit(app.exec_())

运行程序之后,弹出的窗口如下:

好了,列表选择的内容就说到这了,关注我,下一节更精彩。

今日头条:老陈说编程,到2021年国庆节,Python就全部分享完了,完整的课程有:
1.《12天搞定Python》
2.《16天搞定Python数据分析》
3.《10天搞定Python网络爬虫》
4. 《Django3.0项目实战》
5. 《25天学会Wxpython》
6. 《28天学会PyQt5》发布中
7. 《25天学会Seaborn数据分析》在csdn发布完了
8. 《3天搞定Pyecharts数据分析》国庆期间发布

标签:选项,__,sender,19,combobox,self,28,QComboBox,PyQt5
来源: https://blog.csdn.net/a_faint_hope/article/details/120539252