2

我希望选定的单元格具有不同的背景颜色。默认情况下,所选单元格中只有一条细下划线。

我试过这个:

table->setStyleSheet("QTableView {selection-background-color: #0000FF; selection-color: #00FF00;}

但它只会更改指针位于单元格上时显示的颜色。指针离开后,我是否选择了table->selectRow(selRow)只有下划线的单元格。可能它在其他平台上看起来有所不同。

有很多相同主题的线程,但大多数答案是使用上面的样式表。没有任何效果,只有“moseover 颜色”发生了变化。

提前致谢, 问候马蒂亚斯

4

4 回答 4

2

这就是我所做的。

stylesheet =  "QTableView{selection-background-color: " + highlight + ";"
stylesheet +=     "selection-color: white; show-decoration-selected: 10}\n"
stylesheet += "QTableView::item:focus{border: 1px solid yellow;"
stylesheet +=     "background-color:"+highlight+"}"

table->setStyleSheet(stylesheet);

选择颜色对选中的一项进行着色,而项目焦点将为应突出显示的其余项目着色。

这适用于选定的单元格,例如具有选定的行。如果你想要“鼠标悬停”的东西,你可能必须在样式表中使用“悬停”。希望这能给你一些想法。

于 2014-08-06T12:18:18.190 回答
2
class BackgroundDelegate : public QStyledItemDelegate {
public:
  explicit BackgroundDelegate(QObject *parent = 0)
      : QStyledItemDelegate(parent){}
  void paint(QPainter *painter, const QStyleOptionViewItem &option,
             const QModelIndex &index) const {
    // Fill the background before calling the base class paint
    // otherwise selected cells would have a white background
    QVariant background = index.data(Qt::BackgroundRole);
    if (background.canConvert<QBrush>())
        painter->fillRect(option.rect, background.value<QBrush>());
    // the comment below makes selection transparent
    //QStyledItemDelegate::paint(painter, option, index);
    // To draw a border on selected cells
    if(option.state & QStyle::State_Selected) {
        painter->save();
        QPen pen(Qt::black, 2, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
        int w = pen.width()/2;
        painter->setPen(pen);
        painter->drawRect(option.rect.adjusted(w,w,-w,-w));
        painter->restore();
    }
  }
};

then table->setItemDelegateForColumn(2, new BackgroundDelegate(this));

于 2014-08-06T10:33:58.447 回答
1
table->setStyleSheet("QTableView:item:selected {background-color: #XXYYZZ; color: #FFFFFF}\n"
                     "QTableView:item:selected:focus {background-color: #3399FF;}")

不幸的是,似乎没有“nofocus”属性,因此您只需为所有选定项目设置颜色,然后将焦点颜色覆盖回默认值。#3399FF是颜色选择器显示的默认突出显示背景颜色用于我的设置,所以我使用了它。你可以用任何你喜欢的颜色代替。

The color: #FFFFFFsets the text colour to something custom when the selection loses focus. 当我有焦点时它对我来说是白色的,所以当它失去焦点时我只是保持它是白色的。您可以使用您喜欢的任何颜色,或删除该部分以使用默认颜色。

于 2016-05-17T22:05:42.770 回答
0

您需要使用自定义委托来根据需要绘制选定的单元格。

看看QAbstractItemView::setItemDelegate()方法和QItemDelegate类。您需要覆盖该QItemDelegate::paint()方法。paint 方法采用一个QStyleOptionViewItem结构 - 您可以使用它来确定是否选择了您被要求绘制的项目。

Qt 文档QItemDelegate::paint有完全做到这一点的示例代码。

于 2011-04-09T05:34:38.510 回答