qt - 在 QTableWidget 中选择行和列,同时保持突出显示

标签 qt user-interface qtableview qtablewidget

我有一个已设置的 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);

最佳答案

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

enter image description here

关于qt - 在 QTableWidget 中选择行和列,同时保持突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17790509/

相关文章:

android - Qt可以在Android中运行吗?

c++ - OpenCV - 如何启用滚动到带有图像的窗口?

wpf - 设计GUI应用程序: one VS multiple screens

c++ - 使用来自不同线程的实时数据更新 QTableView 的最佳策略

c++ - 结构中的枚举

c++ - 在 Qt 中捕获音频信号

c++ - QObject::connect:在使用 Lambda 语法的升级小部件中找不到信号

Cocoa的事件驱动系统: where do background tasks run?

python-3.x - 在 PyQt5 中,如何使用拖放正确移动 QTableView 中的行

qt - 更改 QTableView 标题中的文本方向