如何将Qt Quick按钮单击连接到c ++方法

The*_*n68 5 binding qt qml

我刚刚开始学习Qt Quick 2.0的Qt Mobile编程,我整天都在google上,它让我疯狂,所以这里就是这样.我有你的标准qt快速移动应用程序.这是所有文件.

(我对此很陌生,所以这些可能是noob qu's,抱歉)好的,所以这里是我不知道的列表:

  1. 我如何将此类方法连接到qml文件中的按钮单击.
  2. 是否有可能连接相同的点击并通过点击从qml到方法传递参数,如果是这样,我该怎么做?

  3. 而且我想知道我是否可以像普通的QWidget类一样快速将类链接到qt:例如:

    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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

主(.)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();
}
Run Code Online (Sandbox Code Playgroud)

这只是我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
    }
Run Code Online (Sandbox Code Playgroud)

这只是一些随机类头:

#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
Run Code Online (Sandbox Code Playgroud)

当然是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;
}
Run Code Online (Sandbox Code Playgroud)

我非常感谢所有的帮助.谢谢.

Fra*_*eld 2

首先,您需要将 SomeClass 对象导出到 QtQuick (这是您的第三个问题吗?):

SomeClass sc;
viewer.rootContext()->setContextProperty(QStringLiteral("_someObject"), &sc);
Run Code Online (Sandbox Code Playgroud)

这使得 sc 对象在 QtQuick 中可用,名称为“_someObject”。

然后,在 QML 中像这样使用它:

Button {
    ....
    onClicked: {
        _someObject.buttonClicked(); //_someObject is the name used in setContextProperty.
    }
}
Run Code Online (Sandbox Code Playgroud)

这假设 Button 有一个在单击/触摸时发出的 clicked() 信号。不知道您使用哪个按钮组件,我无法检查。

要传递参数,只需执行以下操作

onClicked: {
    _someObject.buttonClicked("Something");
}
Run Code Online (Sandbox Code Playgroud)