简体   繁体   中英

How to get item selected from QListView in PyQt

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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM