s.m
s.m

Reputation: 229

Is there any way to disable QListWidgetItem in my QListWidget?

I am using QListWidgetItem to add Items in my QListWidget.

In some situations, I want some rows of my QListWidget become non selectable. (I mean I want some QListWidgetItem to be non selectable)

Is ther any way to do this?

PS: I tried

listWidgetItem->setFlags(Qt::NoItemFlags)

listWidgetItem->setSelected(false);

but they don't disable the selection of items.

Edit:

QStringList _strListClients = _strClients.split(",",QString::KeepEmptyParts,Qt::CaseInsensitive);

for(int i = 0; i < _strListClients.count(); i++)//Add Client's Check Boxes
{
    QListWidgetItem* _listWidgetItem = new QListWidgetItem(_strListClients[i], listWidgetClients);
    listWidgetClients->addItem(_listWidgetItem);

    if(_strListClients[i] == "Unknown"){
        _listWidgetItem->setSelected(false);
        _listWidgetItem->setTextColor(Qt::red);
        _listWidgetItem->setFlags(_listWidgetItem->flags() & ~Qt::ItemIsSelectable);

    }

}

Upvotes: 4

Views: 14982

Answers (2)

peppe
peppe

Reputation: 22826

Just remove the Qt::ItemIsSelectable flag from each item:

item->setFlags(item->flags() & ~Qt::ItemIsSelectable);

Or remove Qt::ItemIsEnabled if you want to remove all interaction with the item.

E.g.

#include <QtWidgets>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QListWidget widget;

    for (int i = 0; i < 100; ++i) {
        QListWidgetItem *item = new QListWidgetItem(QStringLiteral("Item %1").arg(i));
        if (i % 2 == 0) // disable one every two
            item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
        widget.addItem(item);
    }

    widget.show();

    return app.exec();
}

Upvotes: 8

Marco Giordano
Marco Giordano

Reputation: 610

You can try the following:

1) Override the clicked/selection event (sorry I don't remember the exact name. Doing so you can have some sort of flag/bool value on the item, and if is set as not being selectable you just return.

2) Rather then override you just connect to the signal and perform the above check and if you don't want to select that item you un-select it afterwards.

A bit of a work around but I don't know if there is a built in way to do so. Checking the documentation I did not see a disable method on the item itself.

If you go down the road of list view you should have more control on that, also on the display, so you might be able to displayed it greyed etc. A view is a bit more work though.

M.

Upvotes: 1

Related Questions