2017-05-05 96 views
1

我有以下QML文件:QML的FileDialog設置標題從C++代碼

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!

我在做什麼錯?

UPDATE 我也試着直接從C++代碼更新標題。

考慮到我有對話框對象,我更新了瓷磚這樣的:

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

而且也是這樣:

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

文件對話框的產權未設置。

正如@Tarod在他的回答中提到的,這似乎是一個錯誤。

或者我錯過了什麼?

回答

0

這似乎是一個錯誤,因爲下一個代碼工作,如果我們設置

title = "xxx"

,而不是

title = myTitle

此外,您還可以查看其他屬性正確更新。即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 
     } 
    } 
} 
+0

我會等待一段時間才能弄清楚,如果這是一個錯誤,然後,如果沒有其他信息將反饋給,我會接受你的回答:這是一個錯誤。 – mtb