I'm trying to change the user agent in Qt4.
My code:
main.cpp:
#include <QApplication>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include "qmlapplicationviewer.h"
#include "NetworkAccessManagerFactory.h"
#ifdef DEBUG
#include "logger.h"
#endif
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
app->setOrganizationName("...");
app->setApplicationName("...");
QmlApplicationViewer viewer; /*and stuff related to it*/
QString userAgent("useragentstring");
NetworkAccessManagerFactory factory(userAgent);
viewer.engine()->setNetworkAccessManagerFactory(&factory);
/*showing*/
return app->exec();
}
NetworkAccessManagerFactory.h:
#ifndef NETWORKACCESSMANAGERFACTORY_H
#define NETWORKACCESSMANAGERFACTORY_H
#include <QDeclarativeNetworkAccessManagerFactory>
#include "CustomNetworkAccessManager.h"
class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
{
public:
explicit NetworkAccessManagerFactory(QString p_userAgent = "");
QNetworkAccessManager* create(QObject* parent)
{
CustomNetworkAccessManager* manager = new CustomNetworkAccessManager(__userAgent, parent);
return manager;
}
private:
QString __userAgent;
};
#endif // NETWORKACCESSMANAGERFACTORY_H
CustomNetworkAccessManager.h:
#ifndef CUSTOMNETWORKACCESSMANAGER_H
#define CUSTOMNETWORKACCESSMANAGER_H
#include <QNetworkAccessManager>
#include <QNetworkRequest>
class CustomNetworkAccessManager : public QNetworkAccessManager {
Q_OBJECT
public:
explicit CustomNetworkAccessManager(QString p_userAgent = "", QObject *parent = 0);
protected:
QNetworkReply *createRequest( Operation op, const QNetworkRequest &req, QIODevice * outgoingData=0 )
{
QNetworkRequest new_req(req);
new_req.setRawHeader("User-Agent", __userAgent.toAscii());
QNetworkReply *reply = QNetworkAccessManager::createRequest( op, new_req, outgoingData );
return reply;
}
private:
QString __userAgent;
};
#endif // CUSTOMNETWORKACCESSMANAGER_H
The errors are:
/home/marcin/proj/mobilitare/main.cpp:31: error: undefined reference to `NetworkAccessManagerFactory::NetworkAccessManagerFactory(QString)'
/home/marcin/proj/mobilitare/NetworkAccessManagerFactory.h:13: error: undefined reference to `CustomNetworkAccessManager::CustomNetworkAccessManager(QString, QObject*)'
What am I doing wrong? Thanks!
Related
I wrote a simple threadpool server with qt. When i try to connect to server on win 32/64 all works good. But when I use linux centos 7 server is not responding. I use 127.0.0.1:8080 for server address. Also server uses database mysql. When I try to connect via telnet it connects but nothing happens. I checked for open ports with netstat. Maybe I missed something because of this the server is not working?
Here is my code for server. In fact, there is also an http request handler, but it does not reach it, I tried to output a string in the constructor - it is not called.
QthreadPoolServer.cpp
#include "QThreadPoolServer.h"
#include "QSocketRunnable.h"
#include "ConfigReader.h"
#include <memory>
QThreadPoolServer::QThreadPoolServer()
{
ConfigReader reader(config_file_path);
QHostAddress server_IP(reader.getServerAddress());
int port = reader.getServerPort();
listen(QHostAddress::localhost, 8080);
std:: cout << serverError() << errorString().toStdString();
m_threadPool = std::make_shared<QThreadPool>(this);
}
void QThreadPoolServer::incomingConnection(int handle)
{
std::shared_ptr<QSocketRunnable> runnable = std::make_shared<QSocketRunnable>(handle);
runnable->setAutoDelete(false);
m_threadPool->start(runnable.get());
}
QThreadPoolServer::~QThreadPoolServer()
{
m_threadPool->~QThreadPool();
}
QThreadPoolServer.h
#ifndef QTHREADPOOLSERVER_H
#define QTHREADPOOLSERVER_H
#include <QTcpServer>
#include <QThreadPool>
#include <memory>
class QThreadPoolServer : public QTcpServer
{
public:
explicit QThreadPoolServer();
void incomingConnection(int handle);
~QThreadPoolServer();
private:
std::shared_ptr<QThreadPool> m_threadPool;
};
#endif // QTHREADPOOLSERVER_H
QSocketRunnable.cpp
#include "QSocketRunnable.h"
#include <QString>
#include <memory>
#include <iostream>
QSocketRunnable::QSocketRunnable(int handle) : m_descriptor(handle) { }
void QSocketRunnable::run()
{
QTcpSocket* socket = new QTcpSocket();
socket->setSocketDescriptor(m_descriptor);
socket->waitForReadyRead();
QString request_data = QString(socket->readAll());
HttpRequestHandler handler(request_data);
handler.makeResponse();
QString http_response_result = handler.getHttpResponse();
std::cout << http_response_result.toStdString() << "\n";
socket->write(http_response_result.toUtf8());
socket->waitForBytesWritten(90000);
socket->disconnectFromHost();
socket->close();
socket->deleteLater();
}
QSocketRunnable.h
#ifndef QSOCKETRUNNABLE_H
#define QSOCKETRUNNABLE_H
#include <QRunnable>
#include <QTcpSocket>
#include <QtDebug>
#include <QString>
//#include "IDHelper.h"
//#include "JsonFormatter.h"
//#include "HttpRequestHandler.h"
class QSocketRunnable : public QRunnable
{
public:
QSocketRunnable(int handle);
void run() override;
private:
int m_descriptor;
};
#endif // QSOCKETRUNNABLE_H
main.cpp
#include <QCoreApplication>
#include "QThreadPoolServer.h"
#include "signal.h"
#include <sstream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThreadPoolServer server;
return a.exec();
}
Also std:: cout << serverError() << errorString().toStdString(); returns "-1" that means QAbstractSocket::UnknownSocketError -1 An unidentified error occurred.
As #chehrlic correctly noted: I had an incorrectly overloaded function, so here is the ritht version of QThreadPoolServer.h
QThreadPoolServer.h
#ifndef QTHREADPOOLSERVER_H
#define QTHREADPOOLSERVER_H
#include <QTcpServer>
#include <QThreadPool>
#include <memory>
class QThreadPoolServer : public QTcpServer
{
public:
explicit QThreadPoolServer();
protected:
void incomingConnection(qintptr handle) override;
~QThreadPoolServer();
private:
std::shared_ptr<QThreadPool> m_threadPool;
};
#endif // QTHREADPOOLSERVER_H
My my implementation did not work correctly with a smart pointer to a runnable object:
QThreadPoolServer.cpp
void QThreadPoolServer::incomingConnection(qintptr handle)
{
QSocketRunnable* runnable = new QSocketRunnable(handle)
runnable->setAutoDelete(true);
m_threadPool->start(runnable);
}
i know this question has been answered in this forum before, but I need more specific help.
Here's the code:
sessionwindow.cpp
#include "sessionwindow.h"
#include "ui_sessionwindow.h"
#include "session.h"
#include "utils.h"
#include <QStringList>
SessionWindow::SessionWindow(QWidget *parent) : QDialog(parent), ui(new Ui::SessionWindow)
{
ui->setupUi(this);
this->setFixedSize(this->size());
}
SessionWindow::~SessionWindow()
{
delete ui;
}
void SessionWindow::on_cancelBtn_clicked()
{
close();
}
void SessionWindow::on_createBtn_clicked()
{
QString min = (ui->isMin) ? "min" : "nomin";
QString sp = (ui->spHidd) ? "nosp" : "sp";
QString name = ui->sessionName->text();
QString user = ui->skUser->text();
QString pass = ui->skPass->text();
Utils u;
u.createSession(name, user, pass, min, sp);
}
utils.h (Where the function prototype is declared)
#ifndef UTILS_H
#define UTILS_H
#include <QString>
#include <QStringList>
class Utils
{
public:
Utils();
~Utils();
void startSkype(QString, QString, QStringList);
void createSession(QString , QString, QString, QString, QString);
};
#endif // UTILS_H
utils.cpp (Where the function is)
#include "utils.h"
#include "session.h"
#include <QString>
#include <QStringList>
#include <QVector>
#include <QDebug>
QVector<Session> sessions;
Utils::Utils()
{
}
Utils::~Utils()
{
}
void Utils::startSkype(QString user, QString pass, QStringList options)
{
}
void createSession(QString name, QString user, QString pass, QString isMin, QString spHid)
{
sessions.append(Session(name, user, pass, isMin, spHid));
}
The problem is tha I can't compile it, it just throws an error: undefined reference to `Utils::createSession(QString, QString, QString, QString, QString)'
Sorry if I explained bad and thanks for the help!! :D
You forgot to put Utils:: in front of your method definition:
void createSession(QString name, QString user, QString pass, QString isMin, QString spHid)
{
sessions.append(Session(name, user, pass, isMin, spHid));
}
should be
void Utils::createSession(QString name, QString user, QString pass, QString isMin, QString spHid)
{
sessions.append(Session(name, user, pass, isMin, spHid));
}
I have 2 Qt programs that are basically identical, I copied the code from one of them to the other to modify it and save it as a new project, now the second one doesn't run and gives a bunch of errors which don't make sense because the other one runs and they are the same where the errors are coming up. Here is the code:
#ifndef FILM_H
#define FILM_H
#include <QWidget>
#include <QString>
#include <QDate>
class Film: public QObject{
Q_OBJECT
Q_PROPERTY( QString title READ getTitle WRITE setTitle);
Q_PROPERTY( int duration READ getDuration WRITE setDuration);
Q_PROPERTY( QString director READ getDirector WRITE setDirector);
Q_PROPERTY( QDate releaseDate READ getReleaseDate WRITE setReleaseDate);
public:
Film(QString t,int dur,QString dir,QDate r);
Film();
void setTitle(QString t);
void setDuration(int dur);
void setDirector(QString dir);
void setReleaseDate(QDate r);
QString getTitle() const;
int getDuration() const;
QString getDirector() const;
QDate getReleaseDate() const;
QString toString();
private:
QString m_title;
int m_duration;
QString m_director;
QDate m_releaseDate;
};
#endif // FILM_H
#ifndef FILMWRITER_H
#define FILMWRITER_H
#include "Film.h"
#include <QtGui>
#include <QFile>
class FilmWriter{
public:
void accessFilm(Film& f);
};
#endif // FILMWRITER_H
#ifndef FILMINPUT_H
#define FILMINPUT_H
#include <QMainWindow>
#include "Film.h"
#include "FilmWriter.h"
#include <QLabel>
#include <QTextEdit>
#include <QPushButton>
namespace Ui {
class FilmInput;
}
class FilmInput : public QMainWindow
{
Q_OBJECT
public:
explicit FilmInput(QWidget *parent = 0);
~FilmInput();
void obtainFilmData(Film& f);
void saveFilm(Film& f);
public slots:
void getFilm();
private:
Ui::FilmInput *ui;
//widgets
QMainWindow* window;
QLabel* infoLabel;
QLabel* titleLabel;
QLabel* durationLabel;
QLabel* directorLabel;
QLabel* relDateLabel;
QTextEdit* titleEdit;
QTextEdit* durationEdit;
QTextEdit* directorEdit;
QTextEdit* relDateEdit;
QPushButton* saveBtn;
QPushButton* cancelBtn;
Film f;
//sets up gui and connects signals and slots
void setUpGui();
};
#endif // FILMINPUT_H
#include "Film.h"
#include <QDate>
#include <QString>
Film::Film(QString t,int dur,QString dir,QDate r):m_title(t),m_duration(dur),m_director(dir),m_releaseDate(r){
}
Film::Film(){
}
void Film::setTitle(QString t){
m_title = t;
}
void Film::setDuration(int dur){
m_duration = dur;
}
void Film::setDirector(QString dir){
m_director = dir;
}
void Film::setReleaseDate(QDate r){
m_releaseDate = r;
}
QString Film::getTitle() const{
return QString("%1").arg(m_title);
}
int Film::getDuration() const{
return m_duration;
}
QString Film::getDirector() const{
return QString("%1").arg(m_director);
}
QDate Film::getReleaseDate() const{
return m_releaseDate;
}
QString Film::toString()
{
return m_title + " " + m_duration + " " + m_director + " " + m_releaseDate.toString();
}
#include "FilmWriter.h"
#include <QtGui>
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QObject>
#include <QTextStream>
void FilmWriter::accessFilm(Film& f){
QVariant v1 = f.property("title");
QVariant v2 = f.property("duration");
QVariant v3 = f.property("director");
QVariant v4 = f.property("releaseDate");
QString str = v1.toString() +" "+ v2.toString() +" "+ v3.toString() +" "+ v4.toString();
QMessageBox msgBox;
msgBox.setText(str);
msgBox.exec();
}
#include "filminput.h"
#include "ui_filminput.h"
#include <QtGui>
#include "Film.h"
#include "FilmWriter.h"
#include <QTextEdit>
#include <QDate>
#include <QString>
FilmInput::FilmInput(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FilmInput)
{
ui->setupUi(this);
setUpGui();
}
FilmInput::~FilmInput()
{
delete ui;
}
void FilmInput::setUpGui(){
//initialise widgets
infoLabel = new QLabel("Please enter film data which will be saved to a file",this);
titleLabel = new QLabel("Film Title",this);
durationLabel = new QLabel("Film Duration",this);
directorLabel = new QLabel("Film Director",this);
relDateLabel = new QLabel("Film Release Date",this);
titleEdit = new QTextEdit(this);
durationEdit = new QTextEdit(this);
directorEdit = new QTextEdit(this);
relDateEdit = new QTextEdit(this);
saveBtn = new QPushButton("Save Film",this);
cancelBtn = new QPushButton("Cancel",this);
//set layout
QFormLayout* layout = new QFormLayout();
layout->addWidget(infoLabel);
layout->addWidget(titleLabel);
layout->addWidget(titleEdit);
layout->addWidget(durationLabel);
layout->addWidget(durationEdit);
layout->addWidget(directorLabel);
layout->addWidget(directorEdit);
layout->addWidget(relDateLabel);
layout->addWidget(relDateEdit);
layout->addWidget(saveBtn);
layout->addWidget(cancelBtn);
this->ui->widget->setLayout(layout);
this->setWindowTitle("Film Archive");
connect(saveBtn,SIGNAL(clicked()),this, SLOT(getFilm()));
connect(cancelBtn,SIGNAL(clicked()),this,SLOT(close()));
}
void FilmInput::getFilm(){
Film f1(titleEdit->toPlainText(),durationEdit->toPlainText().toInt() ,directorEdit->toPlainText(),
QDate::fromString(relDateEdit->toPlainText(),"dd/MM/YYYY"));;
obtainFilmData(f1);
}
void FilmInput::obtainFilmData(Film &f){
FilmWriter f2;
f2.accessFilm(f);
}
#include <QtGui/QApplication>
#include "filminput.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FilmInput w;
w.show();
return a.exec();
}
the error dump:
..\Ass1Q2\filminput.cpp: In constructor 'FilmInput::FilmInput(QWidget*)':
..\Ass1Q2\filminput.cpp:12: error: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: error: forward declaration of 'struct Ui::FilmInput'
..\Ass1Q2\filminput.cpp:14: error: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: error: forward declaration of 'struct Ui::FilmInput'
..\Ass1Q2\filminput.cpp: In destructor 'virtual FilmInput::~FilmInput()':
..\Ass1Q2\filminput.cpp:20: warning: possible problem detected in invocation of delete operator:
..\Ass1Q2\filminput.cpp:20: warning: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: warning: forward declaration of 'struct Ui::FilmInput'
..\Ass1Q2\filminput.cpp:20: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.
..\Ass1Q2\filminput.cpp: In member function 'void FilmInput::setUpGui()':
..\Ass1Q2\filminput.cpp:50: error: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: error: forward declaration of 'struct Ui::FilmInput'
mingw32-make[1]: Leaving directory `C:/Unisa/COS3711/assignments/Ass1Q2-build-desktop'
mingw32-make: Leaving directory `C:/Unisa/COS3711/assignments/Ass1Q2-build-desktop'
mingw32-make[1]: *** [debug/filminput.o] Error 1
mingw32-make: *** [debug] Error 2
The process "C:/Qt/2010.04/mingw/bin/mingw32-make.exe" exited with code %2.
Error while building project Ass1Q2 (target: Desktop)
When executing build step 'Make'
You copied the code, but not pro file. So, you may miss to add UI file to profile, to invoc UI compiler to generate "ui_FileInput.h" source. Please copy UI file and update .pro file with FORMS += FileInput.ui may solve your problem. To know better you can comment "ui_FileInput.h" and see the behaviour.
Hi I am trying to send an HTTP GET request and receive the result with a function. But I am getting this error:
no matching function for call to 'HttpNetworkRequest::connect(QNetworkAccessManager*&, const char*, RequestFinishFunction&, const
char*)'
the connect function is in this HttpNetworkRequest.cpp file
#include "HttpNetworkRequest.hpp"
#include <QObject>
#include <QIODevice>
#include <QDir>
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/XmlDataModel>
#include <RequestFinishFunction.hpp>
using namespace bb::cascades;
HttpNetworkRequest::HttpNetworkRequest(bb::cascades::Application *app)
: QObject(app)
{
QNetworkRequest networkRequest = QNetworkRequest();
networkRequest.setUrl(QUrl("http://www.blackberry.com"));
RequestFinishFunction req;
QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager;
bool res = connect(networkAccessManager,SIGNAL(finished(QNetworkReply*)),
req,SLOT(requestFinished()));
Q_ASSERT(res);
Q_UNUSED(res);
networkAccessManager->get(networkRequest);
}
The included RequestFinishFunction.hpp
#ifndef REQUESTFINISHFUNCTION_HPP_
#define REQUESTFINISHFUNCTION_HPP_
#include <bb/cascades/ActivityIndicator>
#include <QObject>
#include <QObject>
class RequestFinishFunction : QObject
{
public slots:
void requestFinished(QNetworkReply* reply);
};
#endif /* REQUESTFINISHFUNCTION_HPP_ */
The RequestFinishFunction.cpp file is
#include <bb/cascades/ActivityIndicator>
#include <QObject>
#include <QObject>
#include <RequestFinishFunction.hpp>
void RequestFinishFunction::requestFinished(QNetworkReply* reply)
{
reply->deleteLater();
}
Syntax of connect method
bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection )
We have to pass references of both sender & receiver.
You didn't send reference of receiver. You have two options to do so.
1) Send reference of req using & operator in connect method call
Replace
connect(networkAccessManager,SIGNAL(finished(QNetworkReply*)), req,SLOT(requestFinished()));
with
connect(networkAccessManager,SIGNAL(finished(QNetworkReply*)), &req,SLOT(requestFinished()));
OR
2) Declare req as pointer
Replace
RequestFinishFunction req;
with
RequestFinishFunction *req;
Here is my implementation
Film.h //header
#ifndef FILM_H
#define FILM_H
#include <QString>
class Film {
protected:
QString title;
double dailyRate;
public:
Film(QString ti,double dr);
virtual double calculateRental(int num)const;
};
#endif // FILM_H
Film.cpp
#include "film.h"
#include <QString>
Film::Film(QString ti,double dr){
title=ti;
dailyRate=dr;
}
double Film::calculateRental(int num)const {
return dailyRate*num;
}
main.cpp
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>
#include "film.h"
using namespace std;
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QTextStream cout(stdout, QIODevice::WriteOnly);
Film f("Top Gun", 10.00); //create an instance of a film
cout <<f.calculateRental(2);
return a.exec();
}
how do I count the number of Film instances created? I know is something like that:
static int numOfFilms;
numOfFilms++;
how do I use the code?
It depends. If you replace Class with class, and QString has a conversion constructor from const char*, then yes.