简体   繁体   中英

How to make `QTableWidget` items to be selected only when first column is clicked

I want QTableWidget with the next behaviour:

  1. It should be row selectable and only one row may be selected, I can do it with setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::SingleSelection)

  2. Now I want row to be selected only when user click on item which is in first column. And selection should not change when user click on items which are in other column. How should I do it?

You need to subclass QTableWidget to reimplement mousePressEvent in this way

#include <QMouseEvent>
#include <QTableWidget>

class Table : public QTableWidget {
  virtual void  mousePressEvent(QMouseEvent * event) {
     //the selectable column index
    const int SELECTABLE_COLUMN = 0;

    //retrieve the cell at pos
    QModelIndex i = indexAt(event->pos());

    //check if the item is in the desired column
    if ( i.column() == SELECTABLE_COLUMN ) {
      //behave as normal
      QTableView::mousePressEvent(event);
    }
    //else nothing (ignore click event)
  }
};

Notes

  • Works the same for QTableView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM