我正在尝试使用 QtQuick 与 C ++ 文件中的 qml 对象进行互动。但是现在不幸的是没有成功。知道我做错了吗?我试过两种方法怎么做,第一种结果是 findChild()返回 nullptr ,在第二次尝试我得到 Qml comnponent还没有准备好错误。这样做的正确方法是什么?
主:
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
// 1-st attempt how to do it - Nothing Found
QObject *object = engine.rootObjects()[0];
QObject *mrect = object->findChild<QObject*>("mrect");
if (mrect)
qDebug("found");
else
qDebug("Nothing found");
//2-nd attempt - QQmlComponent: Component is not ready
QQmlComponent component(&engine, "Page1Form.ui.qml");
QObject *object2 = component.create();
qDebug() << "Property value:" << QQmlProperty::read(object, "mwidth").toInt();
return app.exec();
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
width: 640
height: 480
Page1 {
}
Page {
}
}
}
Page1.qml:
import QtQuick 2.7
Page1Form {
...
}
Page1.Form.ui.qml
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
Item {
property alias mrect: mrect
property alias mwidth: mrect.width
Rectangle
{
id: mrect
x: 10
y: 20
height: 10
width: 10
}
}
答案 0 :(得分:3)
import { Component, ViewChild } from '@angular/core';
import { NavController, Slides, IonicPage } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-slide-custom-pagination',
templateUrl: 'slide-custom-pagination.html'
})
export class SlideCustomPaginationPage {
@ViewChild('sliderOne') sliderOne: Slides;
@ViewChild('sliderTwo') sliderTwo: Slides;
@ViewChild('sliderThree') sliderThree: Slides;
slides = [
{
title: 'Dream\'s Adventure',
imageUrl: 'assets/img/lists/wishlist-1.jpg',
songs: 2,
private: false
},
{
title: 'For the Weekend',
imageUrl: 'assets/img/lists/wishlist-2.jpg',
songs: 4,
private: false
},
{
title: 'Family Time',
imageUrl: 'assets/img/lists/wishlist-3.jpg',
songs: 5,
private: true
},
{
title: 'My Trip',
imageUrl: 'assets/img/lists/wishlist-4.jpg',
songs: 12,
private: true
}
];
constructor(public navCtrl: NavController) { }
ngAfterViewInit() {
this.sliderOne.paginationBulletRender = (index, className) => {
return `<span class="custom-pagination ${className}>${index + 1}</\span>`;
};
this.sliderTwo.paginationBulletRender = (index, className) => {
return `<span class="custom-pagination-2 ${className}>${index + 1}</\span>`;
};
this.sliderThree.paginationBulletRender = (index, className) => {
return `<span class="custom-pagination-3 bullet-icon-${index + 1} ${className}></\span>`;
};
}
}
将对象名称作为第一个参数。但不是ID。
http://doc.qt.io/qt-5/qobject.html#findChild
在您的代码中,您尝试使用标识findChild
进行查询。所以它可能不起作用。
在QML中添加mrect
,然后尝试使用对象名称访问objectName
。
下面的内容(我没有尝试过。因此编译时错误的可能性):
在QML中添加objectName
findChild
然后你的findChild如下所示
Rectangle
{
id: mrect
objectName: "mRectangle"
x: 10
y: 20
height: 10
width: 10
}