2012-02-03 358 views
3

我想要實現的是以下內容:我有一個QGraphicsScene,其中顯示一個QGraphicsPixmapItem。像素圖有多種顏色,我需要在像素圖上繪製一條線,這些線必須在每個點都可見和可識別。在Qt中繪製一條多色線

我的想法是繪製一條線,其中每個像素具有像素圖相關像素的負(互補)顏色。所以我想到了子類化QGraphicsItem並重新實​​現了paint()方法來繪製多色線。

但是我卡住了,因爲我不知道如何從paint函數檢索像素圖的像素信息,即使我發現了,我也想不出一種方法來畫線這條路。

你能給我一些關於如何進行的建議嗎?

回答

11

您可以使用QPaintercompositionMode屬性很容易地做這樣的事情,而不必讀取源像素顏色。

簡單的樣品QWidget與自定義paintEvent實施,你應該能夠適應你的項目的paint方法:

#include <QtGui> 

class W: public QWidget { 
    Q_OBJECT 

    public: 
     W(QWidget *parent = 0): QWidget(parent) {}; 

    protected: 
     void paintEvent(QPaintEvent *) { 
      QPainter p(this); 

      // Draw boring background 
      p.setPen(Qt::NoPen); 
      p.setBrush(QColor(0,255,0)); 
      p.drawRect(0, 0, 30, 90); 
      p.setBrush(QColor(255,0,0)); 
      p.drawRect(30, 0, 30, 90); 
      p.setBrush(QColor(0,0,255)); 
      p.drawRect(60, 0, 30, 90); 

      // This is the important part you'll want to play with 
      p.setCompositionMode(QPainter::RasterOp_SourceAndNotDestination); 
      QPen inverter(Qt::white); 
      inverter.setWidth(10); 
      p.setPen(inverter); 
      p.drawLine(0, 0, 90, 90); 
     } 
}; 

這將輸出類似下面的圖片:

Fat inverted line over funky colors

試用其他composition modes以獲得更有趣的效果。

+0

謝謝,工作完美。 – 2012-02-03 14:39:42