【问题标题】:Change highlight color of text inside a QGraphicsTextItem更改 QGraphicsTextItem 内文本的突出显示颜色
【发布时间】:2017-05-08 21:51:56
【问题描述】:

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

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

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);
}

这没有效果....

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

【问题讨论】:

    标签: qt highlight qgraphicsitem textcolor


    【解决方案1】:

    QGraphicsTextItem::paint() 的默认实现不关心QStyleOptionGraphicsItem::palette。如果您想要不同的颜色,则必须实现自定义绘画。

    这是一个简化的方法怎么做:

    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);
        }
    };
    

    但是,这个解决方案并不完美。不闪烁的文本光标是一种缺陷。可能还有其他人。但我相信稍微改进一下对你来说没什么大不了的。

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 2010-12-12
      • 2010-09-29
      相关资源
      最近更新 更多