1

I want to draw a rectangle on a graph with XY axes using Qt. I have found QCustomPlot widget, but it is not what i need (or i did not understand how to apply it to solve my problem).enter image description here

enter image description here

Please any suggestions how to make it work?

Bob
  • 1,433
  • 1
  • 16
  • 36

4 Answers4

2

This is an example of what you need:

#include <QWidget>
#include <QPainter>

class MyPlot : public QWidget
{
    Q_OBJECT

public:
    MyPlot(QWidget *parent = 0)
        : QWidget(parent)
    {
    }


protected:
    void paintEvent(QPaintEvent *event)
    {
        QPainter painter(this);

        painter.save();
        painter.translate(2, height() -2); // 2 pixels between axes and the windows frame
        painter.scale(1,-1);

        QPen pen;
        pen.setWidth(2);
        painter.setPen(pen);

        // X Axis
        painter.drawLine(0,0, width(),0);

        // Y Axis
        painter.drawLine(0,0, 0,height());

        pen.setWidth(4);
        painter.setPen(pen);

        // Rect
        painter.drawRect(10,10, 60,80);

        painter.restore();
    }
};
Meena Alfons
  • 1,230
  • 2
  • 13
  • 30
1

The simplest override paintEvent in QWidget:

void MyWidget::paintEvent(QPaintEvent * event)
{
  Q_UNUSED(event);
  QPainter painter(this);
  painter.drawLine(0, 10, 100, 10);
  painter.drawLine(10, 0, 10, 100);
  painter.drawRect(20, 20, 30, 30);
}
Hurr
  • 55
  • 1
  • 8
1

You can use just the plain QWidget and reimplement it's paintEvent() function. The painting would be realized by the QPainter.

void CMyWidget::paintEvent(QPaintEvent* event)
{
    QPainter p(this);
    p.drawLine(...);
    p.drawRect(...);
    p.drawText(...);
}


Or you can use a QGraphicsView / QGraphicsScene framework: http://doc.qt.io/qt-4.8/graphicsview.html

Tomas
  • 2,170
  • 10
  • 14
1

You can do it by adding QCPItemRect to QCPLayer of QCustomPlot. It seems to be the easiest solution.

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
Andrei R.
  • 2,374
  • 1
  • 13
  • 27
  • if someone would like to get the [answer](http://stackoverflow.com/questions/29444939/qcustomplot-show-item-on-qcpaxisrect-below-customplot) – Bob Apr 07 '16 at 13:37