我想要实现的是以下内容:我有一个 QGraphicsScene
,其中显示了一个 QGraphicsPixmapItem
。像素图有多种颜色,我需要在像素图中画一条线,该线必须在每个点都可见且可识别。
我的想法是画一条线,其中每个像素都具有像素图相对像素的负(互补)颜色。于是想到了QGraphicsItem
的子类化,重新实现paint()
的方法来绘制多色线。
但是我卡住了,因为我不知道如何从 paint
函数中检索像素图的像素信息,即使我发现了,我也想不出用这种方式画线的方法。
你能给我一些关于如何进行的建议吗?
最佳答案
您可以使用 QPainter
的 compositionMode
属性非常轻松地执行此类操作,而无需读取源像素颜色。
带有自定义 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);
}
};
这将输出类似于下图的内容:尝试使用其他 composition modes 以获得更有趣的效果。
关于qt - 在 Qt 中绘制多色线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129955/