c++qtqtablewidgetqtablewidgetitemqpalette

Distinguish alternating rows color from selection color in QTableWidget


I have two QTableWidgets, that should synchronize their selection. More precisely everything selected in Table 2, should be automatically selected in Table 1.

Everything works fine, but if I'm setting the property setAlternatingRowColors to true, I have a visual problem. (I'm thinking that setAlternatingRowsColors is a great feature.)

#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();
}

Even though the selection of elements in odd rows is done as before, the user has no chance to see this selection. It seems that both colors are the same (But why is this so?).

Selection indistinguishable from alternating row

With this perspective there might be only two possible solutions. Either change the selection color or changing the color of the alternatingRows.

How can I change the color of the alternating rows consistently among the whole application, that might contain even more QTableWidgets?


Solution

  • This should work (in main):

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