Linux technical support - [email protected]


Qt qwt example draw graph

main.cpp

    #include "mainwindow.h"
    #include <QApplication>
     
     
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
     
        MyFirstThread t1;
        t1.start();
     
        QObject::connect(&t1, SIGNAL(timeHasCome()), &w, SLOT(drawGraph()));
     
        return a.exec();
    }

mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QDebug>
     
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        this->drawGraph();
    }
     
    MainWindow::~MainWindow()
    {
        delete ui;
    }
     
    void MainWindow::drawGraph()
    {
        ui->qwtPlot->setTitle(QString::fromUtf8("Sima"));
     
        ui->qwtPlot->setAxisTitle(QwtPlot::xBottom,QString::fromUtf8("time"));
        ui->qwtPlot->setAxisScale(QwtPlot::xBottom,0.0,59.0);
        ui->qwtPlot->setAxisTitle(QwtPlot::yLeft,QString::fromUtf8("CPU usage"));
        ui->qwtPlot->setAxisScale(QwtPlot::yLeft,0.0,100.0);
     
        myLine = new QwtPlotCurve(QString(""));
        myLine->setPen(QPen(Qt::darkGreen));
     
        int v1 = rand() % 100;
        qDebug() << v1;
        double X2[4], Y2[4];
     
        X2[0] = 0.0;
        X2[1] = 25.0;
        X2[2] = 59.5;
     
        Y2[0] = 1.0;
        Y2[1] = v1;
        Y2[2] = 10.1;
     
        ui->qwtPlot->clear();
     
        myLine->setData(X2,Y2,3);
        myLine->attach(ui->qwtPlot);
        myLine->setCurveAttribute(QwtPlotCurve::Fitted,true);
        ui->qwtPlot->replot();
    }

mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
     
    #include <QMainWindow>
     
    #include <qwt_plot_canvas.h>
    #include <qwt_legend.h>
    #include <qwt_plot_grid.h>
    #include <qwt_plot_curve.h>
    #include <qwt_symbol.h>
     
    #include <QThread>
     
    namespace Ui {
    class MainWindow;
    }
     
    class MyFirstThread : public QThread
    {
        Q_OBJECT
     
    signals:
        void timeHasCome();
     
    private:
        void run()
        {
            while(1)
            {
                emit timeHasCome();
                sleep(1);
            }
        }
    };
     
     
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
     
    public slots:
        void drawGraph();
     
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
     
     
    private:
        Ui::MainWindow *ui;
        QwtLegend *leg;
        QwtPlotGrid *grid;
        QwtPlotCurve *myLine;
    };
     
    #endif // MAINWINDOW_H

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>