QML filedialog设置标题来自C 代码

QML FileDialog set title from C++ code

本文关键字:代码 标题 filedialog 设置 QML      更新时间:2023-10-16

我有以下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
}

我想从C 代码设置title属性。我的代码看起来像:

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

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

我在做什么错?

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

考虑到我有对话框对象,我会这样更新瓷砖:

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

也这样:

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

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

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

还是我错过了什么?

这似乎是一个错误,因为如果我们设置

,下一个代码有效

title = "xxx"

而不是

title = myTitle

另外,您可以检查其他属性已正确更新。IE。sidebarVisible

main.cpp

#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
        }
    }
}