如何使“QTableWidget”项目仅在单击第一列时才被选中

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

本文关键字:一列 QTableWidget 何使 项目 单击      更新时间:2023-10-16

我想要具有下一行为的QTableWidget

  1. 它应该是可选择的行,并且只能选择一行,我可以用setSelectionBehavior(QAbstractItemView::SelectRows);来做setSelectionMode(QAbstractItemView::SingleSelection)

  2. 现在,我希望只有当用户单击第一列中的项目时才选择行。当用户点击其他列中的项目时,选择不应该改变。我该怎么做?

您需要将QTableWidget子类化才能以这种方式重新实现mousePressEvent

#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)
  }
};

票据

  • QTableView相同