如何在QML中重新绘制封装在QDeclarativeItem中的QWidget

How to repaint QWidget encapsulated in QDeclarativeItem in QML?

本文关键字:绘制 封装 中的 QWidget QDeclarativeItem QML 新绘制      更新时间:2023-10-16

我在C++/QML环境中工作,使用Qt 4.8和QtQuick 1.0。

我有一个QWidget派生类QCustomPlot,并将其封装在一个自定义的QDeclarativeItem派生类中。我使用QGraphicsProxyWidget嵌入QWidget,它在创建时看起来很好。我想定期更新图表,但我根本无法,无论我做什么,它都会停留在我在构造函数中启动的位置。

这是我的代码(有些简化):

flow-grafik.h:

class FlowGrafik : public QDeclarativeItem
{
    Q_OBJECT
public:
    explicit FlowGrafik(QDeclarativeItem *parent = 0);
    ~FlowGrafik();
    void addFlow(double flow);
signals:
public slots:
private:
    QCustomPlot * customPlot;
    QGraphicsProxyWidget * proxy;
    QVector<double> x, y;
};

flowgrafik.cpp:

FlowGrafik::FlowGrafik(QDeclarativeItem *parent) : QDeclarativeItem(parent)
{
    customPlot = new QCustomPlot();
    proxy = new QGraphicsProxyWidget(this);
    proxy->setWidget(customPlot);
    this->setFlag(QGraphicsItem::ItemHasNoContents, false);
    customPlot->setGeometry(0,0,200,200);
    /* WHAT I WRITE HERE WILL BE DISPLAYED */
    // pass data points to graph:
    customPlot->graph(0)->setData(x, y);
    customPlot->replot();

}
FlowGrafik::~FlowGrafik()
{
    delete customPlot;
}
void FlowGrafik::addFlow(double flow)
{
    //THIS PART DOES NOT GET DISPLAYED
    for (int i=0; i<99; ++i)
    {
      y[i] = y[i+1];
    }
    y[99] = flow;
    customPlot->graph(0)->setData(x, y);
    customPlot->replot();
    this->update();
}

mainview.qml:

Rectangle {
    id: flowGrafik
    objectName: "flowGrafik"
    x: 400
    y: 40
    width: 200
    height: 200
    radius: 10
    FlowGrafik {
        id: flowGrafikItem
    }
}

如果有人能告诉我为什么我的QCustomPlot QWidget没有回复,我将不胜感激。

最终的解决方案是在C++代码中创建一个指向QML项的指针。

我无意中在C++中创建了另一个实例,修改了那个实例,并期望QML实例发生更改。

QDeclarativeView mainView;
mainView.setSource(QUrl("qrc:///qml/qml/mainview.qml"));
Flowgrafik * flowGrafik = mainView.rootObject()->findChild<QObject*>(QString("flowGrafikItem"));
//or if Flowgrafik was the main element: Flowgrafik * flowGrafik = mainView.rootObject();
flowGrafik->addFlow(x);