Register QObject classes as QML elements via macros

Using manual registration with qmlRegisterType (or
qmlRegisterUncreatableType) isn't ideal, because Qt Creator can't pick
up on it. When using the macros, autocompletion & unknown type warnings
in the code disappear.
This commit is contained in:
ItsDrike 2024-12-03 15:05:22 +01:00
parent 629676428f
commit 883d766dc3
Signed by: ItsDrike
GPG key ID: FA2745890B7048C0
4 changed files with 9 additions and 3 deletions

View file

@ -2,11 +2,14 @@
#define COLUMNSLOT_H #define COLUMNSLOT_H
#include <QObject> #include <QObject>
#include <qqmlintegration.h>
#include "playingcard.h" #include "playingcard.h"
class ColumnSlot : public QObject class ColumnSlot : public QObject
{ {
Q_OBJECT Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("Use C++ logic to instantiate")
Q_PROPERTY(PlayingCard* card READ card CONSTANT) Q_PROPERTY(PlayingCard* card READ card CONSTANT)
Q_PROPERTY(bool revealed READ isRevealed NOTIFY revealedChanged) Q_PROPERTY(bool revealed READ isRevealed NOTIFY revealedChanged)

View file

@ -2,12 +2,15 @@
#define GAMESTATE_H #define GAMESTATE_H
#include <QObject> #include <QObject>
#include <qqmlintegration.h>
#include "playingcard.h" #include "playingcard.h"
#include "columnslot.h" #include "columnslot.h"
class GameState : public QObject class GameState : public QObject
{ {
Q_OBJECT Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("Use C++ logic to instantiate")
Q_PROPERTY(QList<PlayingCard*> drawPile READ drawPile NOTIFY drawPileChanged) Q_PROPERTY(QList<PlayingCard*> drawPile READ drawPile NOTIFY drawPileChanged)
Q_PROPERTY(QList<PlayingCard*> throwawayPile READ throwawayPile NOTIFY throwawayPileChanged) Q_PROPERTY(QList<PlayingCard*> throwawayPile READ throwawayPile NOTIFY throwawayPileChanged)
Q_PROPERTY(QList<QList<ColumnSlot*>> columns READ columns NOTIFY columnsChanged) Q_PROPERTY(QList<QList<ColumnSlot*>> columns READ columns NOTIFY columnsChanged)

View file

@ -15,9 +15,6 @@ int main(int argc, char *argv[])
[]() { QCoreApplication::exit(-1); }, []() { QCoreApplication::exit(-1); },
Qt::QueuedConnection); Qt::QueuedConnection);
qmlRegisterUncreatableType<PlayingCard>("Solitare", 1, 0, "PlayingCard", "PlayingCard cannot be directly created in QML. Use C++ logic to instantiate.");
qmlRegisterUncreatableType<ColumnSlot>("Solitare", 1, 0, "ColumnSlot", "ColumnSlot cannot be directly created in QML. Use C++ logic to instantiate.");
GameState gameState; GameState gameState;
gameState.dealCards(); gameState.dealCards();
gameState.drawNextCard(); gameState.drawNextCard();

View file

@ -2,10 +2,13 @@
#define PLAYINGCARD_H #define PLAYINGCARD_H
#include <QObject> #include <QObject>
#include <qqmlintegration.h>
class PlayingCard : public QObject class PlayingCard : public QObject
{ {
Q_OBJECT Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("Use C++ logic to instantiate")
Q_ENUMS(Value) Q_ENUMS(Value)
Q_ENUMS(Suit) Q_ENUMS(Suit)