Udvardi Péter
Udvardi Péter

Reputation: 43

Qt quick 2 paint method doesn't get called

I created a simple Qt quick application and I have an issue drawing with QQuickPaintedItem. I checked in debug mode if the paint gets called, but doesn't. Anyway here's my code:

Source:

ParticleHandler::ParticleHandler(QQuickPaintedItem *parent) : QQuickPaintedItem(parent)
{
    setFlag(QQuickItem::ItemHasContents);
    particle = new Particle();
}
void ParticleHandler::paint(QPainter *painter)
{
    QPen pen = QPen(m_color);
    painter->setPen(pen);
    painter->setRenderHints(QPainter::Antialiasing, true);
    painter->drawEllipse(particle->Position.x,particle->Position.y,particle->Radius/2,particle->Radius/2);
}

Header:

ParticleHandler(QQuickPaintedItem *parent = 0);
void paint(QPainter *painter);

Upvotes: 4

Views: 3277

Answers (4)

benlau
benlau

Reputation: 301

Try to add this line after the class declaration

QML_DECLARE_TYPE(ParticleHandler)

Upvotes: 0

user2423772
user2423772

Reputation: 186

Try setting the width and height of your custom item.

import QtQuick 2.0
import Fizika 1.0
Rectangle
{
  width: 360
  height: 360
  Particle
    { 
     width: 100
     height: 100
     radius: 20
     x: 100
     y: 200
     color: "red"
    }
}

Upvotes: 8

Thomas McGuire
Thomas McGuire

Reputation: 5466

Make sure you call update() at some point, which will schedule a repaint.

As a unrelated side note, be careful about threading - paint() is called from the render thread, so you need proper syncronization for things like particle.

Upvotes: 1

ksimons
ksimons

Reputation: 3826

It's not obvious without seeing the rest of the code what the main problem is, but here's a fully self-contained example. Maybe it'll help.

#include <QGuiApplication>
#include <QPainter>
#include <QtQuick>

class PaintedItem : public QQuickPaintedItem {
    Q_OBJECT
public:
    PaintedItem(QQuickItem *parent = 0) : QQuickPaintedItem(parent) {
    }

    void paint(QPainter *painter) {
        painter->fillRect(contentsBoundingRect(), Qt::red);
    }
};

int main(int argc, char *argv[])
{
    QGuiApplication a(argc, argv);

    qmlRegisterType<PaintedItem>("mymodule", 1, 0, "PaintedItem");

    QQuickView view(QUrl("qrc:///qml/main.qml"));
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.resize(500, 500);
    view.show();

    return a.exec();
}

#include "main.moc"

And the contents of main.qml:

import QtQuick 2.0
import mymodule 1.0

Rectangle {
    color: "black"

    PaintedItem {
        anchors.centerIn: parent
        width: 50
        height: 50
    }
}

Upvotes: 2

Related Questions