我有一个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);
}
答案 0 :(得分:4)
此代码允许您先选择列,然后必须按控制键才能选择其他行。试试这个,我希望它可以提供帮助。无论如何,这种解决方案不适用于班次。
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);
}