Object to QML C++ signal/slot mechanism transfer

Hello!

I have a simple class:

// myclass.hh

class MyClass : public QObject {

    Q_OBJECT

    Q_PROPERTY(QString title READ title)

public:
    MyClass(QObject* parent = nullptr)
        : QObject(parent)
    {}

    ~MyClass() {}

    MyClass(const MyClass&, QObject* parent = nullptr)
        : QObject(parent)
    {}

    QString title() const
    {
        return title_;
    }

private:
    QString title_;
};

Q_DECLARE_METATYPE(MyClass);

and in the main function, I save my metatype system class

// main.cc

...
qRegisterMetaType("MyClass");

MainClass mainclass;qml->setContextProperty("mainclass", mainclass);
...

and in another place, I try to convey the purpose of the MyClass class via the signal:

// mainclass.hhclass MainClass : public QObject {    Q_OBJECT
...
signals:
    void my_signal(MyClass);
...
};
// mainclass.cc
...
    MyClass mc;
    emit my_signal(mc);
...

and try to catch this object in qml slot:

// .qml

Container {
    onCreationCompleted: {
        mainclass.my_signal.connect(signalHandler)
    }

    function signalHandler(myClassObj) {
        console.log('we here') // output 'we here'
        console.log(myClassObj.title) // output 'undefined'
        console.log(myClassObj.title()) // empty output
    }
}

Macro Q_INVOCABLE added before the declaration of MyClass::title() has the same effect.

What is wrong with my code?

This is the signal for all

Q_SIGNALS:

    void addedToAllOrder(Order* order);

Order is registered:

qmlRegisterType("org.ekkescorner.data", 1, 0, "Order");

Import in qml:

import org.ekkescorner.data 1.0

Qml connection:

onCreationCompleted: {
        dataManager.addedToAllOrder.connect(onAddedToAllOrder)
    }

Important! set a property in qml:

Page {
    id: orderPage
    .....
    property Order anotherOrder

then everything works well in qml function (SLOT)

    function onAddedToAllOrder(theOrder) {
        anotherOrder = theOrder
        console.debug("Order added: " + anotherOrder.nr)
    }

This is how I have face this kind of stuff

using a pointer ensures that there'e really a single object used in memory and you can use QML.

the cool thing: he is glad assist in qml: type anotherOrder. ... gives all properties to select and you deal directly with your C++ object. don't forget that your C++ class is the owner (parent) of your object

hope that gives you some ideas to try

Tags: BlackBerry Developers

Similar Questions

  • Signal - Slot issue

    I have a VirtualKeyboardService that is configured in this way:

    constchar *uri = "bb.cascades.bps";
    qmlRegisterType(uri, 1, 0, "BPSMonitor");
    qmlRegisterType(uri, 1, 0, "VirtualKeyboardService");
    
    QML :
     attachedObjects: [
                BPSMonitor {
                    id: bpsMonitor
    
                    //Receive events when the keyboard becomes visible or hides
                    virtualKeyboardService: VirtualKeyboardService {
                        id: virtualKeyboardService
                        // Swipe from the bottom-left bezel towards the center of the
                        // screen to force the keyboard to be visible
                    }
                }
    ]
    

    I don't know how to put in place in order to provide this service to the main application class.   I think I need a signal / slot, but don't understand how to set up.   You will need to send a REAL simple when a certain touch.

    VirtualKeyboardService has these signals:

  • Problems with GPS signal/slot

    Hello

    I try to get GPS information for my application. I did a class to do so.

    #ifndef GPSHANDLER_H_
    #define GPSHANDLER_H_
    
    #include 
    
    #include 
    
    #include 
    #include 
    #include 
    
    using namespace QtMobilitySubset;
    
    class GPShandler : public QObject{
        Q_OBJECT
    public:
        GPShandler(QObject* parent);
        virtual ~GPShandler();
    private Q_SLOTS:
        void positionUpdatedSlot(const QGeoPositionInfo &geoInfo);
    
    public:
        void start();
    
        void stop();
    
        double Latitude();
    
        double Longitude();
    
    private:
        double mGeoInfoLat;
        double mGeoInfoLong;
        QGeoPositionInfoSource *mGeo;
    };
    #endif /* GPSHANDLER_H_ */
    
    #include "GPShandler.h"
    
    GPShandler::GPShandler(QObject* parent)
    : QObject(parent) {
        mGeoInfoLat = 0;
        mGeoInfoLong = 0;
        mGeo = QGeoPositionInfoSource::createDefaultSource(this);
        if (mGeo) {
            bool checkval = connect(mGeo, SIGNAL(positionUpdated(const QGeoPositionInfo &)), this,
                    SLOT(positionUpdatedSlot(const QGeoPositionInfo &)));
    
            mGeo->setPreferredPositioningMethods(QGeoPositionInfoSource::SatellitePositioningMethods);
            mGeo->setUpdateInterval(1000);
    
            //checkval = mGeo->setProperty("backgroundMode", true);
            //int i = 3;
        }
    }
    
    GPShandler::~GPShandler() {
        // TODO Auto-generated destructor stub
    }
    
    void GPShandler::positionUpdatedSlot(const QGeoPositionInfo &geoInfo) {
        // Here's where you can do something with the device's position
        mGeoInfoLat = geoInfo.coordinate().latitude();
        mGeoInfoLong = geoInfo.coordinate().longitude();
    }
    
    void GPShandler::start()
    {
        mGeo->startUpdates();
    }
    
    void GPShandler::stop()
    {
        mGeo->stopUpdates();
    }
    
    double GPShandler::Latitude()
    {
        return mGeoInfoLat;
    }
    
    double GPShandler::Longitude()
    {
        return mGeoInfoLong;
    }
    

    As you can see I have connected the signal postionUpdate() of QGeo class that I use for the positionUpdatedSlot() of the slot. I use the class as follows:

    Pop = new GPShandler (this);

    void::startTimer() {} App

    Pop-> start();

    }
    void::stopTimer() {} App

    Pop-> stop();

    }

    which are called when a key is pressed. However, the positionUpdatedSlot() of slot function is never called. I have debugged in my code and cannot find the problem. I can confirm the work of connection (function returns true), and that presented startup and shutdown functions are called as expected. Is there a reason why my slot machine function is not called?

    Note: I have another implementation of signal/slot in this app:

    Connect (mTimer, SIGNAL (timeout ()), this, SLOT (update ()));

    and it works very well.

    Thank you

    Gerry

    I do not know which of the following has solved my problem, but in any case, it's working now after doing these things:

    1. give permission to app to device identification information. (I had already given GPS, but examples also being device identifying information I thought I'd try that)

    2. remove the line:

           mGeo>setPreferredPositioningMethods(QGeoPositionInfoSource::SatellitePositioningMethods);
    

    as an example, I created using this example: http://blackberry.github.com/Cascades-Samples/geo-locationdiagnostics.html did not have this line

  • Expose the QGeoAddress with Q_PROPERTY object to QML

    Hello

    I have a class that I wrote which gets the location of the device and does a reverse search for Geolocation. In my C++, I have an QGeoAddress object, but when I try and access its attributes of QML, I get a "property: unknown type: address QGeoAddress ' error."

    I'm loading my class, called LocationInformation in QML by using attachedObects:

    attachedObjects: [
            LocationInformation {
                id: locationInformation
            }
        ]
    

    In my head of class LocationInformation, I set the latitude and longitude as attributes such as address:

    class LocationInformation : public QObject
    {
        Q_OBJECT
    
        Q_PROPERTY(double latitude READ latitude)
        Q_PROPERTY(double longitude READ longitude)
        Q_PROPERTY(QGeoAddress address READ getAddress)
    
        ...
    }
    

    I am able to call locationInformation.latitude and get a value, but this isn't the case for the address. I have to perform an extra step in order to obtain an QGeoAddress object to be recognized by QML?

    Thank you

    javabb

    QGeoAddress inherit from QObject, my code snippet above will not work (and is what this error means ).  To expose to QML, you would have to wrap up in your own C++ class that extends from QObject.  Or just use c++ instead of QML.

  • Problem with signals slots ToggleButton

    Trying to connect a signal to a slot:

    connect(myToggleButton, SIGNAL(checkChanged(bool)), myDataClass, SLOT(setMyValueOn(bool)));
    

    In myDataClass.hpp:

    public slots:
      void setMyValueOn(bool valueOn);
    

    In the cpp file:

    void MyDataClass::setMyValueOn(bool valueOn)
    {
      // never called
    }
    

    I have the MyDataClass is a subclass of QObject and Q_OBJECT at the appropriate place in the file of the hpp.

    I think that I incorrectly use the toggle switch.

    The signal is called checkedChanged (bool).

    BTW, I suggest using Qt Creator, if you develop mostly in C++. It has the very practical signals AutoComplete functionality.

  • Problem with the C++ object to qml exponent

    Hello, I followed the instructions by Qml and C++ integration but got stuck at a certain time.

    Here is my code:

    // applicationui.cppPage* ApplicationUI::doLoadPageDetails(){
    
        qmlRegisterType("myHtmlPage", 1, 0, "HtmlPage");
    
        QmlDocument *qml = QmlDocument::create("asset:///PageDetails/PageDetails.qml").parent(this);
        qml->setContextProperty("app", this);
    
        HtmlPage *htmlPage = new HtmlPage();
        qml->setContextProperty("htmlPage", htmlPage);
    
        htmlPage->setHtml("*some html code*");
    

    This function creates a Page with a container that contains a WebView. Here, I want to fill the string saved as htmlPage.html.

    I created the RPC classes as described in the link and they work. When I check the htmlPage-> html() in C++, I get the string I wanted.

    Now, my problem is how to get this string for qml.

    Here's what I do:

    import myHtmlPage 1.0....Container {
    ....
            ScrollView {            visible: true
                WebView {
                    attachedObjects: [
                       HtmlPage {
                            id: htmlPage
                        }
                    ]
    
                    id: webViewScrollable1....
                    html: "" +
                    "" +
                   "*style options*" +
                    "" +
    
                    htmlPage.html +  //<----- this should give me the string I saved in C++ under htmlPage->html()
    
                    "" +
                    ""
                }
            }
    

    But nothing is displayed on the page. But why? I forgot to link something?

    I think you're getting confused in the difference between a property and recording a QML component.

    You do both.

    When you attach an object to a QML file, you create an instantiation of the object at this time, when you set a context property that you you already created that object and are just passing a reference to this.

    So when you join HtmlPage in your QML file you create a new object and does not reference that you have created in your program C++ part, so no text.

  • Error in the creation of custom signal slot

    My header class code

    signals:
        void newinfo(int a);
        void testing();private slots:        void process_new_info(unsigned char[]);
    

    My class of CPP.

    connect(this, SIGNAL(newinfo(int)), this,SLOT(process_new_info(unsigned char[])));
    
    void APP::newinfo(int a){
    
    }
    

    When I built the code, I get the error message saying firstly define here (near the function definition)

    Thank you

    Dembélé George Jacob

    You're doing it wrong
    You can not send INT (Sub newinfo(int a)) and receive unsigned char [] (Sub process_new_info (unsigned char []))

    The rest is good
    private, signals, locations etc...

     

    Please read the signals and the QT Slots

    https://developer.BlackBerry.com/native/documentation/Cascades/dev/signals_slots/

  • loading of objects to qml

    Hello

    I'm doing the following.

    I created a home page that displays a list. Now when I click on one of the items in this list another page opens. What I want to do now is to fill the page loaded information. So far, it is just a page with ListViews and WebViews containers.

    Here is a code:

    NavigationPane {
        id: navigationPane
    [...]
        Page {
    [...]
            content: Container {
    
                ListView {
                    id: listview
    [...]
                    onTriggered: {
                        var selectedItem = dataModel.data(indexPath);
                        var GoToSecondPage = secondPageDefinition.createObject();   // here I create the second page with its containers, ListView, etc.
                        Qt.app.fillPageWithContent();     // here I want to add content to the lists
                        navigationPane.push(GoToSecondPage);
                    }
    
                    objectName: "listview"
                    // end of listItemComponents list
                }
    
            } // end of Container
    [...]
        }
    
        attachedObjects: [
            // Definition of the second Page, used to dynamically create the Page above.
            ComponentDefinition {
                id: secondPageDefinition
                source: "asset:///PageDetails/PageDetails.qml"
            }
        ]
    }
    

    Can anyone give me a tip how do I do this?

    I also recommend that you only download a couple of the ListView sample applications that do exactly what you're trying to do.

    Looking at their willingness to code better help understand you what is needed.

    Samples can be found here...

    http://developer.BlackBerry.com/native/sampleapps/

    I recommend the quote and stamp collector.

  • Create an object with a custom code

    Hello

    OK, I'm not sure I'm clear in my title, but I'll try to explain my problem.

    Recently, I request the creation of unlimited QML object. In my example, I want to create a header and an indicator of progress with property ask the user. After that, a timer add '+ 1' for the first indicator of progress, and when its finish, the timer add "+ 1" to the second, etc... ".

    To do this, I want to create an ID for each indicator of progress (PI_1, PI-2, PI_3, etc...).

    How can I do? Can I use the name of the object for that?

    Thanks for your response

    Did you look at my dynamic control KB article?

    It shows you how to set up a connection using signals and slots, that when you work with several items that need work asynchronously is the way to go...

    http://supportforums.BlackBerry.com/T5/native-development-knowledge/how-to-pass-data-to-and-from-a-Q...

    Doing it this way means that the underlying signal/slot mechanism manages the problem "that pits" and you will not need a massive switch statement.
    It has another advantage, as in if you want to stop all the food at once, you can attach a signal to several 'Cancel' slot machines.

  • finished() signal for invoke() on phone app)

    I use bb::system:InvokeManager to start a call using action 'bb.action.DIAL '.

    response of bb::system:InvokeTargetReply * const = invokeMgr.invoke (invokeRequest);

    Invoke() will return an InvokeTargetReply. This response will signal finished(). I use

    Boolean result = QObject::connect (response, SIGNAL (finished (()), this, SLOT (onInvokeResult ()));

    to connect the signal with the slot. However, my CRACK onInvokeResult() is never called. Why is this?

    (1) something wrong with my application?

    (2) signal/slot mechanism only works inside your own application. If this approach can be used when calling invoke() to an external application. Signal/slot isn't an IPC mechanism.

    Documentation says errorType and errorCode is valid after the finished() signal.

    BB::System:InvokeTargetReply * response = qobject_cast(sender());
    BB::System:InvokeReplyError:type errorType = response-> error();
    int errorCode = response-> errorCode();

    If the signal/slot mechanism cannot be used internally within your own application, how can you know if the invoke() on an external application would be successful?

    I wasn't looking to extract the right aways errorType and errorCode after calling invoke()... maybe that can already tell me the result?

    BR, René

    Thanks for sharing this code. My code is almost the same. And I solved the problem. My code now looks like this:

    BB::System:InvokeManager invokeMgr;
    response of BB::System:InvokeTargetReply * = invokeMgr.invoke (invokeRequest);
    If (answer)
    {
    Set the parent for this 'response' otherwise 'response' will be deleted at the end of this function.
    response-> setParent (this);
    Boolean result = QObject::connect (response, SIGNAL (finished (()), this, SLOT (onInvokeResult ()));
    ...

    void controller:nInvokeResult()
    {
    Get the response from the sender object
    BB::System:InvokeTargetReply * response = qobject_cast(sender());
    BB::System:InvokeReplyError:type errorType = response-> error();
    int errorCode = response-> errorCode();

    response-> deleteLater();
    }

    It turns out that it is absolutely essential to add a parent to the response using the line "answer-> setParent (this);" in order to receive the signal finished(). If this line is commented out, then the slot is more will be called.

    You may not use a local variable for the answer, but a member of the class. That also seems to work.

    Thanks for the help!

    BR, René

  • Method is never triggered.

    I do some indepth BB10 development tutorials as I learn myself. Especially for beginners and for those coming to BB Android/Java Dev.

    In any case, I'm my current tutorial I want to talk about networking and FIO. So far I have not all errors in compiling or running the application however watch console I do not get an expected debug output.

    My code:

    Download.HPP (my class managed file download):

    #ifndef DOWNLOAD_HPP_
    #define DOWNLOAD_HPP_
    
    // Import required classes
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    // Class Download extends class QObject
    class Download:public QObject
    {
      // Macro code required for signals/slots mechanism
      Q_OBJECT
    
      // Methods and attributes are declared
      // in header files and implemented in cpp file.
      public:
        // Constructor takes our xml and same as in Java/Android we have
        // to provide Context class in this case in a form of QObject
        explicit Download(QUrl xml, QObject *parent = 0);
        virtual ~Download();
        // Method to return our downloaded data in array of bytes
        QByteArray downloadedData() const;
    
      // Signals and Slots implement similar mechanism in C++/Qt
      // as Observer/Observable concept does in Java/Android
      signals:
        void downloaded();
    
      // Method will emit a signal in a form of a downloaded() method
      // much like setChanged() and notifyObservers() does in Java/Android
      public slots:
        void fileDownloaded(QNetworkReply *reply);
    
      // An instance of QNAM class used for HTTP requests
      // much like DownloadTask in Android
      private:
        QNetworkAccessManager manager;
        QByteArray data;
    };
    
    #endif /* DOWNLOAD_HPP_ */
    

    The Download.cpp:

    #include "Download.hpp"
    
    // Notice unlike in Java/Android where we used a secondary thread
    // to process the download in the background all of our methods in
    // QNAM are async. so they are run in the background automatically.
    
    // The constructor of this class equals:
    // public Download(Url xml, Context context) {
    //   super(context);
    // }
    //  .. in Java/Android
    Download::Download(QUrl xml, QObject *parent):QObject(parent)
    {
      // Similar to addObserver(..) in Java/Android we need to link the
      // slot and signal from our Download calss. Here we use: connect()
    
      // Takes address to our QNAM variable
      connect(&manager, SIGNAL(finished(QNetworkReply*)), SLOT(fileDownloaded(QNetworkReply*)));
    
      // Our QNAM requires a Request in form of a QNetworkRequest
      // a lot like HttpUrlConnection
      QNetworkRequest request(xml);
    
      // Now we can use get method to retrieve our data
      manager.get(request);
    
      // 1. Create an instance of a Download class
      // 2. In turn this creates a request on a given URL
      // 3. QNAM Receives the request in a form of a QNRequest class
      // 4. QNAM Returns the response in a form of a QNReply class
      // 5. fileDownload() method is triggered upon compleated download
      // 6. fileDownload() emits a signal to observing classes
    }
    
    Download::~Download(){}
    
    // Think of the following method as onCompleatedDownload() from our
    // Listner class and our Observable
    void Download::fileDownloaded(QNetworkReply *reply)
    {
      // QNAM Returns the data it pulled from our URL in a form of QNReply
      // class we will store this data in a ByteArray
      data = reply->readAll();
    
      // Dispose of QNReply
      reply->deleteLater();
    
      // This is same as in our onCompleated..() method where we called
      // setChanged() and notifyObservers() methods to tell all classes
      // who are registered as listeners that our file has been downloaded
      emit downloaded();
    }
    
    // Simple getter method for received data
    QByteArray Download::downloadedData() const
    {
      return data;
    }
    

    And my applicationui.cpp

    #include "applicationui.hpp"
    
    #include 
    #include 
    #include 
    #include 
    
    // Import our download service class
    #include "Download.hpp"
    
    using namespace bb::cascades;
    
    ApplicationUI::ApplicationUI(bb::cascades::Application *app) :
            QObject(app)
    {
        // prepare the localization
        m_pTranslator = new QTranslator(this);
        m_pLocaleHandler = new LocaleHandler(this);
    
        bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
        // This is only available in Debug builds
        Q_ASSERT(res);
        // Since the variable is not used in the app, this is added to avoid a
        // compiler warning
        Q_UNUSED(res);
    
        // initial load
        onSystemLanguageChanged();
    
        // Create scene document from main.qml asset, the parent is set
        // to ensure the document gets destroyed properly at shut down.
        QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    
        // Create root object for the UI
        AbstractPane *root = qml->createRootObject();
    
        // Set created root object as the application scene
        app->setScene(root);
    
        // Prepare url for our resource
        QUrl url("http://news.google.com/?output=rss");
    
        // Once our main activity is set we can create a new
        // instance of Download class
        Download down(url, this);
    
        // Once Download(Observable) emmits a signal(notifyObserver)
        // in a form of downloaded() ApplicationUI which will be listening
        // will respond with showNotice()
        connect(&down, SIGNAL(downloaded()), SLOT(showNotice()));
    }
    
    // Shows message once Download class emmits a signal
    // that file download has been compleated
    void ApplicationUI::showNotice()
    {
      // Show notice in debug console
      qDebug("FILE DOWNLOAD COMPETE");
    }
    

    And applicationui.hpp

    class ApplicationUI : public QObject
    {
      Q_OBJECT
      public:
        ApplicationUI(bb::cascades::Application *app);
        virtual ~ApplicationUI() { }
    
      private slots:
        void onSystemLanguageChanged();
        // We will treat ApplicationUI as our Main Activity class
        // thus it will be observing our Download class. Once
        // we are notified that our download is complete we want to
        // do something with that data for now just display the message.
        void showNotice();
    

    In my applicationui.cpp in the constructor I create a new instance of download and request a download on successful download showNotice(); method must be triggered despite no error that the showNotice method is never executed because qDebug line is never displayed.

    To expand my question:

    Once a file is downloaded by programming where is the stored file and can we specify our own destenation or is the file stored under downloads folder automatically?

    You represent download like local and end of the function will be thus destroyed as well as the connection.

    Try to declare on the job not the battery. that is of new Download();

    Wherever you get your http response I think that it's already been destroyed.

  • Connection signal of C++ with slot QML

    Before ask you, I searched for answers to this question, but I have not found a satisfactory example.

    I have set up a service network in C++ that performs queries to REST against a backend. An example query would be to download a given element, the id of the item.

    Once the item is extracted, I emit a signal such as:

    itemReceived(QString& itemId, QString& item);
    

    My question is how can I wire this signal to the slot in a QML page so that the status of the answer? I tried to connect the signal on the Qml in C++ slot, as follows:

    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    QObject::connect(this->networkingService,
                         SIGNAL(itemReceived(QString&, QString&)),
                         qml, SLOT(onItemReceived(QString&, QString&));
    

    With a correspondent QML "slot" like this:

        function onItemReceived(x, y) {
            console.log("*********************");
            console.log("Item Received!");
            console.log("*********************");
        }
    

    But it does not work. I also tried using the element of connection of the QtQuick lib, but this also fails.

    Any help would be greatly appreciated. Even if he were to propose a better architecture for the "path of the cascades. Thank you!

    In C++:
    QmlDocument * qml = QmlDocument::create("asset:///main.qml").parent(this);
    QML-> setContextProperty ("_app", this);

    In QML:
    {Page}
    onCreationCompleted: {}
    _APP.itemReceived.connect (onItemReceived)
    }

    function onItemReceived (x, y) {}
    Console.log("***");
    Console.log ("point received!");
    Console.log("***");
    }

    // ...
    }

  • How to pass 'SIGNAL' object as a parameter of QML

    Hi all

    I'm in a fundamental need for the object that caused the SIGNAL to occur,

    E.g. by a signal "onClicked" (in QML) of the button if I call a method of CRACK or Q_INVOKABLE, then what I have

    the purpose of the call?

    As,

    Button {}

    text: 'Add container ".

    onClicked: {}

    injection.playSound ();

    }

    }

    The code is taken from the tutorial. As you can see the "injection" is through "setContextProperty" and having

    "playSound" method I want to do something like this

    injection.playSound (' Button object which invoked this incrimination (onClicked) ');

    and the method in the class curresponding will look like.

    Q_INVOKABLE Sub playSound (bb::cascades:Button * buttonObject);

    One? Please help me in this regard.

    RIM, please take a look at these simple things and update documents.

    Kind regards

    Diagne

    In c ++ make your method in the header

    Q_INVOKABLE void playSound(QObject* buttonObject);
    

    In your cpp file

    MyClass::void playSound(QObject* buttonObject) {
    
    // Cast QObject to Button
    Button* myButton = qobject_cast

    In your QML file:

    injection.playSound(idOfYourButton);
    
  • Error while establishing an Http connection. Once finished signal request is displayed, no call slot

    I'm instantiated MyNetwork class on click of a button in my app class.

    Therefore it is called class constructor MyNetwork in which I'm checking the availability of the network.

    Once found an available network, a sendRequest() method is called that a get request is initialized.

    And the QNetworkAccessManager object emits a finished(QNetworkReply *) signal is connected to a slot (requestFinished(QNetworkReply *reply)) of this class of MyNetwork .

    When the user clicks on the button in the file app.cpp, create an object of class MyNetwork and checking the availability of the network works within its constructor.

    also the connect() method returns true , but sinking ever crack (requestFinished(QNetworkReply *reply)) method where I am Manager of my answer.

    MyNetwork. HPP

     

     

    #ifndef MYNETWORK_HPP_
    #define MYNETWORK_HPP_
    
    #include
    #include 
    #include
    #include
    #include
    #include 
    #include 
    #include
    
    /*!
     * @brief Network Connection Implementation
     */
    class MyNetwork:public QObject
    {
        Q_OBJECT;
    
        public :
            MyNetwork();
    
            /*!
             * @brief Method to create and send request
             */
            void sendRequest();
            /*!
             * @brief Method to check if network is available
             */
            bool isNetworkAvailable();
    
        private slots:
                void requestFinished(QNetworkReply *reply);
    
    };
    
    #endif /* MYNETWORK_HPP_ */
    

    MyNetwork.cpp

     

     


    #include
    #include
    #include
    #include
    
    QNetworkAccessManager *mNetworkMgr;
    
    MyNetwork::MyNetwork() {
    
        if (isNetworkAvailable()) {
            sendRequest();
        } 
    
    }
    
    void MyNetwork::sendRequest() {
    
        mNetworkMgr = new QNetworkAccessManager(this);
        QNetworkReply *reply =
                mNetworkMgr->get(
                        QNetworkRequest(
                                QUrl(
                                        "http://developer.blackberry.com/cascades/files/documentation/device_platform/networking/model.xml")));
        if (reply) {
            qDebug() << "Reply from server is " << reply;
        }
        bool resFromServer = connect(mNetworkMgr, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(requestFinished(QNetworkReply*)));
        qDebug() << "Connection is success : ? : " << resFromServer;
        Q_ASSERT(resFromServer);
        Q_UNUSED(resFromServer);
    }
    
    void MyNetwork::requestFinished(QNetworkReply *reply) {    if (reply) {
            if (reply->error() == QNetworkReply::NoError) {
                qDebug() << "No Error";
            } else {
                int httpStatus = reply->attribute(
                        QNetworkRequest::HttpStatusCodeAttribute).toInt();
                qDebug() << "Error and the code is " << httpStatus;
            }
            reply->deleteLater();
        } else {
            qDebug() << "Reply comes out to be null";
        }
    }
    
    bool MyNetwork::isNetworkAvailable() {
        QNetworkConfigurationManager netMgr;
        QList mNetList = netMgr.allConfigurations(
                QNetworkConfiguration::Active);
        if (mNetList.count() > 0) {
            if (netMgr.isOnline()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    

    Hmm. I just did a quick test for the for you network code.

    I movedbool resFromServer = connect(mNetworkMgr, SIGNAL(finished(QNetworkReply*)),
    this, SLOT(requestFinished(QNetworkReply*)));
    
    to  be before
    
    QNetworkReply *reply =
    mNetworkMgr->get(
    QNetworkRequest(
    QUrl(
    "http://developer.blackberry.com/cascades/files/documentation/device_platform/networking/model.xml")));
    
    in my test.
    

    As I mentioned to signal before start us sending application network.

    I got "Error no." in the newspaper which seemed to have indicated that the signal/slot was triggerred properly in my case.

    Question for you:

    How did you create your object "MyNetwork"?

    is the object still alive when the network request signal is triggerred?

    Maybe the code for create/destorying your object "MyNetwork" segment will be useful

  • Object of type complex C++ exposing to QML

    In a C++ file, I have an object of the typeQList *, which is supposed to be a two dimension an array of strings.

    How to expose this object to QML, I know how I'll be able to navigate / access its functions in QML?

    Currently, in C++, I am able to do this:

    // this will display the QString value in the Console
    qDebug() << "test: " << entries->at(0).at(0);
    

    I really have to do, is to send a two dimension array of strings of C++ to QML. I do this too complicated? Is there another way to solve this problem?

    Solution here: objects exhibition complex C++ Qt QML

Maybe you are looking for