You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行时获取QListWidget中复合组件内QPushButton的文本?

获取QListWidget项中QPushButton的文本

要获取每个列表项里按钮的文本,核心是先拿到每个项对应的自定义widget(item_widget),再通过widget的findChild方法定位按钮,具体步骤如下:

  1. 遍历QListWidget的所有项,通过count()获取总项数,逐个索引访问。
  2. 对每个项,调用itemWidget()获取你之前设置的复合widget(item_widget),这个widget是QWidget子类,支持findChild/findChildren方法。
  3. 在widget中查找QPushButton实例,再调用text()获取按钮文本。

示例代码

def get_list_button_texts(self):
    button_texts = []
    # 遍历所有列表项
    for idx in range(self.myList.count()):
        list_item = self.myList.item(idx)
        # 获取项对应的自定义widget
        item_widget = self.myList.itemWidget(list_item)
        if not item_widget:
            continue
        # 查找widget内的QPushButton
        target_button = item_widget.findChild(QtWidgets.QPushButton)
        if target_button:
            button_texts.append(target_button.text())
    return button_texts

优化建议

如果你的复合widget里可能存在多个QPushButton,可以给目标按钮设置唯一标识,避免误匹配:

# 创建按钮时设置objectName
line_push_button = QtWidgets.QPushButton("text I want to get")
line_push_button.setObjectName("list_item_action_button")

# 查找时指定名称
target_button = item_widget.findChild(QtWidgets.QPushButton, "list_item_action_button")

内容的提问来源于stack exchange,提问作者Ferex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:33:11