Program stops working while loading QByteArray into QPixmap



  • I'm trying to download an image from the web and save it using a Qt Console App.
    Here is the code:

    temps.pro:

    QT += core
    QT += gui
    QT += network
    
    CONFIG += c++11
    
    TARGET = temps
    CONFIG += console
    CONFIG -= app_bundle
    
    TEMPLATE = app
    
    SOURCES += main.cpp
    
    
    HEADERS += \
        head.h
    
    

    head.h:

    #ifndef HEAD_H
    #define HEAD_H
    
    #include <QCoreApplication>
    #include <QtNetwork/QNetworkAccessManager>
    #include <QtNetwork/QNetworkRequest>
    #include <QtNetwork/QNetworkReply>
    #include <QUrl>
    #include <QEventLoop>
    #include <QString>
    #include <QPixmap>
    
    class desc: public QObject{
        Q_OBJECT
    public:
    
        QNetworkAccessManager nam;
        QNetworkReply* reply;
        QPixmap pm;
    
        desc(QString url){
            QEventLoop loop;
            reply = nam.get(QNetworkRequest(url));
            QObject::connect(&nam,&QNetworkAccessManager::finished,&loop,&QEventLoop::quit);
            loop.exec();
            pm.loadFromData(reply->readAll());
        }
    
    };
    
    #endif // HEAD_H
    
    

    main.cpp:

    #include "head.h"
    
    int main(int argc, char *argv[])
    {
    
        QCoreApplication a(argc, argv);
        desc img("http://www.meteoromania.ro/images/clima/temperatura_orara.png");
        img.pm.save("test.png");
        return a.exec();
    }
    
    

    When compiling, I get follwing error: "temps.exe has stopped working", at line 26 of head.h .
    This is the line : pm.loadFromData(reply->readAll()); .
    reply->readAll() alone doesn't cause problems, and pm.loadFromData(QByteArray()) also works.

    I've pasted the desc class in a Qt Widget app and the code worked with no problems, so I guess the problem is in the .pro file or nearby.


  • Qt Champions 2016

    @cpper

    I don't think you can mix QPixmap with QCoreApplication. Pixmaps are dependent on the window manager running (and you don't interface any). Try with QImage instead.



  • @kshegunov

    I just replaced QPixmap pm; with QImage pm; and it worked. Thank you very much :D


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.