2014-01-29 21 views
4

我剛開始學習Qt Quick 2.0的Qt Quick編程,我一整天都在谷歌上,它讓我瘋狂,所以在這裏。 我只有你的標準qt快速移動應用程序,qt爲你做的。這裏是所有的文件。如何連接一個Qt Quick按鈕點擊一個C++方法

(我是全新的,以本所以這可能是小白曲的,抱歉) 好了,所以這是我的名單,我不知道:

  1. 如何在地球上我連接這個類的方法點擊qml文件中的按鈕。
  2. 是否有可能連接相同的點擊和傳遞參數通過點擊從qml到方法,如果是的話,我會怎麼做呢?

  3. ,也是我在想,如果我可以在類鏈接到Qt Quick的例如像一個普通的QWidget類:(。)

    int main(int argc, char *argv[]) 
    { 
    QGuiApplication app(argc, argv); 
    SomeClass *sc = new SomeClass(); 
    
    QtQuick2ApplicationViewer viewer; 
    
    // this I guess would be more like the Widget method but this i really dont know 
    // about, just a question I'm throwing out there 
    viewer. (Link qt quick qml to object "sc"(Containing all my processes)) 
    
    viewer.setMainQmlFile(QStringLiteral("qml/Final2/main.qml")); 
    viewer.showExpanded(); 
    
    return app.exec(); 
    } 
    

主要CPP文件

#include <QtGui/QGuiApplication> 
#include "qtquick2applicationviewer.h" 

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

    QtQuick2ApplicationViewer viewer; 
    viewer.setMainQmlFile(QStringLiteral("qml/Final2/main.qml")); 
    viewer.showExpanded(); 

    return app.exec(); 
} 

這只是我的main.qml中的按鈕元素

Button { 
     id: btn 
     y: 443 
     height: 39 
     text: "Click Me" 
     anchors.bottom: parent.bottom 
     anchors.bottomMargin: 8 
     anchors.right: parent.right 
     anchors.rightMargin: 25 
     anchors.left: parent.left 
     anchors.leftMargin: 15 
    } 

這只是一些隨機類的頭:

#ifndef SOMECLASS_H 
#define SOMECLASS_H 

#include <QObject> 
#include <QDebug>> 

class SomeClass : public QObject 
{ 
    Q_OBJECT 
public: 
    explicit SomeClass(QObject *parent = 0); 

signals: 

public slots: 
    void buttonClicked(); 
    void buttonClicked(QString &in); 
}; 

#endif // SOMECLASS_H 

當然cpp文件:

#include "someclass.h" 

SomeClass::SomeClass(QObject *parent) : 
    QObject(parent) 
{ 
} 

void SomeClass::buttonClicked() 
{ 
    // do something 
} 

void SomeClass::buttonClicked(QString &in) 
{ 
    qDebug() << "Your string was : " << in; 
} 

我真的很感激所有幫助。 謝謝。

回答

1

首先,您需要將SomeClass的對象導出到QtQuick(是你的第三個問題?):

SomeClass sc; 
viewer.rootContext()->setContextProperty(QStringLiteral("_someObject"), &sc); 

這使得QtQuick可用的SC對象,命名爲 「_someObject」 下。

然後,在QML使用這樣的:

Button { 
    .... 
    onClicked: { 
     _someObject.buttonClicked(); //_someObject is the name used in setContextProperty. 
    } 
} 

這是假設按鈕按下的信號()這是發出對點擊/觸摸。不知道你使用哪個Button組件,我無法檢查。

要傳遞一個說法,只是做

onClicked: { 
    _someObject.buttonClicked("Something"); 
} 
+0

抱歉,但這並沒有在所有的工作。 – TheMan68

+0

我做到了viewer.rootContext(),但之後,我試圖把 - >做其他的過程,它不會給我任何選項,所以我不知道什麼即時做錯了 – TheMan68

+0

你是什麼意思與「沒有工作」?沒有編譯,或在運行時沒有工作? 「選項」是什麼意思? –