QtCharts 使用信号连接实现柱状图series点击事件
看了很久的demo文件,照着里面可以写但是没能完全理解里面的信号连接:
QObject::connect(seasonSeries, &DrilldownBarSeries::clicked, drilldownChart, &DrilldownChart::handleClicked);
卡了很久,发现QBarSeries是继承于QAbstractBarSeries
于是试着写了按照标准信号连接,结果发现可以实现............
实现代码:
-
.cpp
-
//建立图标
-
QBarSet *barset1 = new QBarSet("OK");
-
//QBarSet *barset2 = new QBarSet("NOK");
-
//输入图标数据
-
*barset1 << 0 << 100 << 66.7 << 33.3;
-
//建立条状图
-
QBarSeries *series = new QBarSeries;
-
//加入数据
-
series->append(barset1);
-
//建立图标
-
QChart *chart = new QChart;
-
//图表加入条状图
-
chart->addSeries(series);
-
//设置表头
-
chart->setTitle("Signals");
-
//设置动画选项
-
chart->setAnimationOptions(QChart::SeriesAnimations);
-
//创建一个QStringList 作为x轴标签
-
QStringList categories;
-
categories << "Laser" << "Temp" << "Plasma" << "Ref";
-
//设置分类轴
-
QBarCategoryAxis *axis = new QBarCategoryAxis();
-
axis->append(categories);
-
//创建默认轴
-
chart->createDefaultAxes();
-
//设置轴X
-
chart->setAxisX(axis, series);
-
//设置图标
-
chart->legend()->setVisible(true);
-
chart->legend()->setAlignment(Qt::AlignBottom);
-
//隐藏图标
-
chart->legend()->hide();
-
//series->setLabelsPosition(QAbstractBarSeries::LabelsOutsideEnd);
-
//建立图表视图
-
QChartView *chartView = new QChartView(ui.chartlabel2);
-
chartView->setChart(chart);
-
//抗锯齿
-
chartView->setRenderHint(QPainter::Antialiasing);
-
chartView->resize(300, 150);
-
chartView->show();
-
//信号和槽的连接
-
connect(series, SIGNAL(clicked(int, QBarSet*)), this, SLOT(chartslot1()));
-
void MainWindow::chartslot1()
-
{
-
QBarSet *barset1 = new QBarSet("OK");
-
*barset1 << qrand() % 5 * 20 << qrand() % 5 * 20;
-
QBarSeries *series = new QBarSeries;
-
series->append(barset1);
-
QChart *chart = new QChart;
-
chart->addSeries(series);
-
chart->setTitle("Overview");
-
chart->setAnimationOptions(QChart::NoAnimation);
-
QStringList categories;
-
categories << "OK" << "NOK";
-
QBarCategoryAxis *axis = new QBarCategoryAxis();
-
axis->append(categories);
-
chart->createDefaultAxes();
-
chart->setAxisX(axis, series);
-
chart->axisX()->setRange(10, 50);
-
chart->legend()->setVisible(true);
-
chart->legend()->setAlignment(Qt::AlignBottom);
-
chart->legend()->hide();
-
//series->setLabelsPosition(QAbstractBarSeries::LabelsOutsideEnd);
-
//建立图表视图
-
//将图表显示在ui.chartlabel1上
-
QChartView *chartView = new QChartView(ui.chartlabel1);
-
chartView->setChart(chart);
-
//抗锯齿
-
chartView->setRenderHint(QPainter::Antialiasing);
-
//实现鼠标左键选择放大,右键选择缩小
-
//chartView->setRubberBand(QChartView::RectangleRubberBand);
-
chartView->resize(300, 150);
-
chartView->show();
-
// 设置数据系列标签的位置于数据柱内侧上方
-
series->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
-
// 设置显示数据系列标签
-
series->setLabelsVisible(true);
-
}
代码注释已经很详细了.
最近在学qtcharts发现自己qt和c++基础不扎实.连demo都看不来.或者说看懂了自己没办法熟练使用.还是得练啊!