I have this barebones code, I am trying to make it so some items (all even for this example) are preselected inside the QListWidget. Where am I going wrong?
from PyQt4 import QtGui, QtCore, Qt
import sys
class Main(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self,parent)
grid = QtGui.QGridLayout()
self.builtinpatternslist = QtGui.QListWidget()
self.builtinpatternslist.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
for i in range(5):
self.builtinpatternslist.addItem(QtGui.QListWidgetItem(str(i)))
if i % 2 == 0:
self.builtinpatternslist.setItemSelected(QtGui.QListWidgetItem(str(i)),True)
grid.addWidget(self.builtinpatternslist,0,0)
self.setLayout(grid)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = Main()
gui.show()
gui.raise_()
sys.exit(app.exec_())
Each
QtGui.QListWidgetItem(...)call creates a new item. What you are doing in that code is first creating an item, adding it to the list… And then, if it’s in an odd position, creating a whole new item and selecting it without ever adding it to the list.You need to make sure that you’re only dealing with one item each time: save the result of a single
QtGui.QListWidgetItem(...)call in a variable, and then operate on it: