2

我尝试将来自 QChartView 类的 RubberBandChanged 信号链接到 MainWindow 类中的特定函数。

主窗口.h

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void rubberZoomAdapt(QRect, QPointF, QPointF);

private:
    Ui::MainWindow *ui;
    QChartView* qcvChart;
    Chart* chart;
};

主窗口.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    qcvChart(new QChartView),
    chart(new Chart)
{
    ui->setupUi(this);

    //Connexion
    QObject::connect(qobject_cast<QGraphicsView*>(this->qcvChart),
                     &QGraphicsView::rubberBandChanged,
                     this,
                     &MainWindow::rubberZoomAdapt);

    this->qcvChart->setChart(this->chart);
    this->qcvChart->setRubberBand(QChartView::HorizontalRubberBand);
}

void MainWindow::rubberZoomAdapt(QRect r, QPointF fp, QPointF tp)
{
    static int i = 0;
    qDebug() << "(rubberZoomAdapt) RubberBand Event: " << QString::number(i++);
}

当我在图表中使用 RubberBand 时,我从不输入 RubberZoomAdapt()。

有什么想法可以解决这个问题吗?

谢谢。

4

1 回答 1

2

问题是,虽然QChartView从它继承QGraphicsView不使用相同QRubberBand的,所以rubberBandChanged信号永远不会发出。

解决方案是寻找 ,QRubberBand因为它是事件的子节点QChartView并过滤它resizeEvent,然后创建我们自己的信号:

*。H

...
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    bool eventFilter(QObject *watched, QEvent *event) override;
public slots:
    void rubberZoomAdapt(QPointF fp, QPointF tp);

signals:
    void rubberBandChanged(QPointF fp, QPointF tp);

private:
    Ui::MainWindow *ui;
    QChartView* qcvChart;
    QChart* chart;
    QRubberBand *rubberBand;
};
...

*.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    qcvChart(new QChartView),
    chart(new QChart)
{
    ui->setupUi(this);

    qcvChart->setChart(chart);
    qcvChart->setRubberBand(QChartView::HorizontalRubberBand);
    rubberBand = qcvChart->findChild<QRubberBand *>();
    rubberBand->installEventFilter(this);

    connect(this, &MainWindow::rubberBandChanged,this, &MainWindow::rubberZoomAdapt);

    setCentralWidget(qcvChart);
    ...
}

...

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == rubberBand && event->type() == QEvent::Resize){
        QPointF fp = chart->mapToValue(rubberBand->geometry().topLeft());
        QPointF tp = chart->mapToValue(rubberBand->geometry().bottomRight());
        emit rubberBandChanged(fp, tp);
    }
    return QMainWindow::eventFilter(watched, event);
}

void MainWindow::rubberZoomAdapt(QPointF fp, QPointF tp)
{
    qDebug() << "(rubberZoomAdapt) RubberBand Event: "<<fp<<tp;
}

完整的示例可以在以下链接中找到

于 2018-03-28T16:44:08.277 回答