2

我开始使用 Qt 进行开发,并且正在尝试获取网页源代码。这是我所拥有的:

主窗口.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QString>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QUrl>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

/**/

class GetHTMLSource : public QObject
{
Q_OBJECT

public:
    GetHTMLSource();
    void GetSource();

public slots:
    void GetDone(QNetworkReply*);

private:
    QNetworkAccessManager* NetManager;
};


GetHTMLSource::GetHTMLSource()
{
    NetManager = new QNetworkAccessManager(this);

    connect(NetManager, SIGNAL(finished(QNetworkReply*)),
         this, SLOT(GetDone(QNetworkReply*)));

}

void GetHTMLSource::GetSource()
{
    NetManager->get(QNetworkRequest(QUrl("http://stackoverflow.com")));
}

void GetHTMLSource::GetDone(QNetworkReply* ReplyIn)
{

    QByteArray DataIn=ReplyIn->readAll();
    QString DataString(DataIn);

    //process str any way you like!

}

/**/

void MainWindow::on_pushButton_clicked()
{
    GetHTMLSource Test;
    Test.GetSource();
}

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

.pro

QT       += core gui

TARGET = TestGetPageSource
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

QT += network

错误是:

mainwindow.obj:-1: error:LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall GetHTMLSource::metaObject(void)const" (?metaObject@GetHTMLSource@@UBEPBUQMetaObject@@XZ)

mainwindow.obj:-1: 错误:LNK2001: 无法解析的外部符号“public: virtual void * __thiscall GetHTMLSource::qt_metacast(char const *)” (?qt_metacast@GetHTMLSource@@UAEPAXPBD@Z)

mainwindow.obj:-1: error:LNK2001: unresolved external symbol "public: virtual int __thiscall GetHTMLSource::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@GetHTMLSource@@UAEHW4Call@QMetaObject@@ HPAPAX@Z)

4

2 回答 2

1

通常,如果您创建派生类,QObject则必须将它们放在单独的头文件和源文件中。

所以一个 .h 和一个 .cpp 文件用于一个类。

于 2012-11-07T20:50:30.340 回答
1

我自己修好了。当然,这是我愚蠢的错误。

在类定义中:

public slots:
    void GetDone(QNetworkReply*);

与实际功能不匹配:

void GetHTMLSource::GetDone(QNetworkReply* ReplyIn)
{ ... }

但是,将其移至单独的 .h 和 .cpp 文件可能会有所帮助。

于 2012-11-08T14:06:52.017 回答