【发布时间】:2018-02-14 19:08:21
【问题描述】:
我有一个自定义的 Qt 5 小部件,它使用 QPainter 呈现自己。我希望能够绘制一条线,其中每个顶点都与不同的颜色相关联,并且颜色会沿着连接点的线进行相应的插值。这可能吗?
【问题讨论】:
我有一个自定义的 Qt 5 小部件,它使用 QPainter 呈现自己。我希望能够绘制一条线,其中每个顶点都与不同的颜色相关联,并且颜色会沿着连接点的线进行相应的插值。这可能吗?
【问题讨论】:
我认为您需要逐行绘制。假设这是可以接受的,那么使用合适的 QLinearGradient 初始化的 QPen 应该可以工作...
class widget: public QWidget {
using super = QWidget;
public:
explicit widget (QWidget *parent = nullptr)
: super(parent)
{
}
protected:
virtual void paintEvent (QPaintEvent *event) override
{
super::paintEvent(event);
QPainter painter(this);
/*
* Define the corners of a rectangle lying 10 pixels inside
* the current bounding rect.
*/
int left = 10, right = width() - 10;
int top = 10, bottom = height() - 10;
QPoint top_left(left, top);
QPoint top_right(right, top);
QPoint bottom_right(right, bottom);
QPoint bottom_left(left, bottom);
/*
* Insert the points along with their required colours into
* a suitable container.
*/
QVector<QPair<QPoint, QColor>> points;
points << qMakePair(top_left, Qt::red);
points << qMakePair(top_right, Qt::green);
points << qMakePair(bottom_right, Qt::blue);
points << qMakePair(bottom_left, Qt::black);
for (int i = 0; i < points.size(); ++i) {
int e = (i + 1) % points.size();
/*
* Create a suitable linear gradient based on the colours
* required for vertices indexed by i and e.
*/
QLinearGradient gradient;
gradient.setColorAt(0, points[i].second);
gradient.setColorAt(1, points[e].second);
gradient.setStart(points[i].first);
gradient.setFinalStop(points[e].first);
/*
* Set the pen and draw the line.
*/
painter.setPen(QPen(QBrush(gradient), 10.0f));
painter.drawLine(points[i].first, points[e].first);
}
}
};
上面的结果类似于...
(注意:使用QPainterPath 和QPainterPathStroker 可能有更好的方法来实现这一点,但我不确定是否基于文档。我已经看过了。)
【讨论】: