I can't use a function from C ++



  • Hi.
    I can't use a function from C ++.
    Created a class:

    class DataWorking : public QObject
    {
    public:
        DataWorking();
        ~DataWorking();
        Q_INVOKABLE  int randomNumber;
        int winNumber;
        int progressNumber;
        int roundNumber;// число раундов
     
    public slots:
        Q_INVOKABLE  void setRandomNamber(int first, int last);
     
    };
    
    DataWorking::DataWorking()
    {
        winNumber = 0;
        progressNumber = 0;
        roundNumber = 20;
    }
    
    DataWorking::~DataWorking()
    {
        winNumber = 0;
        progressNumber = 0;
    }
    
    void DataWorking::setRandomNamber(int first, int last)
    {
        //randomNumber = Random::get(first, last);
        randomNumber=654;
        qDebug()<<"randomNamber = "<<randomNumber;
    }
    
    

    main.cpp:

    int main(int argc, char *argv[])
    {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
    
        DataWorking dataWorking;
    
        QQmlContext *context = engine.rootContext();   
           context->setContextProperty("dataWorking", &dataWorking);
    
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        if (engine.rootObjects().isEmpty())
            return -1;
    
        return app.exec();
    }
    

    I specify connection in main.qml:

       Connections
         {
             target: dataWorking // Указываем целевое соединение
     
         }
    

    and trying to call a class function:

       page1Button0.onClicked: //left button
        {
            dataWorking.setRandomNamber(1,55)
        }
    

    but I get the error: Property 'setRandomNamber' of object QObject (0x22fd40) is not a function.
    Tell me please, how can I use this function?



  • @Mikeeeeee said in I can't use a function from C ++:

    DataWorking

    I think you have to change the DataWorking constructor, to call QObject constructor, and very important add Q_OBJECT macro to enable QObject magic:

    class DataWorking : public QObject
    {
        Q_OBJECT
    public:
        explicit DataWorking(QObject *parent = 0);
     ...
    

    in cpp

    DataWorking::DataWorking(QObject *parent) : QObject(parent)
    {
        winNumber = 0;
        progressNumber = 0;
        roundNumber = 20;
    }
    

    Other remark, Q_INVOKABLE is only required if function is not a slot. slots are accessible from QML.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.