我使用QChart&创建了一个图表。 QGraphicsScene& QGraphicsView,但图表不会在窗口更改时自动放大或缩小。我怎么能这样做?我不会在QChart,QGraphicsScene或QGraphicsView类中有任何信号或插槽。 我知道我可以使用QChart& QChartView,但我想要QChart& QGraphicsScene& QGraphicsView用于某种目的。这是我绘制图表的代码:
void MainWindow::on_actionDraw_Sine_Chart_triggered()
{
QSplineSeries *spline = new QSplineSeries;
for (double x = -M_PI; x < M_PI; x += 0.01) {
spline->append(x, sin(x));
}
spline->setName(tr("Sine Curve"));
QChart *chart = new QChart;
chart->addSeries(spline);
chart->createDefaultAxes();
chart->axisX()->setRange(-4, 4);
chart->axisY()->setRange(-1.2, 1.2);
chart->setGeometry(ui->graphicsView->rect());
QGraphicsScene *scene = new QGraphicsScene;
scene->addItem(chart);
ui->graphicsView->setScene(scene);
}
完整代码可用here。
答案 0 :(得分:0)
您必须跟踪viewport
的尺寸变化并更改QChart
的尺寸,因为我们使用eventFilter
,但由于这是另一种方法,您需要该图表是该类的一个属性。
除此之外,不建议在一个插槽中创建场景,但在构造函数中,与QChart相同,然后只添加系列。
<强> *的.h 强>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
...
bool eventFilter(QObject *watched, QEvent *event); // +++
private:
Ui::MainWindow *ui;
QChart *chart; // +++
QGraphicsScene *scene; // +++
};
<强> *。CPP 强>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene;
chart = new QChart;
scene->addItem(chart);
ui->graphicsView->setScene(scene);
ui->graphicsView->viewport()->installEventFilter(this);
}
void MainWindow::on_actionDraw_Sine_Chart_triggered(){
QSplineSeries *spline = new QSplineSeries;
for (double x = -M_PI; x < M_PI; x += 0.01) {
spline->append(x, sin(x));
}
spline->setName(tr("Sine Curve"));
chart->addSeries(spline);
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if(watched == ui->graphicsView->viewport() && event->type() == QEvent::Resize){
if(chart)
chart->resize(ui->graphicsView->viewport()->size());
}
return QMainWindow::eventFilter(watched, event);
}