问题描述
我是PyQt的新手.因此,我试图从QListView中获取所选项目,我能够获取所选项目的索引,但是我无法获取索引的值,请有人帮助我.
I'm new to PyQt. So I'm trying to get selected item from QListView, I'm able to get selected items's index, but I'm not able to get the value of the index, can please someone help me.
这是代码:
import sys
import os
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class asset(QtGui.QDialog):
def __init__(self,parent=None):
super(asset, self).__init__(parent)
self.assetList = QtGui.QListView(self)
self.assetList.clicked.connect(self.on_treeView_clicked)
######################################################################
# ----------------- ADD ITEMS----------------------------------------
######################################################################
list_data = listDirs('D:\\')
dir = listModel(list_data)
self.assetList.setModel(dir)
self.setStyleSheet('''
*{
background-color : rgb(65,65,65);
color : rgb(210,210,210);
alternate-background-color:rgb(55,55,55);
}
QTreeView,QListView,QLineEdit{
background-color : rgb(50,50,50);
color : rgb(210,210,210);
}
'''
)
self.setFocus()
@QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_clicked(self, index):
itms = self.assetList.selectedIndexes()
for it in itms:
print 'selected item index found at %s' % it.row()
class listModel(QAbstractListModel):
def __init__(self, datain, parent=None, *args):
""" datain: a list where each item is a row
"""
QAbstractListModel.__init__(self, parent, *args)
self.listdata = datain
def rowCount(self, parent=QModelIndex()):
return len(self.listdata)
def data(self, index, role):
if index.isValid() and role == Qt.DisplayRole:
return QVariant(self.listdata[index.row()])
else:
return QVariant()
def listDirs(*path):
completePath = os.path.join(*path)
dirs = os.listdir(os.path.abspath(completePath))
outputDir = []
for dir in dirs:
if os.path.isdir(os.path.join(completePath,dir)):
outputDir.append(dir)
return outputDir
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setStyle('plastique')
main = asset()
main.resize(200,200)
main.show()
sys.exit(app.exec_())
谢谢!
推荐答案
您可以使用便捷方法QModelIndex的> data
.它返回一个QVariant
.只需将其转换为您要使用的东西,例如QString
与.toString
:
You can use the convenience method data
of QModelIndex
. It returns a QVariant
. Just convert it to something you'd use, like a QString
with .toString
:
print 'selected item index found at %s with data: %s' % (it.row(), it.data().toString())
顺便说一句,QListView.clicked
将为您提供索引.除非您有多个选择或覆盖默认选择行为,否则它将是唯一选择的项目.您无需遍历selectedIndexes()
:
By the way, QListView.clicked
will give you the index. Unless you have multiple selection, or override the default selection behavior, it will be the only selected item. You don't need to loop over selectedIndexes()
:
@QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_clicked(self, index):
print 'selected item index found at %s with data: %s' % (index.row(), index.data().toString())
这篇关于如何从PyQt的QListView中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!