Skip to content

Instantly share code, notes, and snippets.

@hasselmm
Created September 14, 2018 09:19
Show Gist options
  • Save hasselmm/c527890cfd28ea9996a869ed023eaf1a to your computer and use it in GitHub Desktop.
Save hasselmm/c527890cfd28ea9996a869ed023eaf1a to your computer and use it in GitHub Desktop.
//
// Sometimes QML still surprise by really just doing the right thing.
// For instance the following lines:
//
// console.info("Status:", Status.Unknown, Status.Good, Status.Warning, Status.Failing);
// console.info("Sensor:", Sensor.Unknown, Sensor.Good, Sensor.Warning, Sensor.Failing);
//
// really print:
//
// qml: Status: 0 1 2 3
// qml: Sensor: 0 1 2 3
//
// eventhough there is no meta enum for Unknown in Sensor.
// It just does smartly because the property most likely needs it.
//
#include <QCoreApplication>
#include <QQmlComponent>
#include <QQmlEngine>
namespace SharedEnumTest {
class Status
{
Q_GADGET
public:
enum Value { Unknown, Good, Warning, Failing };
Q_ENUM(Value)
};
class Sensor : public QObject
{
Q_OBJECT
Q_PROPERTY(SharedEnumTest::Status::Value status MEMBER m_status CONSTANT FINAL)
public:
using QObject::QObject;
~Sensor() override = default;
private:
Status::Value m_status = Status::Unknown;
};
} // namespace SharedEnumTest
int main(int argc, char *argv[])
{
QCoreApplication app{argc, argv};
qmlRegisterType<SharedEnumTest::Sensor>("SharedEnumTest", 1, 0, "Sensor");
qmlRegisterUncreatableType<SharedEnumTest::Status>("SharedEnumTest", 1, 0, "Status", "Gadgets cannot be instantiated in QML");
const QByteArray qml = R"(
import SharedEnumTest 1.0
import QtQml 2.2
QtObject {
Component.onCompleted: {
console.info("Status:", Status.Unknown, Status.Good, Status.Warning, Status.Failing);
console.info("Sensor:", Sensor.Unknown, Sensor.Good, Sensor.Warning, Sensor.Failing);
}
}
)";
QQmlEngine engine;
QQmlComponent test{&engine};
test.setData(qml, {});
test.create();
return EXIT_SUCCESS;
}
#include "main.moc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment