How to draw a rectangle on a graph with XY axes Qt

时间:2016-04-07 10:32:45

标签: c++ qt

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?

4 个答案:

答案 0 :(得分:2)

这是您需要的一个例子:

#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();
    }
};

答案 1 :(得分: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);
}

答案 2 :(得分:1)

您只能使用普通QWidget并重新实现paintEvent()功能。这幅画将由QPainter实现。

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


或者您可以使用QGraphicsView / QGraphicsScene框架:http://doc.qt.io/qt-4.8/graphicsview.html

答案 3 :(得分:1)

您可以将QCPItemRect添加到QCustomPlot的{​​{3}}来执行此操作。这似乎是最简单的解决方案。