Select rows and columns in QTableWidget, while keeping highlighted

早过忘川 提交于 2019-12-04 05:02:52

问题


I have a QTableWidget that I've set up such that you can't select the cells, but can select rows/columns by their headers. The problem I'm having is when I select a row, it deselects any columns that were selected, and same for column/rows. I want to be able to select rows with the ExtendedSelection behavior and columns with the SingleSelection behavior, but independently of eachother. Here's what I'm doing:

ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
connect(ui->tableWidget->horizontalHeader(),SIGNAL(sectionClicked(int)), this,SLOT(horizontalHeaderClicked(int)));
connect(ui->tableWidget->verticalHeader(),SIGNAL(sectionClicked(int)), this,SLOT(verticalHeaderClicked(int)));

Then:

void MatrixWidget::horizontalHeaderClicked(int column){
   if(column <= 0) return; //first column is names, doesn't represent a segment

   ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
   ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectColumns);
   ui->tableWidget->selectColumn(column);
   ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);

}

void MatrixWidget::verticalHeaderClicked(int row){
   ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
   ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
   ui->tableWidget->selectRow(row);
   ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);

}


回答1:


This code allows you to select column first then you must press control to select other rows. Try this, I hope it can help. Anyway, this solution doesn't work well with shift.

void SO_Qt::hhSelected( int index )
{
    if(index <= 0) return;
    ui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectColumns);
    ui.tableWidget->selectColumn(index);
    ui.tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
}

void SO_Qt::vhSelected( int index )
{
    ui.tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui.tableWidget->selectRow(index);
    ui.tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
}



来源:https://stackoverflow.com/questions/17790509/select-rows-and-columns-in-qtablewidget-while-keeping-highlighted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!