我有三列如下面的例子一个QTableView中:
| ID |名称|雅阁|
我想强调,整个雅阁列不管,我只在雅阁单击该单元格。
我曾尝试几个例子,但没有什么是有帮助的。最有前途的(也是从官方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列的任意单元格,我不能选择整列,但只有单细胞。
感谢您的任何见解。
我不知道这是否是最优雅的方式来做到这一点,但我能得到(我相信这是)通过修改Qt的“FrozenColumn”示例程序(在$ QTDIR / qtbase /例子/小工具,你想要的行为/ itemviews / frozencolumn)以下列方式:
在freezetablewidget.h
,添加private slots:
段内的以下声明:
void currentColumnChanged(const QModelIndex &);
void autoSelectMagicColumn();
在freezetablewidget.cpp
,添加一个#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”列每当我点击在该列中的任何单元格(或通过箭头键导航到任何细胞在该列中)。也许你可以做你的程序类似的东西。