Drawing inside a widget in Qt

I created a very simple graphical interface that has a button and a widget "Graphic View" from Display Widgets. When I click the button, I want the line to be drawn through the "Graphics" widget. I changed the name of the Graphic View widget to gv by right-clicking the widget in the design view and then selecting change objectName. I can’t understand what the line should look like. I read various Qt texts that provided information about QPainter, PaintEvent, etc. But I was more confused.

Please help me with this. A small code sample should really be useful to me, as I am new to Qt.

+3
source share
3 answers

QGraphicsView QGraphicsItem, QGraphicsScene. QGraphicsLineItem addLine QGraphicsScene.

Qt, . " " , , .

: http://doc.trolltech.com/4.6/examples-graphicsview.html

+4

QPainter

paintevent

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

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

}

QImage ,

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

, QPainter * , .

+3

QPainter, .

QPainter , GUI. ( QPoint, QLine, QRect, QRegion QPolygon) , . , qpaint, : QWidget, QImage, QPixmap, QPicture, QPrinter QOpenGLPaintDevice, , QGraphic qgraphic scene , qgraphic.

:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    scene=new QGraphicsScene(this); //allocate your scene to your main widget
    view=new QGraphicsView(scene,this);//here is your view
    pixmap=new QPixmap(QSize(700,700));// paint device
    view->resize(700,700);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::paintEvent(QPaintEvent *e)
{
    painter=new QPainter;// create your painter
    painter->begin(pixmap);//add painter to your paint device

    painter->fillRect(0,0,300,300,Qt::red);//draw rect
    painter->setPen(Qt::yellow);
    painter->drawLine(0,0,700,700);//draw line
    painter->end();
    scene->addPixmap(*pixmap);// add your paint device to your scene
    view->show();//then show your view

} 
-1

Source: https://habr.com/ru/post/1763854/


All Articles