QListView deselect item by clicking on selected item - QT6
-
Hey,
I have a subclass QListView with SingleSelection mode:
//mGermanNameEditor = Subclass QListView mGermanNameEditor->setSelectionMode(QAbstractItemView::SingleSelection);
At that time I had already asked how to deselect a selected item in a QListView. I would like to do this without an additional button. Means: Select left mouse click, again left mouse click on the same item, deselect item again.
The whole thing worked until recently, then there must have been some updates on my Fedora system and since then some codeparts didn't work as before. I was able to fix everything so far except the problem described above.
At that time I had used this code:
ToggleListView.cpp
ToggleListView::ToggleListView(QWidget *parent): QListView(parent) {} ToggleListView::~ToggleListView() {} void ToggleListView::mousePressEvent(QMouseEvent *event) { Qt::KeyboardModifiers keys; keys.setFlag(Qt::ControlModifier); event->setModifiers(keys); QListView::mousePressEvent(event); }
ToggleListView.h
class ToggleListView : public QListView { Q_OBJECT public: explicit ToggleListView(QWidget *parent = nullptr); ~ToggleListView(); protected: void mousePressEvent(QMouseEvent *event) override; };
The thread at the time is this one.
Can anyone help me? Maybe with code example?
-
Now every mousePressEvent has the control modifier set - since you can select when you dont press the control key (according the documentation) - how is this supposed to work. Fix your code to only set the control key when the item under the cursor is already selected.
-
@Christian-Ehrlicher
Thanks for your answer. I tried it, but it didn't work:void ToggleListView::mousePressEvent(QMouseEvent *event) { if(selectionModel()->hasSelection()){ qDebug() << "Selected"; Qt::KeyboardModifiers keys; keys.setFlag(Qt::ControlModifier); event->setModifiers(keys); QListView::mousePressEvent(event); } else { Qt::KeyboardModifiers keys; keys.setFlag(Qt::NoModifier); event->setModifiers(keys); QListView::mousePressEvent(event); } }
The item cannot be deselected. Can you help me please?