IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau Discussion :

Connecter un QNetworkAccessManager


Sujet :

Réseau

  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations forums :
    Inscription : Avril 2007
    Messages : 211
    Par défaut Connecter un QNetworkAccessManager
    Bonjour,

    Je suis partie d'un exemple qui fonction parfaitement bien:

    http.pro
    Code qt-pro : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    QT += network widgets
     
    HEADERS += httpwindow.h
    SOURCES += httpwindow.cpp \
               main.cpp
    FORMS += authenticationdialog.ui
     
    # install
    target.path = http
    INSTALLS += target

    httpwindow.h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    #ifndef HTTPWINDOW_H
    #define HTTPWINDOW_H
     
    #include <QProgressDialog>
    #include <QNetworkAccessManager>
    #include <QUrl>
     
    QT_BEGIN_NAMESPACE
    class QFile;
    class QLabel;
    class QLineEdit;
    class QPushButton;
    class QSslError;
    class QAuthenticator;
    class QNetworkReply;
    class QCheckBox;
     
    QT_END_NAMESPACE
     
    class ProgressDialog : public QProgressDialog {
        Q_OBJECT
     
    public:
        explicit ProgressDialog(const QUrl &url, QWidget *parent = Q_NULLPTR);
     
    public slots:
       void networkReplyProgress(qint64 bytesRead, qint64 totalBytes);
    };
     
    class HttpWindow : public QDialog
    {
        Q_OBJECT
     
    public:
        explicit HttpWindow(QWidget *parent = Q_NULLPTR);
     
        void startRequest(const QUrl &requestedUrl);
     
    private slots:
        void downloadFile();
        void cancelDownload();
        void httpFinished();
        void httpReadyRead();
        void enableDownloadButton();
        void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
    #ifndef QT_NO_SSL
        void sslErrors(QNetworkReply*,const QList<QSslError> &errors);
    #endif
     
    private:
        QFile *openFileForWrite(const QString &fileName);
     
        QLabel *statusLabel;
        QLineEdit *urlLineEdit;
        QPushButton *downloadButton;
        QCheckBox *launchCheckBox;
        QLineEdit *defaultFileLineEdit;
        QLineEdit *downloadDirectoryLineEdit;
     
        QUrl url;
        QNetworkAccessManager qnam;
        QNetworkReply *reply;
        QFile *file;
        bool httpRequestAborted;
    };
     
    #endif

    httpwindow.cpp, cf lignes 95-96
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
     
    #include <QtWidgets>
    #include <QtNetwork>
    #include <QUrl>
     
    #include "httpwindow.h"
    #include "ui_authenticationdialog.h"
     
    #ifndef QT_NO_SSL
    static const char defaultUrl[] = "https://www.google.fr";
    #else
    static const char defaultUrl[] = "https://www.google.fr";
    #endif
    static const char defaultFileName[] = "index.html";
     
    ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent)
      : QProgressDialog(parent)
    {
        setWindowTitle(tr("Download Progress"));
        setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
        setLabelText(tr("Downloading %1.").arg(url.toDisplayString()));
        setMinimum(0);
        setValue(0);
        setMinimumDuration(0);
    }
     
    void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes)
    {
        setMaximum(totalBytes);
        setValue(bytesRead);
    }
     
    HttpWindow::HttpWindow(QWidget *parent)
        : QDialog(parent)
        , statusLabel(new QLabel(tr("Please enter the URL of a file you want to download.\n\n"), this))
        , urlLineEdit(new QLineEdit(defaultUrl))
        , downloadButton(new QPushButton(tr("Download")))
        , launchCheckBox(new QCheckBox("Launch file"))
        , defaultFileLineEdit(new QLineEdit(defaultFileName))
        , downloadDirectoryLineEdit(new QLineEdit)
    /*    , reply(Q_NULLPTR)
        , file(Q_NULLPTR)*/
        , httpRequestAborted(false)
    {
        setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
        setWindowTitle(tr("HTTP"));
     
        connect(&qnam, &QNetworkAccessManager::authenticationRequired,
                this, &HttpWindow::slotAuthenticationRequired);
    #ifndef QT_NO_SSL
        connect(&qnam, &QNetworkAccessManager::sslErrors,
                this, &HttpWindow::sslErrors);
    #endif
     
        QFormLayout *formLayout = new QFormLayout;
        urlLineEdit->setClearButtonEnabled(true);
        connect(urlLineEdit, &QLineEdit::textChanged,
                this, &HttpWindow::enableDownloadButton);
        formLayout->addRow(tr("&URL:"), urlLineEdit);
        QString downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
        if (downloadDirectory.isEmpty() || !QFileInfo(downloadDirectory).isDir())
            downloadDirectory = QDir::currentPath();
        downloadDirectoryLineEdit->setText(QDir::toNativeSeparators(downloadDirectory));
        formLayout->addRow(tr("&Download directory:"), downloadDirectoryLineEdit);
        formLayout->addRow(tr("Default &file:"), defaultFileLineEdit);
        launchCheckBox->setChecked(true);
        formLayout->addRow(launchCheckBox);
     
        QVBoxLayout *mainLayout = new QVBoxLayout(this);
        mainLayout->addLayout(formLayout);
     
        mainLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
     
        statusLabel->setWordWrap(true);
        mainLayout->addWidget(statusLabel);
     
        downloadButton->setDefault(true);
        connect(downloadButton, &QAbstractButton::clicked, this, &HttpWindow::downloadFile);
        QPushButton *quitButton = new QPushButton(tr("Quit"));
        quitButton->setAutoDefault(false);
        connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close);
        QDialogButtonBox *buttonBox = new QDialogButtonBox;
        buttonBox->addButton(downloadButton, QDialogButtonBox::ActionRole);
        buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
        mainLayout->addWidget(buttonBox);
     
        urlLineEdit->setFocus();
    }
     
    void HttpWindow::startRequest(const QUrl &requestedUrl)
    {
        url = requestedUrl;
        httpRequestAborted = false;
     
        reply = qnam.get(QNetworkRequest(url));
        connect(reply, &QNetworkReply::finished, this, &HttpWindow::httpFinished);
        connect(reply, &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);
     
        ProgressDialog *progressDialog = new ProgressDialog(url, this);
        progressDialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(progressDialog, &QProgressDialog::canceled, this, &HttpWindow::cancelDownload);
        connect(reply, &QNetworkReply::downloadProgress, progressDialog, &ProgressDialog::networkReplyProgress);
        connect(reply, &QNetworkReply::finished, progressDialog, &ProgressDialog::hide);
        progressDialog->show();
     
        statusLabel->setText(tr("Downloading %1...").arg(url.toString()));
    }
     
    void HttpWindow::downloadFile()
    {
        const QString urlSpec = urlLineEdit->text().trimmed();
        if (urlSpec.isEmpty())
            return;
     
        const QUrl newUrl = QUrl::fromUserInput(urlSpec);
        if (!newUrl.isValid()) {
            QMessageBox::information(this, tr("Error"),
                                     tr("Invalid URL: %1: %2").arg(urlSpec, newUrl.errorString()));
            return;
        }
     
        QString fileName = newUrl.fileName();
        if (fileName.isEmpty())
            fileName = defaultFileLineEdit->text().trimmed();
        if (fileName.isEmpty())
            fileName = defaultFileName;
        QString downloadDirectory = QDir::cleanPath(downloadDirectoryLineEdit->text().trimmed());
        if (!downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir())
            fileName.prepend(downloadDirectory + '/');
        if (QFile::exists(fileName)) {
            if (QMessageBox::question(this, tr("Overwrite Existing File"),
                                      tr("There already exists a file called %1 in "
                                         "the current directory. Overwrite?").arg(fileName),
                                      QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
                == QMessageBox::No)
                return;
            QFile::remove(fileName);
        }
     
        file = openFileForWrite(fileName);
        if (!file)
            return;
     
        downloadButton->setEnabled(false);
     
        // schedule the request
        startRequest(newUrl);
    }
     
    QFile *HttpWindow::openFileForWrite(const QString &fileName)
    {
        QScopedPointer<QFile> file(new QFile(fileName));
        if (!file->open(QIODevice::WriteOnly)) {
            QMessageBox::information(this, tr("Error"),
                                     tr("Unable to save the file %1: %2.")
                                     .arg(QDir::toNativeSeparators(fileName),
                                          file->errorString()));
            return Q_NULLPTR;
        }
        return file.take();
    }
     
    void HttpWindow::cancelDownload()
    {
        statusLabel->setText(tr("Download canceled."));
        httpRequestAborted = true;
        reply->abort();
        downloadButton->setEnabled(true);
    }
     
    void HttpWindow::httpFinished()
    {
        QFileInfo fi;
        if (file) {
            fi.setFile(file->fileName());
            file->close();
            delete file;
            file = Q_NULLPTR;
        }
     
        if (httpRequestAborted) {
            reply->deleteLater();
            reply = Q_NULLPTR;
            return;
        }
     
        if (reply->error()) {
            QFile::remove(fi.absoluteFilePath());
            statusLabel->setText(tr("Download failed:\n%1.").arg(reply->errorString()));
            downloadButton->setEnabled(true);
            reply->deleteLater();
            reply = Q_NULLPTR;
            return;
        }
     
        const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
     
        reply->deleteLater();
        reply = Q_NULLPTR;
     
        if (!redirectionTarget.isNull()) {
            const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl());
            if (QMessageBox::question(this, tr("Redirect"),
                                      tr("Redirect to %1 ?").arg(redirectedUrl.toString()),
                                      QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
                downloadButton->setEnabled(true);
                return;
            }
            file = openFileForWrite(fi.absoluteFilePath());
            if (!file) {
                downloadButton->setEnabled(true);
                return;
            }
            startRequest(redirectedUrl);
            return;
        }
     
        statusLabel->setText(tr("Downloaded %1 bytes to %2\nin\n%3")
                             .arg(fi.size()).arg(fi.fileName(), QDir::toNativeSeparators(fi.absolutePath())));
        if (launchCheckBox->isChecked())
            QDesktopServices::openUrl(QUrl::fromLocalFile(fi.absoluteFilePath()));
        downloadButton->setEnabled(true);
    }
     
    void HttpWindow::httpReadyRead()
    {
        // this slot gets called every time the QNetworkReply has new data.
        // We read all of its new data and write it into the file.
        // That way we use less RAM than when reading it at the finished()
        // signal of the QNetworkReply
        if (file)
            file->write(reply->readAll());
    }
     
    void HttpWindow::enableDownloadButton()
    {
        downloadButton->setEnabled(!urlLineEdit->text().isEmpty());
    }
     
    void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authenticator)
    {
        QDialog authenticationDialog;
        Ui::Dialog ui;
        ui.setupUi(&authenticationDialog);
        authenticationDialog.adjustSize();
        ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm(), url.host()));
     
        // Did the URL have information? Fill the UI
        // This is only relevant if the URL-supplied credentials were wrong
        ui.userEdit->setText(url.userName());
        ui.passwordEdit->setText(url.password());
     
        if (authenticationDialog.exec() == QDialog::Accepted) {
            authenticator->setUser(ui.userEdit->text());
            authenticator->setPassword(ui.passwordEdit->text());
        }
    }
     
    #ifndef QT_NO_SSL
    void HttpWindow::sslErrors(QNetworkReply*,const QList<QSslError> &errors)
    {
        QString errorString;
        foreach (const QSslError &error, errors) {
            if (!errorString.isEmpty())
                errorString += '\n';
            errorString += error.errorString();
        }
     
        if (QMessageBox::warning(this, tr("SSL Errors"),
                                 tr("One or more SSL errors has occurred:\n%1").arg(errorString),
                                 QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
            reply->ignoreSslErrors();
        }
    }
    #endif
    main.cpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    #include <QApplication>
    #include <QDesktopWidget>
    #include <QDir>
     
    #include "httpwindow.h"
     
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
     
        HttpWindow httpWin;
        const QRect availableSize = QApplication::desktop()->availableGeometry(&httpWin);
        httpWin.resize(availableSize.width() / 5, availableSize.height() / 5);
        httpWin.move((availableSize.width() - httpWin.width()) / 2, (availableSize.height() - httpWin.height()) / 2);
     
        httpWin.show();
        return app.exec();
    }
    et authenticationdialog.ui:
    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>Dialog</class>
     <widget class="QDialog" name="Dialog">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>389</width>
        <height>243</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>Http authentication required</string>
      </property>
      <layout class="QGridLayout">
       <item row="0" column="0" colspan="2">
        <widget class="QLabel" name="label">
         <property name="text">
          <string>You need to supply a Username and a Password to access this site</string>
         </property>
         <property name="wordWrap">
          <bool>false</bool>
         </property>
        </widget>
       </item>
       <item row="2" column="0">
        <widget class="QLabel" name="label_2">
         <property name="text">
          <string>Username:</string>
         </property>
        </widget>
       </item>
       <item row="2" column="1">
        <widget class="QLineEdit" name="userEdit"/>
       </item>
       <item row="3" column="0">
        <widget class="QLabel" name="label_3">
         <property name="text">
          <string>Password:</string>
         </property>
        </widget>
       </item>
       <item row="3" column="1">
        <widget class="QLineEdit" name="passwordEdit">
         <property name="echoMode">
          <enum>QLineEdit::Password</enum>
         </property>
        </widget>
       </item>
       <item row="5" column="0" colspan="2">
        <widget class="QDialogButtonBox" name="buttonBox">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="standardButtons">
          <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
         </property>
        </widget>
       </item>
       <item row="1" column="0">
        <widget class="QLabel" name="label_4">
         <property name="text">
          <string>Site:</string>
         </property>
        </widget>
       </item>
       <item row="1" column="1">
        <widget class="QLabel" name="siteDescription">
         <property name="font">
          <font>
           <weight>75</weight>
           <bold>true</bold>
          </font>
         </property>
         <property name="text">
          <string>%1 at %2</string>
         </property>
         <property name="wordWrap">
          <bool>true</bool>
         </property>
        </widget>
       </item>
       <item row="4" column="0">
        <spacer>
         <property name="orientation">
          <enum>Qt::Vertical</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>20</width>
           <height>40</height>
          </size>
         </property>
        </spacer>
       </item>
      </layout>
     </widget>
     <resources/>
     <connections>
      <connection>
       <sender>buttonBox</sender>
       <signal>accepted()</signal>
       <receiver>Dialog</receiver>
       <slot>accept()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>248</x>
         <y>254</y>
        </hint>
        <hint type="destinationlabel">
         <x>157</x>
         <y>274</y>
        </hint>
       </hints>
      </connection>
      <connection>
       <sender>buttonBox</sender>
       <signal>rejected()</signal>
       <receiver>Dialog</receiver>
       <slot>reject()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>316</x>
         <y>260</y>
        </hint>
        <hint type="destinationlabel">
         <x>286</x>
         <y>274</y>
        </hint>
       </hints>
      </connection>
     </connections>
    </ui>



    Le code ci dessus fonctionne parfaitement, J'ai donc voulu le réutiliser en créant le code ci-dessous mais la pas moyen de compiler:

    http_issue.pro:
    Code qt-pro : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    #-------------------------------------------------
    #
    # Project created by QtCreator 2018-11-23T19:49:44
    #
    #-------------------------------------------------
     
    QT       += core gui
    QT += network
     
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
     
    TARGET = http_issue
    TEMPLATE = app
     
     
    SOURCES += main.cpp\
            mainwindow.cpp \
        http.cpp
     
    HEADERS  += mainwindow.h \
        http.h
     
    FORMS    += mainwindow.ui

    mainwindow.h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
     
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QIODevice>
    #include <QUrl>
    #include <QtNetwork/QNetworkAccessManager>
    #include <QtNetwork/QNetworkRequest>
    #include <QtNetwork/QNetworkReply>
     
    #include <QMainWindow>
    #include <QStringListModel>
    #include <QTimer>
    #include <QFile>
    #include <QDir>
    #include <iostream>     // std::cout
    #include <fstream>      // std::ifstream
    #include <string>
    #include <QDateTime>
     
     
    /*QT_BEGIN_NAMESPACE
    class QFile;
    class QLabel;
    class QLineEdit;
    class QPushButton;
    class QSslError;
    class QAuthenticator;
    class QNetworkReply;
    class QCheckBox;
     
    QT_END_NAMESPACE*/
     
    namespace Ui {
    class MainWindow;
    }
     
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
     
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
        QNetworkAccessManager *manager2;
     
    public slots:
        void httpFinished2(QNetworkReply *);
        void httpReadyRead2(QIODevice *);
    private:
        Ui::MainWindow *ui;
     
     
    };
     
    #endif // MAINWINDOW_H

    mainwindow.cpp, cf lignes 15-18 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
     
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
     
     
        std::string link = "https://www.google.fr";
        manager2 = new QNetworkAccessManager;
        manager2->get(QNetworkRequest(QUrl(QString::fromStdString(link))));
     
    //fonctionne
    //connect(manager2, SIGNAL(finished(QNetworkReply *)), this, SLOT(httpFinished2(QNetworkReply *)));
        // create an error
    connect(manager2, &QNetworkReply::finished, this, &MainWindow::httpFinished2);
     
    //  connect(manager2, SIGNAL(readyRead(QIODevice *)), this, SLOT(httpReadyRead2(QIODevice *)));
    //  connect(manager2, &QIODevice::readyRead, this, &MainWindow::httpReadyRead);
    }
     
    MainWindow::~MainWindow()
    {
        delete ui;
    }
     
    void MainWindow::httpReadyRead2(QIODevice *reply)
    {
        // this slot gets called every time the QNetworkReply has new data.
        // We read all of its new data and write it into the file.
        // That way we use less RAM than when reading it at the finished()
        // signal of the QNetworkReply
    //    if (file)
    //        file->write(reply->readAll());
    }
     
    void MainWindow::httpFinished2(QNetworkReply *reply)
    {
        QString html = reply->readAll();
        ui->textBrowser->append(html);
    }
    main.cpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #include "mainwindow.h"
    #include <QApplication>
     
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
     
        return a.exec();
    }
    mainwindow.ui
    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>400</width>
        <height>300</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <widget class="QWidget" name="centralWidget">
       <widget class="QTextBrowser" name="textBrowser">
        <property name="geometry">
         <rect>
          <x>10</x>
          <y>10</y>
          <width>371</width>
          <height>231</height>
         </rect>
        </property>
       </widget>
      </widget>
      <widget class="QMenuBar" name="menuBar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>400</width>
         <height>21</height>
        </rect>
       </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
       <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
       </attribute>
       <attribute name="toolBarBreak">
        <bool>false</bool>
       </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
     </widget>
     <layoutdefault spacing="6" margin="11"/>
     <resources/>
     <connections/>
    </ui>

    Quand je complie le code avec le:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    connect(manager2, &QNetworkReply::finished, this, &MainWindow::httpFinished2);
    J'ai l'erreur suivante
    D:\software\projet\http_issue\http_issue\mainwindow.cpp:16: erreur : no matching function for call to 'MainWindow::connect(QNetworkAccessManager*&, void (QNetworkReply::*)(), MainWindow*, void (MainWindow::*)(QNetworkReply*))'
    connect(manager2, &QNetworkReply::finished, this, &MainWindow::httpFinished2);
    ^
    Et je ne comprend vraimant pas puisque ca fonctionne parfaitement avec le code exemple (lignes 85-96 dans httpwindow.cpp du premier exemple)...
    Quelqu'un comprend pourquoi ?

  2. #2
    Invité
    Invité(e)
    Par défaut
    Bonsoir,

    Tu as commis une petite erreur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    connect(manager2, &QNetworkReply::finished, this, &MainWindow::httpFinished2);
    manager2 n'est pas un pointeur vers le type QNetworkReply comme l'était le reply du premier projet, mais de type QNetworkAccessManager* ici.
    Vient donc :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    connect(manager2, &QNetworkAccessManager::finished, this, &MainWindow::httpFinished2);
                       ^^^^^^^^^^^^^^^^^^^^^
    Le connect(manager2, SIGNAL(finished(QNetworkReply *)), this, SLOT(httpFinished2(QNetworkReply *))); avec l'ancienne syntaxe fonctionne, car le QNetworkReply* mentionné est ici le type du paramètre du signal qui est transmis au slot, pas celui de manager2.

  3. #3
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations forums :
    Inscription : Avril 2007
    Messages : 211
    Par défaut
    Merci Beaucoup !!

    tu ne peux pas savoir le temps que j'ai passé sur ce code à essayer de le recompiler dans tout les senses et quand on a la solution on se dit comment j'ai fait pour ne pas le voir... lol

    En tout cas encor merci !!

    Je laisse la discussion ouverte car j'avais un autre souci mais avec ce que tu m'as donnés il va peut être se résoudre. (je vais cherche un peu. Si je ne trouve pas je l'ajouterai à cette discussion)

    Grand merci !!

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations forums :
    Inscription : Avril 2007
    Messages : 211
    Par défaut
    Re-Bonsoir Winjerome,

    En fait, initialement essayais d’implémenter QNetworkAccessManager dans une class et comme ça ne marchait pas j'avais ensuite essayé directement dans le MainWindow.
    Avec ce que tu m'as donné hier et qui marche bien dans la class MainWindow j'ai essayé d’implémenter la class http:

    http.h:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    #ifndef HTTP_H
    #define HTTP_H
     
    #include <QFile>
    #include <QMessageBox>
    #include <QtWidgets>
    #include <QtNetwork>
     
    #include <QProgressDialog>
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QIODevice>
    #include <QUrl>
     
    #include <QMainWindow>
    #include <QStringListModel>
    #include <QTimer>
    #include <QFile>
    #include <QDir>
    #include <iostream>     // std::cout
    #include <fstream>      // std::ifstream
    #include <string>
    #include <QDateTime>
     
     
    QT_BEGIN_NAMESPACE
    class QFile;
    class QLabel;
    class QLineEdit;
    class QPushButton;
    class QSslError;
    class QAuthenticator;
    class QNetworkReply;
    class QCheckBox;
     
    QT_END_NAMESPACE
     
    class http
    {
    QTextBrowser *textBrowser;
    public:
        QNetworkAccessManager *manager2;
        QNetworkReply *reply2;
        http(QTextBrowser *textBrowser_);
        void startRequest(const QUrl &requestedUrl);
        void download_html(QString urlSpec, QString filepath );
    public slots:
        void httpFinished3();
        void httpReadyRead3();
    };
     
    #endif // HTTP_H
    http.cpp, cf. lignes 12 et 13
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    #include "http.h"
     
    http::http(QTextBrowser *textBrowser_)
    {
    textBrowser=textBrowser_;
    textBrowser->append(QString::fromStdString("called http::http(MainWindow *MainWin_)"));
     
        std::string link = "https://www.google.fr";
        manager2 = new QNetworkAccessManager;
        reply2 = manager2->get(QNetworkRequest(QUrl(QString::fromStdString(link))));
     
        connect(reply2, &QNetworkReply::finished, this, &http::httpFinished3);
        connect(reply2, &QIODevice::readyRead, this, &http::httpReadyRead3);
    }
     
    void http::httpFinished3()
    {
        QString html = reply2->readAll();
        textBrowser->append(html);
    }
     
    void http::httpReadyRead3()
    {
     
    }
    http_issue.pro
    Code qt-pro : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
     
    #-------------------------------------------------
    #
    # Project created by QtCreator 2018-11-23T19:49:44
    #
    #-------------------------------------------------
     
    QT       += core gui
    QT += network
     
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
     
    TARGET = http_issue
    TEMPLATE = app
     
     
    SOURCES += main.cpp\
            mainwindow.cpp \
        http.cpp
     
    HEADERS  += mainwindow.h \
        http.h
     
    FORMS    += mainwindow.ui

    mainwindow.h:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
     
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QIODevice>
    #include <QUrl>
    #include <QtNetwork/QNetworkAccessManager>
    #include <QtNetwork/QNetworkRequest>
    #include <QtNetwork/QNetworkReply>
     
    #include <QMainWindow>
    #include <QStringListModel>
    #include <QTimer>
    #include <QFile>
    #include <QDir>
    #include <iostream>     // std::cout
    #include <fstream>      // std::ifstream
    #include <string>
    #include <QDateTime>
    #include "http.h"
     
    /*QT_BEGIN_NAMESPACE
    class QFile;
    class QLabel;
    class QLineEdit;
    class QPushButton;
    class QSslError;
    class QAuthenticator;
    class QNetworkReply;
    class QCheckBox;
     
    QT_END_NAMESPACE*/
     
    namespace Ui {
    class MainWindow;
    }
     
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
     
    public:
        http *http_module;
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
        QNetworkAccessManager *manager2;
        QNetworkReply *reply2;
    public slots:
        void httpFinished3();
        void httpReadyRead3();
    private:
        Ui::MainWindow *ui;
     
     
    };
     
    #endif // MAINWINDOW_H
    mainwindow.cpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
     
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
     
     
        http_module = new http(ui->textBrowser);
     
    }
     
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    mainwindow.ui
    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>400</width>
        <height>300</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <widget class="QWidget" name="centralWidget">
       <widget class="QTextBrowser" name="textBrowser">
        <property name="geometry">
         <rect>
          <x>10</x>
          <y>11</y>
          <width>381</width>
          <height>301</height>
         </rect>
        </property>
       </widget>
      </widget>
      <widget class="QMenuBar" name="menuBar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>400</width>
         <height>21</height>
        </rect>
       </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
       <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
       </attribute>
       <attribute name="toolBarBreak">
        <bool>false</bool>
       </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
     </widget>
     <layoutdefault spacing="6" margin="11"/>
     <resources/>
     <connections/>
    </ui>

    Quand j'essaie de compiler j'ai l'erreur suivante:

    D:\software\projet\http_issue2\http_issue\http.cpp:12: erreur : invalid conversion from 'QNetworkReply*' to 'SOCKET {aka unsigned int}' [-fpermissive]
         connect(reply2, &QNetworkReply::finished, this, &http::httpFinished3);
                                                                             ^
    D:\software\projet\http_issue2\http_issue\http.cpp:12: erreur : cannot convert 'void (QNetworkReply::*)()' to 'const sockaddr*' for argument '2' to 'int connect(SOCKET, const sockaddr*, int)'
    D:\software\projet\http_issue2\http_issue\http.cpp:13: erreur : invalid conversion from 'QNetworkReply*' to 'SOCKET {aka unsigned int}' [-fpermissive]
         connect(reply2, &QIODevice::readyRead, this, &http::httpReadyRead3);
                                                                           ^
    D:\software\projet\http_issue2\http_issue\http.cpp:13: erreur : cannot convert 'void (QIODevice::*)()' to 'const sockaddr*' for argument '2' to 'int connect(SOCKET, const sockaddr*, int)'
    Je ne comprends pas car ce code fonctionne dans la class MainWindow et j'ai copié collé le code dans la class http: Implémenter dans sa propre classe ça ne veut plus compiler...
    Stp, verrais tu ce qui cloche ?

  5. #5
    Invité
    Invité(e)
    Par défaut
    Afin de pouvoir utiliser les signaux et slots, ta classe http doit hériter de la classe QObject (ou de l'une de ses classes dérivées) et avoir la macro Q_OBJECT.

    Ici, étant donné que ta classe n'hérite pas de la classe QObject, elle ne possède pas la fonction membre connect(), et la seule fonction connect() que parvient à trouver le compilateur, c'est la fonction connect en relation avec les sockets. Et comme tu le vois, il a un peu de mal à faire le lien entre les paramètres que tu lui fournis et ceux que cette fonction attend .

  6. #6
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    211
    Détails du profil
    Informations personnelles :
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations forums :
    Inscription : Avril 2007
    Messages : 211
    Par défaut
    Je ne savais pas cela...

    Un infini remerciement !!

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 3
    Dernier message: 29/11/2018, 19h13
  2. couper une connection avec un serveur corba
    Par pons dans le forum CORBA
    Réponses: 3
    Dernier message: 31/05/2002, 10h11
  3. Réponses: 2
    Dernier message: 30/05/2002, 08h54
  4. Réponses: 3
    Dernier message: 22/05/2002, 09h37
  5. [Kylix] Pb connection à Mysql
    Par Anonymous dans le forum EDI
    Réponses: 3
    Dernier message: 25/04/2002, 15h26

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo