Question

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.

Was it helpful?

Solution

setSelectionMode as default is NoSelection to ignore all the selection on widget. Then connect as below code to trigger hhSelected and vhSelected slots. In those slots you just set the corresponding selectionMode and 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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top