tags:

views:

68

answers:

2

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.

+2  A: 

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.

Martin Beckett
I created a widget MyDisplayWidget. But I have designed a form mainwindow.ui using Qt's drag-n-drop facility. How do I include this new widget in that gui ?
nishant
There is a lot of coding to be done to be able to use custom widgets in Qt's designer application. If you want to use your custom widget in your mainwindow, use the designer application to put a place holder widget (or frame) and then in the code for your main window, create an instance of your custom widget and add it to the place holder.
Arnold Spence
@nishant-4545: Promoted widgets are a quick way to get the job done. See http://doc.trolltech.com/4.6/designer-using-custom-widgets.html
Steve S
@Arnold Spence - sorry this wasn't a very good example for just drawing a line on a button. I'm using it to draw video into a GLWidget
Martin Beckett
No worries. I was just trying to fill in some additional info for the OP after he mentioned he was using Qt's Designer :)
Arnold Spence
+3  A: 

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

Jim Brissom