1

I'm trying to disable users from selecting individual cells in the table widget and I only want to be able to select column and row headers, with their own separate selection behavior. Here's what I tried:

ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
ui->tableWidget->horizontalHeader()->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableWidget->verticalHeader()->setSelectionMode(QAbstractItemView::MultiSelection);

But it's not allowing me to select anything, and I can't find a method to set the selection behavior for only cells. Anyone?

EDIT: I tried connecting to the sectionClicked signal of the table widgets vertical and horizontal headers, and those seem to be emitting even with the table widget's selection set to none, but they don't remain highlighted.

4

1 回答 1

2

setSelectionMode 默认为 NoSelection 以忽略小部件上的所有选择。然后按照以下代码连接以触发 hhSelected 和 vhSelected 插槽。在这些插槽中,您只需设置相应的 selectionMode 和 SelectionBehavior。

SO_Qt::SO_Qt(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);
ui.tableWidget->setSelectionMode(QAbstractItemView::NoSelection);

QHeaderView* hh = ui.tableWidget->horizontalHeader();
bool success = connect(hh, SIGNAL(sectionClicked( int )), this, SLOT(hhSelected(int)));

QHeaderView* vh = ui.tableWidget->verticalHeader();
success = connect(vh, SIGNAL(sectionClicked( int )), this, SLOT(vhSelected(int)));
}

void SO_Qt::hhSelected( int index )
{
    ui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectColumns);
    ui.tableWidget->selectColumn(index);
}

void SO_Qt::vhSelected( int index )
{
    ui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.tableWidget->selectRow(index);
}
于 2013-07-20T13:24:49.227 回答