gpt4 book ai didi

c++ - 当窗口大小改变时,如何在 Qt 中自动缩放图表?

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:47 28 4
gpt4 key购买 nike

我使用 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 .

最佳答案

您必须跟踪 viewport 的大小变化并更改 QChart 的大小,为此我们使用 eventFilter,但是由于这是您需要的另一种方法,图表是该类的属性。

除此之外不建议在one slot中创建场景,而是在constructor中,和QChart一样,然后只添加series。

*.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);
}

关于c++ - 当窗口大小改变时,如何在 Qt 中自动缩放图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50064727/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com