How to get item selected from QListView in PyQt

江枫思渺然 提交于 2020-05-23 03:45:05

问题


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.

Here is the code :

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_())   

Thanks !


回答1:


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())

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())


来源:https://stackoverflow.com/questions/14546913/how-to-get-item-selected-from-qlistview-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!