问题描述
创建了一个QtGui.QListWidget列表小部件:
Created a QtGui.QListWidget list widget:
myListWidget = QtGui.QListWidget()
使用QListWidgetItem列表项填充此ListWidget:
Populated this ListWidget with QListWidgetItem list items:
for word in ['cat', 'dog', 'bird']:
list_item = QtGui.QListWidgetItem(word, myListWidget)
现在在list_item的左键单击上连接一个函数:
Now connect a function on list_item's left click:
def print_info():
print myListWidget.currentItem().text()
myListWidget.currentItemChanged.connect(print_info)
从我的代码中可以看到,我左键单击的只是list_item的标签名称.但是除了标签名称之外,我还想获取一个list_item的索引号(在ListWidget中显示的订单号).我想获得有关左击list_item的尽可能多的信息.我看着目录(my_list_item).但是我在那里没有任何用处(除了已经使用过的my_list_item.text()方法,该方法返回list_item的标签名称).提前致谢!
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!
推荐答案
使用 QListWidget.currentRow 获取当前项目的索引:
Use QListWidget.currentRow to get the index of the current item:
def print_info():
print myListWidget.currentRow()
print myListWidget.currentItem().text()
QListWidgetItem 不知道它自己的索引:由列表决定-widget来进行管理.
A QListWidgetItem does not know its own index: it's up to the list-widget to manage that.
您还应该注意, currentItemChanged 发送当前和之前的项目作为参数,因此您可以简化为:
You should also note that currentItemChanged sends the current and previous items as arguments, so you could simplify to:
def print_info(current, previous):
print myListWidget.currentRow()
print current.text()
print current.isSelected()
...
这篇关于如何从QtGui.QListWidget获取当前商品的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!