2017-01-23 19 views
0

最近,我遇到了一個小問題,它在QT中從cpp訪問qml中的複選框。所以問題很簡單:我有一個main.qml文件,它有一個複選框,我想根據我在啓動應用程序時保存在QSettings中的配置將「checked」屬性更新爲true或false。目前,我已經在應用程序啓動時成功地從cpp文件中加載QSettings的設置。那麼如何修改這個cpp文件中的「checked」屬性?如何從QT中的.cpp訪問QML中的一個複選框?

我試過這個:http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html並使用findChild函數,但它不起作用。

1),我把import <QtQuick>放在cpp文件中,但是我的錯誤是QtQuick file can't be found

2),我改爲「import <QtQuick/QQuickView>」。解決1),但有新的錯誤此行QObject* object = view.rootObject();

cannot initialize a variable of type 'QObject *' with an rvalue of type 'QQuickItem *` 

3),我改變QObject* object = view.rootObject();此行QQuickItem* object = view.rootObject();和使用後QObject* acbox = object->findChild<QObject* >("acbox");。 (acbox是該複選框的objectName)解決2)但得到新的錯誤:

Undefined symbols for architecture x86_64: 
    "QQuickView::setSource(QUrl const&)", referenced from: 
     ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o 
    "QQuickView::QQuickView(QWindow*)", referenced from: 
     ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o 
    "QQuickView::~QQuickView()", referenced from: 
     ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o 
    "QQuickView::rootObject() const", referenced from: 
     ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

任何人有任何建議嗎?提前致謝!

回答

0

可以使用的setProperty在CPP設置在QML屬性,然後綁定是在QML文件中的檢查狀態檢查下面的代碼

int main(int argc, char *argv[]) 
    { 
      QGuiApplication app(argc, argv); 
      QQmlApplicationEngine engine; QQmlComponent component(&engine, QUrl("qrc:/main.qml")); 
      QObject *object = component.create(); 
      object->setProperty("checkstatus", false); 
      return app.exec(); 
    } 




    in qml try this 


    Window { 
    visible: true 
    width: 640 
    height: 480 
    title: qsTr("Hello World") 

    property bool checkstatus 


    CheckBox { 
     id:checkbox 
     text: qsTr("checkbox1") 
     checked: checkstatus 
    } 


    } 
0

你是否在你的ref QT頁面中嘗試了這個例子?下面的例子將qml信號連接到C++類的插槽,但我認爲應該可以做相反的事情,即:將C++的變量信號連接到希望複選框更新的信號。然後它連接到執行復選框更新的QML插槽。

int main(int argc, char *argv[]) { 
    QGuiApplication app(argc, argv); 

    QQuickView view(QUrl::fromLocalFile("MyItem.qml")); 
    QObject *item = view.rootObject(); 

    MyClass myClass; 
    QObject::connect(item, SIGNAL(qmlSignal(QString)), 
        &myClass, SLOT(cppSlot(QString))); 

    view.show(); 
    return app.exec(); 
} 
相關問題