更新时间:2022-06-20 08:29:08
QGraphicsTextItem :: paint()
的默认实现与 QStyleOptionGraphicsItem :: palette
无关..如果要使用其他颜色,则必须实施自定义绘画.
The default implementation of QGraphicsTextItem::paint()
doesn't care about QStyleOptionGraphicsItem::palette
. You have to implement a custom painting if you want different color.
这是简化的方式:
class CMyTextItem : public QGraphicsTextItem
{
public:
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
QAbstractTextDocumentLayout::PaintContext ctx;
if (option->state & QStyle::State_HasFocus)
ctx.cursorPosition = textCursor().position();
if (textCursor().hasSelection())
{
QAbstractTextDocumentLayout::Selection selection;
selection.cursor = textCursor();
// Set the color.
QPalette::ColorGroup cg = option->state & QStyle::State_HasFocus ? QPalette::Active : QPalette::Inactive;
selection.format.setBackground(option->state & QStyle::State_HasFocus ? Qt::cyan : ctx.palette.brush(cg, QPalette::Highlight));
selection.format.setForeground(option->state & QStyle::State_HasFocus ? Qt::blue : ctx.palette.brush(cg, QPalette::HighlightedText));
ctx.selections.append(selection);
}
ctx.clip = option->exposedRect;
document()->documentLayout()->draw(painter, ctx);
if (option->state & (QStyle::State_Selected | QStyle::State_HasFocus))
highlightSelected(this, painter, option);
}
};
但是,此解决方案并不完美.不闪烁文本光标是一种缺陷.可能还有其他人.但是我相信稍微改善一下对您来说并不是什么大问题.
However, this solution is not perfect. Not-blinking text cursor is one imperfection. There are probably others. But I believe that improving it a little will be not that big deal for you.