简体   繁体   中英

How to retrieve the QPainter object in QML Canvas object

I have a QML Canvas, on which I'm drawing in C++ by overriding the paint(QPainter *painter) method and using a bunch of statements that use that painter object.

Stuff like...

void myGraphDisplay::paint (QPainter* painter) {

    QPainterPath path;
    path.MoveTo(0, 0);
    path.LineTo(100, 100);
    painter->strokePath(path, painter->pen());

etc.

Now some time later, another function wants to draw on the canvas, but the painter object is no longer available. I have tried saving it as a private member of the myGraphDisplay class but my application crashes if I try to access it again in the later function.

void myGraphDisplay::updateGraph () {
    QPainterPath path;
    path.MoveTo(100, 0);
    path.LineTo(0, 100);
    painter->strokePath(path, painter->pen()); // where do I get "painter" here?

I also tried

QPainter painter(this);

as shown on the QT reference pages but that gives me an error...

no matching function for call to QPainter::QPainter(myGraphDisplay*)

How do I get the current QPainter object? If it's any help, updateGraph() is a Q_INVOKABLE called from the same QML.

The rules state that the process of painting a QQuickItem occurs in the paint method, not in another method. The generic solution is:

  1. Save the painting information in some attribute of the class.
  2. Invoke the paint method
  3. Implement the logic in the paint method.

* .h

private:
    QPainterPath m_path;

* .cpp

myGraphDisplay::myGraphDisplay(QQuickItem *parent): QQuickItem(parent){
    // default path
    m_path.MoveTo(0, 0);
    m_path.LineTo(100, 100);
}

void myGraphDisplay::updateGraph(){
    QPainterPath path;
    path.MoveTo(100, 0);
    path.LineTo(0, 100);
    m_path = path;
    update();
}

void myGraphDisplay::paint (QPainter* painter) {
    painter->strokePath(m_path, painter->pen());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM