我想用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类型。
但什么都没发生。谢谢。
答案 0 :(得分:3)
Claudia,你的主要问题是QML信号类型与插槽类型不兼容。我已使用signal qmlSignal(string msg)
和main.cpp
:
QObject *rect = dynamic_cast<QObject*>(view->rootObject());
SignalslotlistView myClass;
QObject::connect(rect, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
现在我可以在C ++端接收QML信号。