view raw
yvesva yvesva - 7 months ago 56
Python Question

Accessing property of dynamically created QStandardItems in PyQt5

I'm having a problem determining whether or not the checkboxes that are dynamically created have been checked or unchecked by the user in a simple GUI I've created.

I've adapted the relevant code and pasted it below. Although it may be easy to just create and name 4 QStandardItems, I'm dealing with many lists containing many different items that change quite a lot, so it isn't really feasible to create them myself.

Any help finding out how to access these properties would be much appreciated.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class Splash(QWidget):
def __init__(self):

# imagine this is a very long list...
self.seasons = ['summer','autumn','winter','spring']


def initUI(self):
layout = QVBoxLayout()

list = QListView()
model = QStandardItemModel()

printbtn = QPushButton('print values')

for season in self.seasons:
item = QStandardItem(season)

model.dataChanged.connect(lambda: self.print_action(item.text()))



def print_action(self, item):
print('changed', item)

if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ex = Splash()

In short - I can detect when an item has been checked using model.dataChanged and connecting that to a function, but it cannot differentiate between the seasons.


If you keep a reference to the list (or the model), you can search for the items by their text, and then get their check-state:

def print_action(self):
    model = self.list.model()
    for text in 'summer', 'autumn', 'winter', 'spring':
        items = model.findItems(text)
        if items:
            checked = items[0].checkState() == Qt.Checked
            print('%s = %s' % (text, checked))