4

8 months ago here was such a question - how to embed a qwidget-based object into QML,http://doc.qt.digia.com/4.7/declarative-cppextensions-qwidgets.html Qt5. Embed QWidget object in QML. Has the situation changed? Or for some complex applications, using own reimplemented paintEvent, we can use only classic Qt?

Community
  • 1
  • 1
aptypr
  • 417
  • 5
  • 15
  • 1
    Possible duplicate of [Qt5. Embed QWidget object in QML](https://stackoverflow.com/questions/13014415/qt5-embed-qwidget-object-in-qml) – fkorsa Jun 22 '18 at 08:21
  • The original question does have answers that explain how to embed QWidgets inside Qt Quick 2 scenes. This question is thus merely a duplicate. – fkorsa Jun 22 '18 at 08:23

1 Answers1

5

QQuickPaintedItem can be used for drawing with QPainter API.

In the code below I tried to wrap QCalendarWidget into QQuickPaintedItem. It renders correctly, but doesn't process input events:

.h:

class CalendarControl : public QQuickPaintedItem
{
    Q_OBJECT
public:
    explicit CalendarControl(QQuickItem *parent = 0);
    virtual ~CalendarControl();

    void paint(QPainter *painter);
…
protected:
    QCalendarWidget *calendar_;
}

.cpp:

CalendarControl::CalendarControl(QQuickItem *parent)
    : QQuickPaintedItem(parent)
    , calendar_(NULL)
{
    setOpaquePainting(true);
    setAcceptHoverEvents(true);
    setAcceptedMouseButtons(Qt::AllButtons);

    calendar_ = new QCalendarWidget;

    // Calendar will draw partially if update is called right here
    QTimer::singleShot(0, this, SLOT(update()));
}

void CalendarControl::paint(QPainter *painter)
{
    calendar_->render(painter, QPoint(), QRegion(),
        QCalendarWidget::DrawWindowBackground | QCalendarWidget::DrawChildren);
}

To catch mouse events, override

void hoverEnterEvent(QHoverEvent *event);
void hoverLeaveEvent(QHoverEvent *event);
void hoverMoveEvent(QHoverEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);

I weren't able to pass them to QCalendarWidget though, it ignores them. But when creating a wrapper for custom QWidget, you can probably pass these events directly to it.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
Zmey
  • 2,304
  • 1
  • 24
  • 40