Qt多边形的线性渐变

时间:2014-05-22 16:17:21

标签: c++ qt

我想用线性渐变颜色填充多边形,我不确定如何实现它。到目前为止,我正在使用以下代码。

std::vector<Element*> elems = m_mesh->getElements();

for (unsigned int i=0; i<elems.size(); ++i)
{
    std::vector<Node*> nodes = elems[i]->getNodes();


    QPolygon elepolygon;
    unsigned int j;
    for (j=0; j<nodes.size(); ++j)
    {
        elepolygon << QPoint(nodes[j]->x()*scalex+shiftx,nodes[j]->y()*scaley+shifty);
    }


    int r = qrand() % ((255 + 1) - 0);
    int g = qrand() % ((255 + 1) - 0);
    int b = qrand() % ((255 + 1) - 0);

    QBrush brush(QColor(r,g,b));

    QPainterPath tmpPath;
    tmpPath.addPolygon(elepolygon);
    painter.fillPath(tmpPath,brush);
    painter.drawPolygon(elepolygon);

}

1 个答案:

答案 0 :(得分:1)

您可以创建QLinearGradient,使用setColorAt功能设置不同停留点的颜色,并将画家的画笔设置为创建的QLinearGradient

    painter->setPen(QPen(Qt::black, 3));

    QLinearGradient gradient(-400,-400,400,400);
    gradient.setColorAt(0, QColor(110,110,110));
    gradient.setColorAt(0.27, QColor(230,230,230));
    gradient.setColorAt(0.44, QColor(110,110,110));
    gradient.setColorAt(0.76, QColor(230,230,230));
    gradient.setColorAt(1, QColor(110,110,110));

    painter->setBrush(gradient);

    painter->drawPolygon(elepolygon);

在此示例中,插值区域介于(-400,-400)和(400,400)之间。您可以使用任意定义渐变方向的那些。