64 bit integers in QML

五迷三道 提交于 2020-01-01 10:13:26

问题


How do I deal with 64 bit integers in QML? I know that useless Javascript can't handle them normally as it uses doubles for everything, and if I try to use them in a signal, everything gets set to undefined. Is there a way around this? Perhaps I have to use a QVariant or something?


回答1:


Create your own Integer64 class derived from QObject and give it the functions you need, like

class Integer64 : public QObject
{
    Q_OBJECT

public:
    // ...
    Q_PROPERTY(QString value READ value WRITE setValue NOTIFY valueChanged)
    QString value() const;
    void setValue(QString value);

    Q_INVOKABLE void add(Integer64 * other);
    Q_INVOKABLE void subtract(Integer64 * other);
    Q_INVOKABLE void multiply(Integer64 * other);
    Q_INVOKABLE void divide(Integer64 * other);
    // ...

where you use value() to get a string representation in QML and setValue() to set a value from a string representation.

An additional constructor can be used to efficiently create Integer64 from C++

public:
    explicit Integer64(QObject *parent = 0);
    explicit Integer64(qint64 value, QObject *parent);
    // ...

Then register the type to QML

qmlRegisterType<Integer64>("MyModules", 1, 0, "Integer64");



回答2:


If you do not need methods on your 64-bit object, use Q_GADGET to create a type that you can store in a QVariant:

struct Int64Data
{
    Q_GADGET
public:
    int64_t value;
};

Register using:

qRegisterMetaType<Int64Data>();

You can pass this type to QML:

Q_INVOKABLE QVariant getMax() {
    Int64Data idx;
    idx.value = INT64_MAX;
    return QVariant::fromValue(idx);
}

You cannot manipulate it directly in QML, but you can pass to slots:

Q_INVOKABLE void dumpIndex(const QVariant idx) const {
    if (idx.canConvert<Int64Data>()) {
        auto data = qvariant_cast<Int64Data>(idx);
        qDebug() << "Index value:" << data.value;
    }
}



回答3:


You can include qglobal.h and use qint64/quint64, or qlonglong/qulonglong, which are typedefs for long long int and unsigned long long int respectively. These are recognised by the QML engine. However, creating your own typedefs, or using long long explicitly, seems not to work.



来源:https://stackoverflow.com/questions/23781083/64-bit-integers-in-qml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!