Python 如何从 QtGui.QListWidget 获取当前项目的信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21566556/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a current Item's info from QtGui.QListWidget?
提问by alphanumeric
Created a QtGui.QListWidget list widget:
创建了一个 QtGui.QListWidget 列表小部件:
myListWidget = QtGui.QListWidget()
Populated this ListWidget with QListWidgetItem list items:
使用 QListWidgetItem 列表项填充此 ListWidget:
for word in ['cat', 'dog', 'bird']:
    list_item = QtGui.QListWidgetItem(word, myListWidget)
Now connect a function on list_item's left click:
现在在 list_item 的左键单击上连接一个函数:
def print_info():
    print myListWidget.currentItem().text()
myListWidget.currentItemChanged.connect(print_info)
As you see from my code all I am getting on a left click is a list_item's label name. But aside from a label name I would like to get a list_item's index number (order number as it is displayed in ListWidget). I would like to get as much info on left-clicked list_item as possible. I looked at dir(my_list_item). But I can't anything useful there ( other than already used my_list_item.text() method which returns a list_item's label name). Thanks in advance!
正如您从我的代码中看到的,我左键单击的所有内容都是 list_item 的标签名称。但除了标签名称之外,我还想获得一个 list_item 的索引号(在 ListWidget 中显示的订单号)。我想获得尽可能多的有关左键单击 list_item 的信息。我看着 dir(my_list_item)。但是我在那里没有任何有用的东西(除了已经使用的 my_list_item.text() 方法返回一个 list_item 的标签名称)。提前致谢!
采纳答案by ekhumoro
Use QListWidget.currentRowto get the index of the current item:
使用QListWidget.currentRow获取当前项的索引:
def print_info():
    print myListWidget.currentRow()
    print myListWidget.currentItem().text()
A QListWidgetItemdoes not know its own index: it's up to the list-widget to manage that.
一个QListWidgetItem不知道自己的索引:它是由列表窗口小部件来管理。
You should also note that currentItemChangedsends the current and previous items as arguments, so you could simplify to:
您还应该注意currentItemChanged将当前和上一个项目作为参数发送,因此您可以简化为:
def print_info(current, previous):
    print myListWidget.currentRow()
    print current.text()
    print current.isSelected()
    ...
回答by thecreator232
Well, I have listed some of the things you can display about the current item, if you want more than this then you should look through the PyQt Documentation. link
好吧,我已经列出了一些你可以显示的关于当前项目的内容,如果你想要更多,那么你应该查看 PyQt 文档。关联
 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)

