更改QGraphicsTextItem中文本的突出显示颜色 [英] Change highlight color of text inside a QGraphicsTextItem

查看:185
本文介绍了更改QGraphicsTextItem中文本的突出显示颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 QGraphicsTextItem 中更改所选文本的突出显示颜色.

I would like to change the highlight color of the selected text inside a QGraphicsTextItem.

我把paint方法子类化了,所以我认为它就像在 QStyleOptionGraphicsItem 上设置一个不同的调色板一样简单-但我看不到任何示例,而且我尝试的方法不起作用:

I have the paint method subclassed, so I thought it can be as simple as setting a different palette on the QStyleOptionGraphicsItem - but I can't see any examples, and what I try is not working:

void TextItem::paint(QPainter* painter,
                     const QStyleOptionGraphicsItem* option,
                     QWidget* widget)
{
    QStyleOptionGraphicsItem opt(*option);

    opt.palette.setColor(QPalette::HighlightedText, Qt::green);

    QGraphicsTextItem::paint(painter, &opt, widget);
}

这没有效果....

如何更改项目内所选文本的突出显示颜色?

How can I change the highlight color of the selected text inside an item ?

推荐答案

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.

这篇关于更改QGraphicsTextItem中文本的突出显示颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆