我正在尝试制作一个单击按钮后显示图表的应用程序。
我在 MainWindow 类中创建图表。
图表.h
class Chart: public QChart
{
Q_OBJECT
public:
Chart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
QTimer m_timer;
virtual ~Chart();
public slots:
void handleTimeout();
private:
QSplineSeries *m_series;
QStringList m_titles;
QValueAxis *m_axis;
qreal m_step;
qreal m_x;
qreal m_y;
};
图表.cpp
Chart::Chart(QGraphicsItem *parent, Qt::WindowFlags wFlags) :
QChart(QChart::ChartTypeCartesian, parent, wFlags),
m_series(0),
m_axis(new QValueAxis),
m_step(0),
m_x(5),
m_y(1)
{
qsrand((uint)QTime::currentTime().msec());
QObject::connect(&m_timer, &QTimer::timeout, this, &Chart::handleTimeout);
m_timer.setInterval(1000);
m_series = new QSplineSeries(this);
QPen green(Qt::red);
green.setWidth(3);
m_series->setPen(green);
m_series->append(m_x, m_y);
addSeries(m_series);
createDefaultAxes();
setAxisX(m_axis, m_series);
m_axis->setTickCount(5);
axisX()->setRange(0, 10);
axisY()->setRange(-5, 10);
qDebug() << "created";
m_timer.start();
}
Chart::~Chart()
{
qDebug() << "Destroyed";
}
void Chart::handleTimeout()
{
qreal x = plotArea().width() / m_axis->tickCount();
qreal y = (m_axis->max() - m_axis->min()) / m_axis->tickCount();
m_x += y;
m_y = qrand() % 5 - 2.5;
m_series->append(m_x, m_y);
scroll(x, 0);
qDebug() << "Date:";
if (m_x == 100)
m_timer.stop();
}
主类.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
Chart *chart;
protected:
public slots: void slot1();
private:
QDialogButtonBox *buttonBox;
};
主类.cpp
MainWindow::MainWindow()
{
buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(slot1()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(slot2()));
QDockWidget *dock = new QDockWidget(tr("dialog"), this);
dock->setWidget(buttonBox);
addDockWidget(Qt::TopDockWidgetArea, dock);
}
void MainWindow::slot1()
{
Chart *chart = new Chart;
chart->setTitle("Dynamic spline chart");
chart->legend()->hide();
chart->setAnimationOptions(QChart::AllAnimations);
QChartView chartView(chart);
chartView.setRenderHint(QPainter::Antialiasing);
QWidget *window = new QWidget;
formGroupBox = new QGroupBox(tr("Form layout"));
QFormLayout *layout = new QFormLayout;
layout->addWidget(&chartView);
window->setLayout(layout);
window->show();
}
主文件
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWin;
mainWin.show();
return app.exec();
}
Chart 对象正在 MainWindow 类中创建,但立即被销毁。我认为它在继承方面存在一些问题。我不太擅长QT中的继承如果问题解决了会很有帮助。