pyqt5 如何读取qcombobox 的全部项

29 篇文章 0 订阅

在 PyQt5 中,可以使用 QComboBox 的方法 count()itemText() 来读取 QComboBox 的全部项。count() 方法用于获取 QComboBox 中项的数量,而 itemText(index) 方法用于获取指定索引位置的项的文本。

以下是一个示例代码,展示如何读取 QComboBox 的全部项:

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


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

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("QComboBox Example")
        self.setGeometry(100, 100, 300, 150)

        layout = QVBoxLayout()

        self.combo_box = QComboBox()
        self.combo_box.addItem("Item 1")
        self.combo_box.addItem("Item 2")
        self.combo_box.addItem("Item 3")
        self.combo_box.addItem("Item 4")

        layout.addWidget(self.combo_box)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        self.show()

        # Read and print all items in the QComboBox
        self.read_combobox_items()

    def read_combobox_items(self):
        # Get the number of items in the QComboBox
        num_items = self.combo_box.count()

        # Read and print all items
        for index in range(num_items):
            item_text = self.combo_box.itemText(index)
            print(f"Item {index + 1}: {item_text}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

运行这个示例代码,你将看到在 QComboBox 中添加了四个项,并且在控制台输出中显示了所有项的文本。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值