【问题标题】:How to get a current Item's info from QtGui.QListWidget?如何从 QtGui.QListWidget 获取当前项目的信息?
【发布时间】:2014-03-01 06:04:03
【问题描述】:

创建了一个 QtGui.QListWidget 列表小部件:

myListWidget = QtGui.QListWidget()

使用 QListWidgetItem 列表项填充此 ListWidget:

for word in ['cat', 'dog', 'bird']:
    list_item = QtGui.QListWidgetItem(word, myListWidget)

现在在list_item的左键上连接一个函数:

def print_info():
    print myListWidget.currentItem().text()


myListWidget.currentItemChanged.connect(print_info)

正如您从我的代码中看到的,我在左键单击时得到的只是一个 list_item 的标签名称。但除了标签名称之外,我还想获得一个 list_item 的索引号(在 ListWidget 中显示的订单号)。我想尽可能多地获取有关左键单击的 list_item 的信息。我查看了目录(my_list_item)。但是我在那里没有任何用处(除了已经使用的返回 list_item 的标签名称的 my_list_item.text() 方法)。提前致谢!

【问题讨论】:

    标签: python listview pyqt listviewitem


    【解决方案1】:

    使用QListWidget.currentRow获取当前项的索引:

    def print_info():
        print myListWidget.currentRow()
        print myListWidget.currentItem().text()
    

    QListWidgetItem 不知道自己的索引:由列表小部件来管理。

    您还应该注意,currentItemChanged 将当前和以前的项目作为参数发送,因此您可以简化为:

    def print_info(current, previous):
        print myListWidget.currentRow()
        print current.text()
        print current.isSelected()
        ...
    

    【讨论】:

    • 多选怎么用?
    • @laserpython。 QListWidget.selectedItems.
    • @ekhumoro 我的意思是你如何获得 selectedItems 的索引? selectedItems 只返回文本值,而不是索引...有 currentRow() 但没有 currentRows()
    • 请阅读我链接到的文档。 selectedItems()方法返回项目列表,而不是文本。当前只能有一项,因此currentRows() 没有意义。要从项目中获取 QModelIndex,请使用 QListWidget.indexFromItem
    【解决方案2】:

    好吧,我已经列出了一些你可以显示的关于当前项目的内容,如果你想要更多,那么你应该查看 PyQt 文档。 link

     def print_info():
        print myListWidget.currentItem().text()
        print myListWidget.row(myListWidget.currentItem())
        print myListWidget.checkState()  # if it is a checkable item
        print myListWidget.currentItem().toolTip().toString()
        print myListWidget.currentItem().whatsThis().toString()
    
    myListWidget.currentItemChanged.connect(print_info)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多