C ++和QML:将QML信号连接到C ++插槽

时间:2017-05-08 20:56:23

标签: c++ qt qml

我无法通过以下代码获取信号连接。我特别希望通过将信号连接到cpp插槽而不设置上下文来实现此目的。我想问题是那个

 item->findChild<QObject*>("signalItem");

找不到合适的物品? 这里是相关的代码文件:

main.cpp中:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "include/myclass.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    QObject * item = engine.rootObjects().value(0);
    QObject * myObject= item->findChild<QObject*>("signalItem");
    MyClass myClass;
    QObject::connect(item, SIGNAL(testSignal()),&myClass,SLOT(cppSlot()));

    return app.exec();
}

main.qml:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    visible: true
    width: 800
    height: 460

    Page1 {
        id: page1
        visible: true
    }
}

Page1.qml:

import QtQuick 2.7
import QtQuick.Window 2.2

Item {
    width: 800
    height: 460
    id: signalItem
    objectName: "signalItem"
    signal testSignal()

    CustomButton {
        id: cppSignalButton
        x: 14
        y: 55
        buttonText: "Test CPP Signal"
        onButtonClicked: {
            signalItem.testSignal();
        }
     }
}

1 个答案:

答案 0 :(得分:2)

因为您要连接<MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="true" /> <Condition Binding="{Binding TabStripPlacement, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type TabControl}}}" Value="Top" /> </MultiDataTrigger.Conditions> <Setter Property="Panel.ZIndex" Value="1" /> <!-- commented line below, because we don't need Select Scale behaviour in metro style anymore --> <!--<Setter Property="Margin" Value="-2,-2,-2,0" />--> <Setter TargetName="innerBorder" Property="Opacity" Value="1" /> <Setter TargetName="innerBorder" Property="BorderThickness" Value="0,0,0,2" /> <Setter TargetName="innerBorder" Property="BorderBrush" Value="#0088cc" /> <Setter TargetName="contentPresenter" Property="TextBlock.Foreground" Value="#0088cc" /> <Setter TargetName="mainBorder" Property="BorderThickness" Value="0" /> </MultiDataTrigger> (main.qml)而不是item

如果您这样做,它将起作用:

myObject

实际上,如果该函数的返回值不为null,您还应该添加检查:

QObject::connect(myObject, SIGNAL(testSignal()),&myClass,SLOT(cppSlot()));