Search code examples
pythoncheckboxpyqt4qlistview

PYQT4, ListView: How to get selected rows using QStandardItemModel


I want to use ListView in Pyqt4 to display some items with a checkbox in front of each item. And, I want to get those selected items,but return value of self.ui.listView.selectedIndexes() is None, I really don’t know what to do to get what I want.
My codes are as following:

#coding=utf-8
from loadtsklist import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os

class MyLoadTskList(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.initTaskList()
    def initTaskList(self):
        global connectserver
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.btsure.clicked.connect(self.test)


        tsklist = [u'北京',u'南京', u'海南', u'青岛', u'西安']
        model = QStandardItemModel()
        for task in tsklist:
            print(task)
            item = QStandardItem(QString(task))
            check = Qt.Unchecked
            item.setCheckState(check)
            item.setCheckable(True)
            model.appendRow(item)
            self.ui.listView.setModel(model)
    def test(self):
        print len(self.ui.listView.selectedIndexes())
        print "hello this is LoadTskList"

app = QApplication(sys.argv)
tsk = MyLoadTskList()
tsk.show()
app.exec_()

Could someone please tell me how to do? thanks in advance!


Solution

  • Firstly, your code for loading the list can be made more efficient, like this:

        model = QStandardItemModel(self)
        self.ui.listView.setModel(model)
        for task in tsklist:
            item = QStandardItem(task)
            item.setCheckable(True)
            model.appendRow(item)
    

    And then to get the checked items, you need another loop, like this:

    def test(self):
        model = self.ui.listView.model()
        for row in range(model.rowCount()):
            item = model.item(row)
            if item.checkState() == QtCore.Qt.Checked:
                print('Row %d is checked' % row)