【问题标题】:QTableWidget, different selection colors for the different cellsQTableWidget,不同单元格的不同选择颜色
【发布时间】:2019-07-24 08:56:02
【问题描述】:

我想为 QTableWidget 的不同单元格设置不同的选择颜色。

要更改我可以使用的整个表格的选择颜色

QTableWidget* table = new QTableWidget;
table->setStyleSheet("QTableWidget::item{selection-background-color:#ff0000;}");

要设置单个单元格的常用背景颜色,可以按以下方式编写:

table->setItem(row, column, new QTableWidgetItem(""));
table->item(row, column)->setBackgroundColor(QColor(255,255,0));

但我找不到有关不同单元格的不同选择颜色的任何信息。

请帮忙!

【问题讨论】:

  • 看起来你需要像this这样的解决方案

标签: qt qtablewidget


【解决方案1】:

这对我来说是一个非常有趣的问题,我写了一个例子)) 我使用委托来解决这个问题

class MyDelegate : public QItemDelegate
{
  public:
    MyDelegate( QObject *parent ) : QItemDelegate( parent ) { }
    void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const;

};

void MyDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
     QItemDelegate::paint( painter, option, index );

     QColor background = QColor(rand()%255, rand()%255, rand()%255);
     QColor background2 = QColor(255, 255, 255);

     painter->fillRect(option.rect, background);

     if (option.state & QStyle::State_Selected) {
            painter->fillRect(option.rect, background);
        } else {
            painter->fillRect(option.rect, background2);
        }

}

它将如何工作?每次选择都会为所选项目生成一种新颜色

委托集成

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    QTableWidget* m_pTableWidget = new QTableWidget();
    m_pTableWidget->setRowCount(10);
    m_pTableWidget->setColumnCount(10);

    for (int i = 0; i < m_pTableWidget->rowCount(); ++i) {
        m_pTableWidget->setItemDelegateForRow(i, new MyDelegate(m_pTableWidget));

    }
    m_pTableWidget->show();

    return a.exec();
}

结果

您可以更改代码并为某些项目指定特定颜色。

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 2023-04-07
    • 1970-01-01
    • 2017-09-11
    • 2018-11-24
    • 2012-06-13
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多