1

我有以下 qml 文件:

import QtQuick 2.2
import QtQuick.Dialogs 1.2

FileDialog 
{
 property string myTitle: "Select file to open"
 property string myfilter: "All files (*)"

 id: fileDialog
 objectName: "fileDialogObj"
 title: myTitle
 folder: shortcuts.home
 sidebarVisible : true
 nameFilters: [ myfilter ]
 onAccepted: 
 {
  close()
 }
 onRejected: 
 {
  close()
 }
 Component.onCompleted: visible = true
}

我想title从 C++ 代码中设置属性。我的代码如下所示:

QQmlEngine engine;
QQmlComponent component( &engine );
component.loadUrl( QUrl( QStringLiteral( "qrc:/qml/my_file_dialog.qml" ) ) );
QObject* object = component.create();
object->setProperty( "myTitle", "Open file!" );

标题具有Select file to open属性的初始值 ( )myTitle并且永远不会更改为Open file!

我究竟做错了什么?

更新 我还尝试直接从 C++ 代码更新标题。

考虑到我有对话框对象,我像这样更新磁贴:

QQmlProperty::write( dialog, "title", "testing title" );

也像这样:

dialog->setProperty( "title", "testing title" );

未设置文件对话框的属性标题。

正如@Tarod 在他的回答中提到的,这似乎是一个错误。

还是我错过了什么?

4

1 回答 1

0

这似乎是一个错误,因为如果我们设置下一个代码有效

title = "xxx"

代替

title = myTitle

此外,您可以检查其他属性是否已正确更新。IEsidebarVisible

主文件

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include <QQmlProperty>
#include <QDebug>    

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlEngine engine;
    QQmlComponent component(&engine, QUrl(QLatin1String("qrc:/main.qml")));
    QObject *object = component.create();

    QObject *fileDialog = object->findChild<QObject*>("fileDialogObj");

    if (fileDialog)
    {
        fileDialog->setProperty("myTitle", "new title");
        fileDialog->setProperty("sidebarVisible", true);
        qDebug() << "Property value:" << QQmlProperty::read(fileDialog, "myTitle").toString();
    } else
    {
        qDebug() << "not here";
    }

    return app.exec();
}

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQml 2.2
import QtQuick.Dialogs 1.2

Item {
    FileDialog
    {
        property string myTitle: fileDialog.title
        property string myfilter: "All files (*)"

        id: fileDialog
        objectName: "fileDialogObj"
        title: "Select file to open"
        folder: shortcuts.home
        sidebarVisible : true
        nameFilters: [ myfilter ]

        onAccepted:
        {
            close()
        }
        onRejected:
        {
            close()
        }
        Component.onCompleted:
        {
            visible = true
        }
        onMyTitleChanged:
        {
            console.log("The next title will be: " + myTitle)
            title = myTitle
        }
    }
}
于 2017-05-10T07:44:11.617 回答