How to connect Qt shortcut button to C ++ method

I was just starting to learn Qt Mobile programming using Qt Quick 2.0, and I was on google all day and drove me crazy, like that. I only have your standard qt fast mobile application that qt does for you. Here are all the files.

(I'm new to this, so it could be noob qu, sorry) So here is my “Don't know” list:

  • How can I connect this class method to a button click in the qml file.
  • Is it possible to link the same click and pass parameters through a click from qml to the method, and if so, how would I do it?

  • and also I was wondering if I can associate a class with qt quickly, like a regular QWidget class, for example:

    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();
    }
    

The main (.) Cpp file

#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();
}

This is just the button element from my 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
    }

This is just some random class title:

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

. .

+4
1

-, SomeClass QtQuick ( ?):

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

sc QtQuick "_someObject".

QML :

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

, (), /. , Button , .

,

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

Source: https://habr.com/ru/post/1524330/


All Articles