C++ 信号到 Qt 中的 QML 插槽

标签 c++ qt qml signals-slots

我想从 C++ 向我的 QML 文件中的插槽发送信号。 我已经让它在没有原始类型参数的情况下工作,但如果我想将 QString 发送到我的 QML Slot,我会在连接时遇到错误。

我在 main.cpp 中连接

QObject *contentView = rootObject->findChild<QObject*>(QString("contentView"));
QObject::connect(&myObj,      SIGNAL(finishedGatheringDataForItem(QString)), 
                 contentView, SLOT(updateViewWithItem(QString)));

我的 qml 文件的相关部分

Rectangle {
        objectName: "contentView"
        function updateViewWithItem(string) { console.log('got some Items'); }  // slot
}

错误:

Object::connect: No such slot QDeclarativeRectangle_QML_2::updateViewWithItem(QString)

最佳答案

您应该使用 Connections在这种情况下(也许这是唯一的连接方式)。

  1. 通过 setContextProperty

    将您的对象 myObj 放入 QML 文件
    qmlVectorForm->rootContext()->setContextProperty("YourObject", myOb);
    
  2. 你的信号是

    finishedGatheringDataForItem(QString signalString)
    
  3. 在 QML 文件中,添加如下 Connectios:

    Connections {
        target: YourObject 
        onFinishedGatheringDataForItem: {
            qmlString = signalString
        }
    }
    

关于C++ 信号到 Qt 中的 QML 插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8834147/

相关文章:

c++ - 回调函数参数的 C++11 std::bind 和 auto 编译错误

c++ - 在 C++ 中处理任意长度的整数

javascript - 如何从 qml 将 javascript 对象发送到 C++?

c++ - 对常量对象 C++ 感到困惑

c++ - 在 C++ 中,当字符串文字传递给接受 const std::string & 的函数时会发生什么?

python - Qt 调试器在 mac 上使用错误的 python 版本

qt - 如何保存和恢复 ListModel 的内容?

c++ - 将 System::Datetime 转换为 QDateTime

listview - QML ListView 和 ListModel 索引

Qt (QML) 虚线圆