Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

painting inside widget in Qt

Tags:

c++

qt

I created a very simple GUI that has a push button and a "Graphics View" widget from Display Widgets. On pushing the button I want a line to be drawn across the "Graphics View" widget. I have changed the name of the "Graphics View" widget to gv by right-clicking the widget in design view and then selecting change objectName. I am not able to understand how should the line be drawn. I read various texts on Qt that provided information about QPainter, PaintEvent etc. But I got more confused.

Kindly help me with this. A small sample code shall be really helpful for me as I am new to Qt.

like image 262
krackoder Avatar asked Nov 19 '25 21:11

krackoder


2 Answers

A QGraphicsView is meant for displaying instances of QGraphicsItem that are managed by a component called QGraphicsScene. In your case, you'd create a QGraphicsLineItem and add it to the scene, or directly create it as an item of the scene by calling the addLine member function of your QGraphicsScene instance.

All drawing will be done by Qt itself, assuming that you did connect your graphics view and scene properly. Be sure to read The Graphics View Framework, which gives you an overview over how these components work.

You will find code examples of how to manage and display a scene using the graphics view framework here: http://doc.trolltech.com/4.6/examples-graphicsview.html

like image 110
Jim Brissom Avatar answered Nov 22 '25 11:11

Jim Brissom


You can paint into a QPainter

Either override the paintevent and draw there

void MyDisplayWidget::paintEvent(QPaintEvent*)
{
    QPainter p(this);   
    p.setPen(Qt::green);

    p.drawText(10,10,"hello");

}

Or draw into a QImage and display that

QImage image = QImage(size);
QPainter p(&image);
p.drawText(10,10,"hello");
// draw or save QImage 

You can even use the same draw function taking a QPainter * to draw either direct to the screen or to an image.

like image 36
Martin Beckett Avatar answered Nov 22 '25 10:11

Martin Beckett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!