【问题标题】:QT - Connect Qml button Click to Cpp ConstructorQT - 连接 Qml 按钮单击到 Cpp 构造函数
【发布时间】:2017-08-25 15:23:39
【问题描述】:

这是我的代码(无法编译,在 main.cpp 中标记连接时说:“在‘,’标记之前预期主表达式”)

ma​​in.cpp

QObject *myButton = engine.rootObjects().first() -> findChild<QObject*>("btn");
QObject::connect(myButton, SIGNAL(clicked()), MyClass, SLOT(MyClass()));

ma​​in.qml

ApplicationWindow {
    id: appWindow
    visible: true
    width: 850; height: 500
Button
{
objectName: btn
anchors.centerIn: parent
}
}

我希望每次单击按钮时都实例化 cpp 类 MyClass

我之前做了一件不同的事情,但是它在应用程序运行时实例化 MyClass 的问题,而不是在单击按钮时实例化的问题。此外,我不能调用构造函数,只能调用 Q_INVOKABLE 公共方法。

ma​​in.cpp

MyClass myClass;
engine.rootContext() -> setContextProperty("_btn", &myClass);

ma​​in.qml

ApplicationWindow {
    id: appWindow
    visible: true
    width: 850; height: 500
Button
{
objectName: btn
anchors.centerIn: parent
onClicked: _btn.myMethod() //where myMethod is a Q_INVOKABLE public method belonging to MyClass.
}
}

【问题讨论】:

    标签: c++ qt qml signals-slots


    【解决方案1】:

    请看QObject::connect的定义

    QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
    

    参数 1 和 3 是基于 QObject 的类的实例(不是您在 sn-p 中所述的定义),因此您需要一个类的实例来使用信号槽机制。这就是你编译失败的原因。

    要完成您的任务,您必须创建一些“代理”类并连接到插槽,您将在其中动态创建 MyClass

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多