c++ - 如何选择 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 列的任何单元格,我将无法选择整个列,而只能选择单个单元格。
感谢您的任何见解。
解决方案
我不知道这是否是最优雅的方法,但我能够通过修改 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”列。也许你可以在你的程序中做类似的事情。
推荐阅读
- c# - JSON.NET 反序列化程序返回 Null
- mysql - 更改sql模式后在ubuntu上重新启动MySQL
- airflow - 需要在完成 2 个并行 dag 后触发 dag
- r - R 闪亮、多选择输入和计算在选择新输入时更新
- android - 没有时如何动态添加片段。是不是事先知道的?
- ios - 使用 SwiftUI 以编程方式发送 SMS
- c++ - Visual Studio 控制台程序在 control-c 后崩溃
- python - 从 apache beam pcollection 返回什么以写入 bigquery
- python - 将 Paramiko SSH 模块与 csv.reader 一起使用?
- r - 如何使用 select 在 R 中删除多个列?我只是不知道在哪里放置“-”