简体   繁体   English

如何在PyQt中从QListView中选择项目

[英]How to get item selected from QListView in PyQt

I'm new to PyQt. 我是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. 所以我试图从QListView中获取所选项目,我能够获得所选项目的索引,但我无法获得索引的值,可以请有人帮助我。

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 . 您可以使用QModelIndex的便捷方法data It returns a QVariant . 它返回一个QVariant Just convert it to something you'd use, like a QString with .toString : 只需将其转换为您使用的内容,例如带有.toStringQString

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. 顺便说一句, QListView.clicked将为您提供索引。 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() : 您不需要遍历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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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