Qt如何连接rubberBandChanged信号

时间:2018-03-28 15:27:50

标签: c++ qt qt5 qt-signals qtchart

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

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;
};

MainWindow.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()。

有任何想法来解决这个问题吗?

感谢。

1 个答案:

答案 0 :(得分: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;
}

完整示例可在以下link

中找到