目的是在用户单击列表上的项目时检测项目索引。
示例:
A
B
C
D
E
如果用户单击C,那么我想从list()
中检索该索引号。
试图直接打印出项目变量,但我在命令提示符下得到了此输出:
[<PyQt5.QtCore.QModelIndex object at 0x0416CA70>]
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtGui import QBrush, QColor
class Widget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
lay = QtWidgets.QVBoxLayout(self)
self.listView = QtWidgets.QListView()
self.label = QtWidgets.QLabel("Please Select item in the QListView")
lay.addWidget(self.listView)
lay.addWidget(self.label)
model = QStringListModel()
textList = list()
textList = ["Itemname1", "Itemname2", "Itemname3", "Itemname4", "Itemname5", "Itemname6", "Itemname7", "Itemname8"]
model.setStringList(textList)
self.listView.setModel(model)
self.listView.clicked[QtCore.QModelIndex].connect(self.on_clicked)
def on_clicked(self, index):
item = self.listView.selectedIndexes()
print(item)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
输出为[<PyQt5.QtCore.QModelIndex object at 0x0416CA70>]
,但我想要整数。
此便利功能返回所有已选择和视图中的非隐藏项目索引。该列表没有重复项,并且未排序。
返回QModelIndex的列表。以下将获得第一个索引:
print(item[0].row())
此外,对于单个选择,您可以改用QListView.currentSelection()