Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 720
ldl Avatar asked Oct 18 '25 10:10

ldl


1 Answers

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)
like image 89
ekhumoro Avatar answered Oct 20 '25 01:10

ekhumoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!