Setting flags to make an item unselectable and later, selectable again
Asked Answered
I

1

5

I am learning PySide and I was confused how to set the flag for a QListWidget item back to selectable after first setting it to unselectable. I know I can:

QListWidget.SetFlags(QtCore.Qt.ItemIsSelectable)

I am a bit unsure why the flag is named, "ItemIsSelelectable" when it seems to make the item unselectable. But I wanted to set the item back to selectable after setting this flag.

Improvise answered 27/5, 2018 at 5:26 Comment(0)
K
12

If you want to activate a flag of an item you must use the operator |:

it.setFlags(it.flags() | Qt.ItemIsSelectable)

If you want to deactivate it you must use & ~:

it.setFlags(it.flags() & ~Qt.ItemIsSelectable)

Example:

import sys
from PySide.QtGui import QApplication, QWidget, QVBoxLayout, QListWidget, QPushButton
from PySide.QtCore import Qt

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        lay = QVBoxLayout(self)
        self.button = QPushButton("UnSelectable")
        self.listWidget = QListWidget()

        for i in range(10):
            self.listWidget.addItem("item {}".format(i))

        lay.addWidget(self.button)
        lay.addWidget(self.listWidget)
        self.button.clicked.connect(self.on_clicked)

    def on_clicked(self):
        if self.button.text() == "UnSelectable":
            self.button.setText("Selectable")
            for i in range(self.listWidget.count()):
                it = self.listWidget.item(i)
                it.setFlags(it.flags() & ~Qt.ItemIsSelectable)
        else:
            self.button.setText("UnSelectable")
            for i in range(self.listWidget.count()):
                it = self.listWidget.item(i)
                it.setFlags(it.flags() | Qt.ItemIsSelectable)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
Kilowatthour answered 27/5, 2018 at 5:47 Comment(2)
Thank you very much. Is this syntax true for Pyside? I do not recognize the | and & ~ symbols you are using with the setFlags method. Thank you again.Improvise
This seems to work very well. I will mark as correct.Improvise

© 2022 - 2024 — McMap. All rights reserved.