3

我有一个 QTableWidget 我已经设置,这样你就不能选择单元格,但可以通过它们的标题选择行/列。我遇到的问题是当我选择一行时,它会取消选择任何已选择的列,并且对于列/行也是如此。我希望能够选择具有 ExtendedSelection 行为的行和具有 SingleSelection 行为的列,但彼此独立。这就是我正在做的事情:

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)));

然后:

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);

}

4

1 回答 1

4

此代码允许您先选择列,然后您必须按控制选择其他行。试试这个,我希望它可以帮助。无论如何,这个解决方案不适用于 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);
}

在此处输入图像描述

于 2013-07-22T17:08:38.703 回答