2017-05-08 345 views
0

我想更改QGraphicsTextItem中選定文本的突出顯示顏色。更改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); 
} 

這沒有效果。

如何更改項目內選定文本的高亮顏色?

回答

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

然而,這種解決方案並不完美。不閃爍的文本光標是一個缺陷。可能還有其他人。但我相信稍微改進它對你來說不會有什麼大不了的。

相關問題