PySide2基础篇(七)——QComboBox运用

PySide2基础篇(七)——QComboBox运用

前言:
阅读这篇文章我能学到什么?
  组合框是进行选择性输入常用的控件,这篇文章将介绍它的基本用法。

——如果你觉得这是一篇不错的博文,希望你能给一个小小的赞,感谢您的支持。

1 创建一个组合框

  通过类QComboBox创建一个组合框对象,addItem()函数用于给组合框添加项。
  代码示例:

from PySide2.QtWidgets import QApplication, QMainWindow, QComboBox

app = QApplication([])

MainWindow = QMainWindow()

ComboBox = QComboBox(MainWindow)
ComboBox.addItem("1")
ComboBox.addItem("2")
ComboBox.addItem("3")

MainWindow.show()
app.exec_()

  运行结果:
在这里插入图片描述

2 对组合框项的操作

  一个组合框可以含有多个项供选择,我们可以对这些项进行添加、删除、修改等操作。

2.1 清空组合框

  清空组合框的项很简单,只需要调用Clear()函数即可删除组合框所有的项。
  代码示例:

from PySide2.QtWidgets import QApplication, QMainWindow, QComboBox

app = QApplication([])

MainWindow = QMainWindow()

ComboBox = QComboBox(MainWindow)
ComboBox.addItem("1")
ComboBox.addItem("2")
ComboBox.addItem("3")
ComboBox.clear()                        #清空组合框项

MainWindow.show()
app.exec_()

  运行结果:
在这里插入图片描述

2.2 插入组合框

  有时候需要在某两项组合框之间插入一项,可以使用InsertItem()函数进行插入新项。
  代码示例:

from PySide2.QtWidgets import QApplication, QMainWindow, QComboBox

app = QApplication([])

MainWindow = QMainWindow()

ComboBox = QComboBox(MainWindow)
ComboBox.addItem("1")
ComboBox.addItem("2")
ComboBox.addItem("3")
ComboBox.insertItem(1, "0")             #索引1后插入项

MainWindow.show()
app.exec_()

  运行结果:
在这里插入图片描述

2.3 失能组合框

  禁用组合框可以使用setEnabled()函数。
  代码示例:

from PySide2.QtWidgets import QApplication, QMainWindow, QComboBox

app = QApplication([])

MainWindow = QMainWindow()

ComboBox = QComboBox(MainWindow)
ComboBox.addItem("1")
ComboBox.addItem("2")
ComboBox.addItem("3")
ComboBox.setEnabled(False)                  #失能组合框

MainWindow.show()
app.exec_()

  运行结果:
在这里插入图片描述

3 组合框的选择

  通常我们选择组合框的某一项之后,还会有个点击按钮确定的动作。currentIndex()函数用于获取当前选中项的索引(第一项索引为0),currentText()函数用于获取当前选中项的文本。另外可以使用在函数addItem()中添加参数给项设置图标。
  代码示例:

from PySide2.QtWidgets import QApplication, QMainWindow, QComboBox, QPushButton
from PySide2.QtCore import Slot
from PySide2.QtGui import QIcon

app = QApplication([])

MainWindow = QMainWindow()

PushButton = QPushButton(MainWindow)
PushButton.setText("按钮")
PushButton.move(90, 0)
PushButton.resize(50, 20)

Icon = QIcon(".\png\PNG.png")

ComboBox = QComboBox(MainWindow)
ComboBox.move(0, 0)
ComboBox.resize(80, 20)
ComboBox.addItem(Icon, "Item1")
ComboBox.addItem(Icon, "Item2")
ComboBox.addItem(Icon, "Item3")

@Slot()
def PressButton():
    print(ComboBox.currentIndex(), ComboBox.currentText())

PushButton.clicked.connect(PressButton)

MainWindow.show()
app.exec_()

  运行结果:
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值