天天看點

qml使用c++中信号

#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>
class test : public QObject
{
    Q_OBJECT
public:
    explicit test(QObject *parent = nullptr);

public slots:
   void show()
   {
       qDebug() << "===========show========";
       emit mysignalval("10");

   }

signals:
     void mysignalval(QString time);

};

#endif // TEST_H
      
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "test.h"
#include <QQmlEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    test ptest;
    engine.rootContext()->setContextProperty("ptest",&ptest);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}      
import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    function timevar(time)
    {
        console.log("==========time = " + time)
    }


//    Connections//可行
//    {
//        target:ptest
//        onMysignalval:{
//            console.log("-----time-----"+time)
//        }
//    }


    Component.onCompleted: {
         ptest.show()
         ptest.mysignalval.connect(timevar)//連接配接不到信号值
        console.log("----onCompleted------")

       // timevar()

    }
}