dosvarog
dosvarog

Reputation: 754

How to deselect selected cell in QTableWidget by clicking on it again?

I am trying to deselect a selected cell in QTableWidget by clicking on it again. I don't know if I missed an option or a signal in documentation (I hope not). I tried with signals cellClicked and cellActivated. None of them work. Thing is, if a cell is in a deselected state and I click on it, by the time signal cellClicked is emitted, cell already has selection. So I cannot check for selection in a slot that reacts to that signal.

So how can I deselect a selected cell? Selection mode is SingleSelection. I just hope I don't have to subclass QTableWidget.

Upvotes: 0

Views: 1665

Answers (1)

G.M.
G.M.

Reputation: 12899

I've only performed minimal testing but the following appears to do what you want...

#include <iostream>
#include <QApplication>
#include <QTableWidget>

int main (int argc, char **argv)
{
  QApplication app(argc, argv);
  QTableWidget tw(5, 10);

  /*
   * Disable any normal selection mode.
   */
  tw.setSelectionMode(QAbstractItemView::NoSelection);

  QObject::connect(&tw, &QTableWidget::cellClicked,
                   [&tw](int row, int col)
                     {

                       /*
                        * Make sure we have an item in the cell.
                        */
                       auto *item = tw.itemAt(row, col);
                       if (!item) {
                         item = new QTableWidgetItem(QString("cell[%1, %2]").arg(row).arg(col));
                         tw.setItem(row, col, item);
                       }

                       /*
                        * Update selection based on current state.
                        */
                       bool was_selected = item->isSelected();
                       tw.selectionModel()->clear();
                       item->setSelected(!was_selected);
                     });
  tw.show();
  return app.exec();
}

Upvotes: 1

Related Questions