c – 将信号从QML连接到Qt 5.1

前端之家收集整理的这篇文章主要介绍了c – 将信号从QML连接到Qt 5.1前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想用qt 5.1将qml信号连接到qt插槽.我不能在这个版本的qt中使用DeclarativeView.
我的qml元素是一个简单的矩形,onClicked事件启动信号.
Rectangle{
    id:test
    width:  200
    height: 50
    x: 10
    y: 10
    signal qmlSignal()
    MouseArea {
        hoverEnabled: false
        anchors.fill: parent
        onClicked: {

            console.log("geklickt")
            test.qmlSignal()


        }
}

我有一个带有此标头的SignalslotlistView类:

class SignalslotlistView: public QObject{
Q_OBJECT
public slots:
void cppSlot(const QString &msg);

};

和.cpp

void SignalslotlistView::cppSlot(const QString &msg) {

qDebug() << "Called the C++ slot with message:" << msg;}

在MainWindow类中,我尝试设置连接:

view->setSource(QUrl::fromLocalFile("main.qml"));
QObject *object = (QObject *)view->rootObject();
QObject *rect = object->findChild<QObject*>("test");

SignalslotlistView myClass;
    QObject::connect(rect,SIGNAL(qmlSignal()),&myClass,SLOT(cppSlot()));

视图来自QQuickView类型.

但什么都没发生.谢谢.

解决方法

Claudia,你的主要问题是QML信号类型与插槽类型不兼容.我使用信号qmlSignal(string msg)和main.cpp修复了它:
QObject *rect = dynamic_cast<QObject*>(view->rootObject());
SignalslotlistView myClass;
QObject::connect(rect,SIGNAL(qmlSignal(QString)),SLOT(cppSlot(QString)));

现在我可以在C端接收QML信号.

猜你在找的C&C++相关文章