[SOLVED]How to draw a filled rectangle on QGraphicsScene using QPainter



  • Isn't there something like scene->addFilledRect(......)



  • You can add a QGraphicsRectItem to the scene .

    something like

    @#include <QtGui>
    int main(int argc,char ** argv)
    {
    QApplication app(argc,argv);

    QGraphicsScene scene;
    QGraphicsView view(&scene);
    QGraphicsRectItem* item1 = new QGraphicsRectItem(0,0,100,100);
    QGraphicsRectItem* item2 = new QGraphicsRectItem(0,100,100,100);
    QGraphicsRectItem* item3 = new QGraphicsRectItem(100,0,100,100);
    QGraphicsRectItem* item4 = new QGraphicsRectItem(100,100,100,100);

    item1->setBrush(QBrush(Qt::red));
    item2->setBrush(QBrush(Qt::green));
    item3->setBrush(QBrush(Qt::blue));
    item4->setBrush(QBrush(Qt::yellow));

    scene.addItem(item1);
    scene.addItem(item2);
    scene.addItem(item3);
    scene.addItem(item4);

    view.setFixedSize(250,250);
    view.setWindowTitle("QGraphicsRectItem Color Example");
    view.show();

    return app.exec();
    }@



  • Thanks a lot! such a good piece of code!



  • Is it possible to draw the above rectangles with gradient effects like, light in middle and dark at top and bottom, to give a 3D effect.



  • Yes for the gradients you can check "QLinearGradient Class":http://doc.qt.nokia.com/4.7-snapshot/qlineargradient.html#details

    for eg

    @QLinearGradient grad1(0, 20, 0, 110);

    grad1.setColorAt(0.1, Qt::red);
    grad1.setColorAt(0.5, Qt::yellow);
    grad1.setColorAt(0.9, Qt::red);

    QLinearGradient grad2(0, 20, 0, 110);

    grad2.setColorAt(0.1, Qt::green);
    grad2.setColorAt(0.5, Qt::white);
    grad2.setColorAt(0.9, Qt::green);

    QLinearGradient grad3(0, 20, 0, 110);

    grad3.setColorAt(0.1, Qt::blue);
    grad3.setColorAt(0.5, Qt::white);
    grad3.setColorAt(0.9, Qt::blue);

    QLinearGradient grad4(0, 20, 0, 110);

    grad4.setColorAt(0.1, Qt::yellow);
    grad4.setColorAt(0.5, Qt::red);
    grad4.setColorAt(0.9, Qt::yellow);

    item1->setBrush(grad1);
    item2->setBrush(grad2);
    item3->setBrush(grad3);
    item4->setBrush(grad4);@

    Which displays as

    !http://imageshack.us/a/img259/6941/80671453.png(gradient)!



  • Thanks for your reply!



  • Glad to be of some help. You are welcome :)



  • good work sam....!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.