首页 文章

将信号QML连接到C(Qt5)

提问于
浏览
1

当我点击一个按钮时,我想改变矩形的颜色 . 它们都在main.qml文件中 . 我想向C后端发送一个信号来改变矩形的颜色 . 我似乎无法从文档中给出的代码中弄清楚

main.qml:import QtQuick 2.4导入QtQuick.Controls 1.3导入QtQuick.Window 2.2导入QtQuick.Dialogs 1.2

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


    id:root

    signal mysignal()


    Rectangle{
     anchors.left: parent.left
     anchors.top: parent.top
     height : 100
     width : 100
    }

    Button
    {

        id: mybutton
        anchors.right:parent.right
        anchors.top:parent.top
        height: 30
        width: 50
     onClicked:root.mysignal()

    }

}

main.cpp中:

#include <QApplication>
#include <QQmlApplicationEngine>
#include<QtDebug>
#include <QQuickView>

class MyClass : public QObject
{
    Q_OBJECT
public slots:
    void cppSlot() {
        qDebug() << "Called the C++ slot with message:";
    }
};

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  MyClass myClass;

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QPushButton *mybutton = engine.findChild("mybutton");

    engine.connect(mybutton, SIGNAL(mySignal()),
                   &myClass, SLOT(cppSlot()));

    return app.exec();
}

任何帮助,将不胜感激!

2 回答

  • 2

    QPushButton * mybutton = engine.findChild(“mybutton”);

    首先, QObject::findChild 通过 object name 找到QObjects,而不是id(无论如何都是上下文的本地) . 因此在QML中你需要这样的东西:

    objectName: "mybutton"
    

    其次,我认为你需要在引擎本身上执行 findChild ,而不是从 QQmlApplicationEngine::rootObjects() 返回它的根对象 .

    // assuming there IS a first child
    engine.rootObjects().at(0)->findChild<QObject*>("myButton");
    

    第三,QML中的 Button 由您只是将结果分配给 QPushButton * 的类型表示,但您需要坚持使用通用 QObject * .

  • 0

    我必须创建一个单独的类和头文件,然后将它连接到main.cpp中的信号

    main.cpp中

    #include <QApplication>
    #include <QQmlApplicationEngine>
    #include<QtDebug>
    #include <QQuickView>
    #include<QPushButton>
    #include<myclass.h>
    
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
    
    
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
        QObject *topLevel = engine.rootObjects().at(0);
    
        QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    
        MyClass myClass;
    
        QObject::connect(window,
                         SIGNAL(mysignal()),
                         &myClass,
                         SLOT(cppSlot())
                         );
    
    
        return app.exec();
    }
    

    myclass.h

    #ifndef MYCLASS
    #define MYCLASS
    
    
    
    #include <QObject>
    #include <QDebug>
    
    class MyClass : public QObject
    {
        Q_OBJECT
    
    public slots:
        void cppSlot();
    
    };
    #endif // MYCLASS
    

    myclass.cpp

    #include<myclass.h>
    
    void MyClass::cppSlot(){
    
        qDebug()<<"Trying";
    }
    

相关问题