pythonpysideqlistwidgetqlistwidgetitem

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


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.


Solution

  • 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_())