Qt World Summit: Submit your Presentation


QListView deselect item by clicking on selected Item



  • Hey,

    I have a question about the QListView. In a QListView I can set the SelectionMode via listView->setSelectionMode(QAbstractItemView::SelectionMode).I want to achieve the same as with QAbstractItemView::ExtendedSelection but without pressing the CTRL key. The best would be to simply click on the activated item and this will deselect it. Is this possible in a simple way?


  • Lifetime Qt Champion

    @Gabber
    Hi
    Ok. i missed the shift part.

    Well you can try a mousepress override.
    Normally one would subclass QItemSelectionModel but I'm not sure if we can know ctrl was pressed (in the view) and
    change the selection. logic

    You can try

    class ToggleListView : public QListView
    {
        Q_OBJECT
    public:
        explicit ToggleListView(QWidget *parent = Q_NULLPTR) : QListView(parent) {}
    protected:
        void mousePressEvent(QMouseEvent *event) override
        {
            Qt::KeyboardModifiers keys;
            keys.setFlag(Qt::ControlModifier);
            event->setModifiers(keys);
            QListView::mousePressEvent(event);
        }
    };
    
    

    Seems to be ok but you might want to test if shift is pressed and then not set CTRL.


  • Lifetime Qt Champion

    Hi
    But does
    setSelectionMode(QAbstractItemView::SelectionMode::MultiSelection);
    not function as you want as it can select/deselect by clicking ?
    (no ctrl)

    alt text



  • Hi,

    no MultiSelection is not what I want. I want a single item selection and the possibility to select multiple items with shift. Selecting and deselecting a single selection should only be done by mouse click (not CTRL + mouse).


  • Lifetime Qt Champion

    @Gabber
    Hi
    Ok. i missed the shift part.

    Well you can try a mousepress override.
    Normally one would subclass QItemSelectionModel but I'm not sure if we can know ctrl was pressed (in the view) and
    change the selection. logic

    You can try

    class ToggleListView : public QListView
    {
        Q_OBJECT
    public:
        explicit ToggleListView(QWidget *parent = Q_NULLPTR) : QListView(parent) {}
    protected:
        void mousePressEvent(QMouseEvent *event) override
        {
            Qt::KeyboardModifiers keys;
            keys.setFlag(Qt::ControlModifier);
            event->setModifiers(keys);
            QListView::mousePressEvent(event);
        }
    };
    
    

    Seems to be ok but you might want to test if shift is pressed and then not set CTRL.



  • @mrjj
    Thanks for your code example, it works perfectly!

    I have thought about the whole thing again and will stay for now with a simple select (without shift). Therefore I will mark the thread as solved.


Log in to reply