首页 > 解决方案 > 如何选择 QTableView 的特定整列

问题描述

我有一个包含三列的 QTableView,如下例所示:

| 身份证 | 姓名 | 坐标 |

无论我在 ACoord 中单击哪个单元格,我都试图突出显示整个 ACoord 列。

我尝试了几个例子,但没有任何帮助。最有前途的(也来自官方 QT 文档)似乎是setSelectionBehavior(QAbstractItemView::SelectColumns)但并没有完全按照我的需要工作。

这是代码片段:

connect(mTurnIntoExcelData, &QAction::triggered, [&]() {
        int row = -1, column = -1;
        QString reference;
        QString type;
        QModelIndex index;
        int rowModel = index.row();
        SelectionData currentData;

        for(int i = 0; i < ui->tableViewLeft->model()->columnCount(); i++)
        {
          if(ui->tableViewLeft->model()->headerData(i, Qt::Horizontal).toString() == "ACoord") {
              column = i;
              ui->tableViewLeft->setSelectionBehavior(QAbstractItemView::SelectColumns);
              ui->tableViewLeft->setSelectionMode(QAbstractItemView::SingleSelection);
              type = "ACoord";
      }

预期的结果是:我单击 ACoord 的任何单元格,整个列变为可选择的。

但是,实际结果是,如果我单击 ACoord 列的任何单元格,我将无法选择整个列,而只能选择单个单元格。

感谢您的任何见解。

标签: c++qt5

解决方案


我不知道这是否是最优雅的方法,但我能够通过修改 Qt 的“FrozenColumn”示例程序(在 $QTDIR/qtbase/examples/widgets /itemviews/frozencolumn)以下列方式:

freezetablewidget.h中,在该部分中添加以下声明private slots:

void currentColumnChanged(const QModelIndex &);  
void autoSelectMagicColumn();

freezetablewidget.cpp中,将 a 添加#include <QTimer>到顶部的包含部分,然后将以下行添加到FreezeTableWidget::init()方法的末尾:

connect(frozenTableView->selectionModel(), SIGNAL(currentColumnChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentColumnChanged(const QModelIndex &)));
connect(frozenTableView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(currentColumnChanged(const QModelIndex &)));  // optional

...最后,将以下新行添加到freezetablewidget.cpp

const int magicColumnIndex = 2;  // or whichever column you want the auto-selecting to happen on

void FreezeTableWidget::currentColumnChanged(const QModelIndex & mi)
{
   const int col = mi.column();
   if (col == magicColumnIndex)
   {
      // Auto-select the entire column!  (Gotta schedule it be done later 
      //  since it doesn't work if I just call selectColumn() directly at this point)
      QTimer::singleShot(100, this, SLOT(autoSelectMagicColumn()));
   }
}

void FreezeTableWidget::autoSelectMagicColumn()
{
    // Double-check that the focus is still on the magic column index, in case the user moves fast
    if (selectionModel()->currentIndex().column() == magicColumnIndex) frozenTableView->selectColumn(magicColumnIndex);
}

通过上述更改,当我单击该列中的任何单元格(或通过箭头键导航到该列中的任何单元格)时,FrozenColumn 示例应用程序将自动选择整个“YDS”列。也许你可以在你的程序中做类似的事情。


推荐阅读