【问题标题】:Distinguish alternating rows color from selection color in QTableWidget在 QTableWidget 中区分交替行颜色和选择颜色
【发布时间】:2018-01-04 09:30:52
【问题描述】:

我有两个QTableWidgets,应该同步他们的选择。更准确地说,表 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();
}

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

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

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

【问题讨论】:

  • 这并不重要,但你有内存泄漏

标签: c++ qt qtablewidget qtablewidgetitem qpalette


【解决方案1】:

这应该有效(主要):

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

【讨论】:

  • 感谢您的回复。这适用于所有 QStyle 吗? (其实我只是用windows而已,只是好奇而已。)
  • 其实可以,但是有一些副作用。也可以更改选择颜色?
  • 对不起。没有副作用。我只是不需要设置background-color: gray
  • 静止。如何更改选择颜色?这可能吗?
  • 它说:QApplication,通过了无效的样式覆盖,忽略它。它适用于你的情况吗?我们使用的是 Qt 5.8。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 2012-07-17
  • 2015-07-30
  • 1970-01-01
相关资源
最近更新 更多