c++ - 在 QTableWidget 中区分交替行颜色和选择颜色

标签 c++ qt qtablewidget qtablewidgetitem qpalette

我有两个 QTableWidget,它们应该同步它们的选择。更准确地说,表 2 中选择的所有内容都应在表 1 中自动选择。

一切正常,但如果我将属性 setAlternatingRowColors 设置为 true,则会出现视觉问题。 (我认为 setAlternatingRowsColors 是一个很棒的功能。)

#include <QApplication>
#include <QPushButton>
#include <QTableWidget>
#include <QHBoxLayout>

QTableWidget* create() {
    auto table = new QTableWidget;
    table->setAlternatingRowColors(true);
    table->setSortingEnabled(true);
    table->setRowCount(20);
    table->setColumnCount(2);
    for (auto i = 0; i < 20; i++) {
        {
            auto item = new QTableWidgetItem(QString("%1").arg(i));
            table->setItem(i, 1, item);
        }
        {
            auto item = new QTableWidgetItem(QString("%1").arg(i));
            table->setItem(i, 0, item);
        }
    }
    return table;
}
int main(int argc, char** args) {
    QApplication app(argc, args);
    QTableWidget* table1 = create();
    QTableWidget* table2 = create();
    auto frame = new QFrame;
    frame->setLayout(new QHBoxLayout);
    frame->layout()->addWidget(table1);
    frame->layout()->addWidget(table2);
    frame->show();
    QObject::connect(table2, &QTableWidget::itemSelectionChanged, [&]() {
        table1->selectionModel()->clearSelection();
        for (auto item : table2->selectedItems()) {
            table1->item(item->row(), item->column())->setSelected(true);
        }
        table1->update();
    });
    app.exec();
}

即使像以前一样选择了奇数行的元素,用户也没有机会看到这个选择。看起来两种颜色都一样(但为什么会这样?)。

Selection indistinguishable from alternating row

从这个角度来看,可能只有两种可能的解决方案。更改选择颜色或更改 alternatingRows 的颜色。

如何在可能包含更多 QTableWidgets 的整个应用程序中一致地更改交替行的颜色?

最佳答案

这应该有效(主要):

QString style = "QTableWidget { alternate-background-color: white; background-color: gray; }";
style.append(" QTableWidget::item:selected { background: red; }"); //selection color
QApplication::setStyleSheet(style);

关于c++ - 在 QTableWidget 中区分交替行颜色和选择颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48092265/

相关文章:

c++ - 将 Bullet Physics 与项目(未命名标签)集成时出错

c++ - 错误 MIDL2025 : syntax error : expecting an interface

c++ - 使用 stringstream 库解析行时的 std::getline 问题

c++ - 应用程序在窗口拖动时卡住

python - 如何在 QTableWidget 中使特定单元格可编辑并保留其余单元格不可编辑?

c++ - 新手问题 - 使用 Eigen 的复矩阵代数

c++ - 在 Qt 中使用 StackedLayout 类

qt - Qt Installer Framework 可以返回失败退出代码吗?

c++ - QTabWidget:确定页面为QTableWidget

QTableWidgetItem 设置隐藏数据