如何将qml子组件信号连接到c++插槽
How to connect a qml child component signal to a c++ slot
我想将子项目组件信号连接到c++插槽,但它不工作。我有一个文件 ButtonItem。qml中的代码类似于
Item {
id: button
property string label
property alias cellColor : rectangle.color
Rectangle {
id : rectangle
objectName : "rectangle"
height : 40
width : 50
radius: 10
color: "gray"
Text {
anchors.centerIn: parent
font.pixelSize: 20
text: button.label
color: "white"
}
}
}
,主文件为 button.qml
Rectangle {
id : rect
width: systemWidth
height: systemHeight.getHeight()
Text{
id : text
objectName : "text"
height : 20
width : 10
anchors.centerIn : parent
text : systemHeight.getText()
}
ButtonItem {
signal qmlMsg(string msg)
objectName : "button"
id : button3
cellColor : "blue"
label : "3"
MouseArea {
anchors.fill : parent
onClicked : button3.qmlMsg("Hello World")
}
}
}
和在我的主源文件中的代码是
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QDeclarativeView *qmlView = new QDeclarativeView;
qmlView->rootContext()->setContextProperty("systemWidth", 1000);
Sample sObj;
qmlView->rootContext()->setContextProperty("systemHeight", &sObj);
this->setCentralWidget(qmlView);
qmlView->setSource(QUrl::fromLocalFile("E:/samplecode/qmlsample/button.qml"));
QObject *obj = qmlView->rootObject();
QObject *childObj = obj->findChild<QObject *>("button");
connect(childObj, SIGNAL(qmlMsg(QString)), this, SLOT(printData(QString)));
}
void MainWindow::printData(QString message)
{
qDebug()<<message;
}
但是没有插槽正在接收呼叫。如果我将父信号连接到c++插槽,则工作正常。
问题不在于孩子的信号/槽,它的MouseArea的大小为零。在ButtonItem.qml中为根条目添加宽度和高度。
Item {
id: button
width: 40 // add this
height: 40 // add this
...
}
或者直接添加到按钮。也qml
ButtonItem {
signal qmlMsg(string msg)
objectName : "button"
id : button3
cellColor : "blue"
label : "3"
width: 40 // add this
height: 40 // add this
...
}
要使用QObject::findChild()
查找QML子项目,它应该有一个名称。所以应该是这样的:
Item {
id: button
objectName: "button"
...
}
现在你可以访问它:
QObject *obj = qmlView->rootObject();
QObject *childObj = obj->findChild<QObject *>("button");
if (childObj)
{
connect(childObj, SIGNAL(qmlMsg(QString)), this, SLOT(printData(QString)));
}
相关文章:
- 当套接字连接断开时检测C/C++Unix
- 无法在windows上使用mingw将sqlite3与c连接
- 到连接组件算法的问题(递归)
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- 无法在C++中建立与MySQL数据库的连接
- PC中的程序和PHONE中的本机描述应用程序之间的数据连接
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 连接 dockerized 模型和 dockerized 数据库时出现"无法 SQLConnect"错误
- 使用 bfs 解决连接组件问题时得到错误的答案
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 如何修复valgrind启动时的致命错误(与libc6-dbg和libc6-dbg:i386连接)
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- OSX蓝牙打开RFCOMMChannelAsync声称已连接,但未建立连接,并且从未调用过委托
- 在 libcurl 连接池中预创建连接
- 套接字连接"Operation not permitted"错误,甚至使用升压/平发器根.cpp
- libcurl 和 DNS ttl 中的内部连接管理
- 如何应用 libcurl 的持久连接选项
- 提升 ASIO - io_service 不要等待连接到线程
- WinSock2:connect() 提供"连接被拒绝"
- 升压信号2将插槽传递到成员功能以断开连接