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.

mpellegr
  • 3,072
  • 3
  • 22
  • 36

1 Answers1

2

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);
}
trandatnh
  • 351
  • 8
  • 26
  • I used this but I reset to NoSelection after selecting the row/column. It's a little hacky, but at least it does what I wanted. Thanks a lot! – mpellegr Jul 22 '13 at 14:33
  • I'm having issue using this solution. I created another question if you wanted to answer it: http://stackoverflow.com/questions/17790509/select-rows-and-columns-in-qtablewidget-while-keeping-highlighted – mpellegr Jul 22 '13 at 14:47