2017-05-08 4 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); 
    } 
}; 

しかし、この解決策は完璧ではありません。点滅していないテキストカーソルは1つの不完全です。おそらく他のものがあります。しかし、私はそれを少し改善することはあなたにとって大きな問題ではないと信じています。

関連する問題