Downloading txt file with qtnetwork - c++

I am trying to download a txt file from a url in QT but i can't seem to make it work.
I am following this guide https://wiki.qt.io/Download_Data_from_URL. I implemented the filedownloader class exactly like it's made in the guide, but when i try to use it like specified in the guide I cannot make it work. I created a slot to be called when the download is finished, but if i try to call the downloader inside like the guide it says it is an undeclared identifier.
Does anyone know how to correctly implement this code?
this is the .cpp of my code
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mainwindow.h"
#include <QStringList>
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QtNetwork/QNetworkReply>
#include <QStringList>
#include <QTimer>
#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <filedownloader.h>
#include <iostream>
#include <QObject>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QUrl emiurl( "url of my file");
// call to the downloader class.In the guide it's made differently, but it doesn't work
FileDownloader emiload(emiurl,this);
//this connect links the end of the download with the textwriter slot
QObject::connect(&emiload, SIGNAL (downloaded()), this, SLOT (textwriter()));
}
>MainWindow::~MainWindow()
{
delete ui;
}
//slot needed to create the txt file from the downloaded one
void MainWindow::textwriter()
{
QByteArray emibyte;
emibyte=emiload->downloadedData(); //this line gives me error
QFile emifile("emi.txt");
emifile.open(QIODevice::WriteOnly);
std::cout << emibyte.size() << std::endl;
QDataStream out(&emifile);
out << emibyte;
std::cout << emifile.size() << std::endl;
}
Now here's the .h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "filedownloader.h"
#include <QMainWindow>
#include <QtNetwork/QNetworkAccessManager>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void textwriter();
};
#endif // MAINWINDOW_H

To make the undeclared identifier go away and successfully compile, you need to add FileDownloader to the class' declaration. This way, it will be known throughout the class.
I chose to go with the approach that's usual in Qt, to declare a pointer to FileDownloader.
#pragma once // <--- this is supported by virtually any compiler today
#include <QMainWindow>
#include <QtNetwork/QNetworkAccessManager>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class FileDownloader; // <-- forward declaration is enough, but you can also #include "filedownloader.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr);
~MainWindow();
private:
Ui::MainWindow* ui = nullptr;
FileDownloader* emiload = nullptr; // <--- the important line!
private slots:
void textwriter();
};
And then instantiate and call emiload in the constructor:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// create an instance of FileDownloader with "new".
emiload = new FileDownloader(QUrl("url of my file"), this);
// using member pointer connection available since Qt5
connect(emiload, &FileDownloader::downloaded, this, &MainWindow::textwriter);
}

Related

Access widgets in QMainWindow from another class

Although it is a frequently asked question, and I've tried many ways including those from SO, like Trying to access widgets of MainWindow from another class, However I still cannot work out a solution, below is my code which reported error "Unknown type name 'CustomClass'" in mainwindow.h:
Thanks in advance for any help!
customclass.h
#ifndef CUSTOMCLASS_H
#define CUSTOMCLASS_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
class MainWindow;
class CustomClass
{
public:
CustomClass(MainWindow *parent);
MainWindow * mainWindow;
void testFunc();
};
#endif // CUSTOMCLASS_H
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "customclass.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
Ui::MainWindow *ui;
CustomClass *customClass = new CustomClass(this);
};
#endif // MAINWINDOW_H
customclass.cpp
#include "customclass.h"
CustomClass::CustomClass(MainWindow *parent)
{
this->mainWindow = parent;
}
void CustomClass::testFunc()
{
mainWindow->ui->label->setText("Hello World!");
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
customClass->testFunc();
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
please read about Circular Dependencies in C++ .
you have problems because you create a loop, you included #include "customclass.h" in MainWindow class and also #include "mainwindow.h" in CustomClass .
it's better that you don't use MainWindow in other classes and add CustomClass objects in MainWindow. The idea is that MainWindow is your root window class and we create one object from it in main.cpp you can do what you ask but logically it's not good.
as we can see in QMainWindow Class document.
The QMainWindow class provides a main application window
A main window provides a framework for building an application's user
interface.
This is your base, you should add the feature you want inside this class not add it in other widgets.
It's the main class for other widgets. This is a clean way to code and if you look at big projects in GitHub you will see this.
move #include "mainwindow.h" and #include "ui_mainwindow.h" inside customclass.h into customclass.cpp before #include "customclass.h" and it works! Thank you!#drescherjm
The fixed code is shown below:
customclass.h
#ifndef CUSTOMCLASS_H
#define CUSTOMCLASS_H
class MainWindow;
class CustomClass
{
public:
CustomClass(MainWindow *parent);
~CustomClass();
MainWindow *mainWindow;
void testFunc();
};
#endif // CUSTOMCLASS_H
customclass.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"//Move these two lines from the header to here
#include "customclass.h"
CustomClass::CustomClass(MainWindow *parent)
{
this->mainWindow = parent;
}
CustomClass::~CustomClass()
{
}
void CustomClass::testFunc()
{
mainWindow->ui->label->setText("Hello World!");
}

Inheritance from MainWindow problem in Qt

I wrote a program to control device with serial port. It works fine but I'd like to seperate the class which would operate serial ports. I also want to have acess to buttons, comboboxes, etc. from this class.
Here are most important parts of code:
Serialsettings header:
#ifndef SERIALSETTINGS_H
#define SERIALSETTINGS_H
#include <QMainWindow>
#include <QSerialPort>
#include "mainwindow.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class SerialSettings : public MainWindow
{
Q_OBJECT
public:
struct Settings
{
QString name;
qint32 baudRate;
QString stringBaudRate;
QSerialPort::DataBits dataBits;
QString stringDataBits;
QSerialPort::Parity parity;
QString stringParity;
QSerialPort::StopBits stopBits;
QString stringStopBits;
QSerialPort::FlowControl flowControl;
QString stringFlowControl;
};
explicit SerialSettings(QWidget *parent = nullptr);
~SerialSettings();
Settings settings() const;
signals:
private:
void fillPortsInfo();
void fillPortsParameters();
void updateSettings();
private:
Settings m_currentSettings;
};
#endif
Serialsettings source:
#include "serialsettings.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include "mainwindow.h"
#include "ui_mainwindow.h"
SerialSettings::SerialSettings(QWidget *parent)
: MainWindow(parent)
{
//some functions
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSerialPort>
//#include "serialsettings.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class SerialSettings;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
Ui::MainWindow *ui;
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
// some code
};
#endif
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "serialsettings.h"
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QString>
#include <QDebug>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//some code
};
MainWindow::~MainWindow()
{
delete ui;
}
I don't have any error at this moment but it finishes with: The program has unexpectedly finished.
Could you help me please with this problem?

How to connect a button from ui-file class to slots from other classes?

I have 3 classes.
class with a mainwindow which comes from the designer(ui-file)
class wich will manage database stuff like inserts
controller class. I want to extend the whole thing to networkcommunication later.
My problem:
I want to connect a simple QPushButton ui->addbutton from the window class with a slot addEntry from the databaseclass, but I get this error :
ERROR: no matching function for call to
'generalControler::connect(QPushButton*, const char*, dbmanager*&,
const char*)'
mydb, SLOT(addEntry()));
//no difference with &mydb or *mydb
MainWindow(0x13f57988, name = "MainWindow") QPushButton(0x13f5f3e0, name = "addButton")
MainWindow(0x13f57988, name = "MainWindow") 0x13f5f3e0//<--?????
//<=Here u see the adresses printed with Qdebug(). top: mainwindowclass. bot: generalcontrolerclass
//why there is missing information after returning the adress of a 'ui->addButton' to another class? Is this maybe the problem?
main.cpp
#include <QApplication>
#include "generalcontroler.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
generalControler controler;
return a.exec();
}
generalcontroler.h
#ifndef GENERALCONTROLER_H
#define GENERALCONTROLER_H
#include <QApplication>
#include "mainwindow.h"
#include "dbmanager.h"
class generalControler : public QObject
{
Q_OBJECT
public:
generalControler();
};
#endif // GENERALCONTROLER_H
generalcontroler.cpp
#include "generalcontroler.h"
#include <QDebug>
generalControler::generalControler(){
MainWindow* window = new MainWindow;
window->show();
dbmanager* mydb= new dbmanager("path_to_my_database.db", window);
mydb->addEntry();
qDebug()<<window->getThis()<<window->getcloseButton();
connect(window->getaddButton(), SIGNAL(clicked()),
mydb, SLOT(addEntry()));
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMessageBox>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QPushButton* getaddButton();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){
ui->setupUi(this);
}
QPushButton* MainWindow::getaddButton()
{
return ui->addButton;
}
dbmanager.h
#ifndef DBMANAGER_H
#define DBMANAGER_H
#include <QSqlDatabase>
#include <QDebug>
#include "mainwindow.h"
class dbmanager: public QObject{
Q_OBJECT
public:
dbmanager(const QString& path);
public slots:
void addEntry();
private:
QSqlDatabase mydatabase;
};
#endif // DBMANAGER_H
dbmanager.cpp
#include "dbmanager.h"
dbmanager::dbmanager(const QString& path)
{
mydatabase = QSqlDatabase::addDatabase("QSQLITE");
mydatabase.setDatabaseName(path);
if (!mydatabase.open())
{
qDebug() << "Error: connection fail";
}
else
{
qDebug() << "Database: connection ok";
}
}
void dbmanager::addEntry()
{
qDebug()<<"addEntry success";
}
I was searching for 6 hours but I never saw such an example with 2 classes, a controler and an ui-file. Could anyone help me?
The connect looks good to me. Try if #include <QPushButton> in generalcontroler.cpp helps. If the compiler knows about QPushButton only by forward-declaration, it doesn't know that it's a QObject and thus the connect() signatures (with QObject* in it) don't match.

QT signal-slot not received

I am trying to connect a signal from a second QMainWindow to the mainwindow. It doesn't say anything about a problem connection when the program is launched, but It doesn't work. I am not very familiar with C++ and Qt so maybe is something simple.
My code consists on a Mainwindow used as a SCADA with Start, stop, On, off buttons. In the second qmainwindow I created a terminal where you can type, start,stop... There, I would like to emit a signal to my MainWindow which is in charge of controlling the multiple threads and windows. The problem is that I cannot connect to my slot. I present here a simple overview of this two pieces of code.
Terminal. h
#ifndef TERMINAL__H
#define TERMINAL__H
#include <QMainWindow>
#include <QTextEdit>
#include <QLineEdit>
#include <QObject>
namespace Ui {
class Terminal_;
}
class Terminal_ : public QMainWindow
{
Q_OBJECT
public:
explicit Terminal_(QWidget *parent = 0);
~Terminal_();
signals:
void turnonPLC_terminal();
public slots:
void newline();
private:
Ui::Terminal_ *ui;
QTextEdit* mTerminal;
QLineEdit* mInput;
};
#endif // TERMINAL__H
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "terminal_.h"
#include "terminal_help.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
Terminal_ *terminal;
public slots:
void turnon_terminal();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "terminal_.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
terminal = new Terminal_(this);
connect(terminal, SIGNAL(turnonPLC_terminal()), this, SLOT(turnon_terminal()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::turnon_terminal(){
turnonPLC=1;
}
terminal_.cpp
#include "terminal_.h"
#include "ui_terminal_.h"
#include <QDockWidget>
#include <QWidget>
#include <QLineEdit>
QString on=("on");
Terminal_::Terminal_(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Terminal_)
{
ui->setupUi(this);
mTerminal = new QTextEdit();
setCentralWidget(mTerminal);
mInput = new QLineEdit();
QDockWidget* qdw = new QDockWidget;
qdw->setWidget(mInput);
addDockWidget(Qt::BottomDockWidgetArea, qdw);
connect (mInput, SIGNAL(returnPressed()),
this, SLOT(newline()));
}
Terminal_::~Terminal_()
{
delete ui;
}
void Terminal_::newline(){
QString command = mInput->text();
if (command==on){
emit turnonPLC_terminal();
}
}
Thanks
The signal-slots part in the code works perfectly. (compiled and tested with some small modifications)
After entering "on" (not On as written in question)
Terminal_::newline() slot called, turnonPLC_terminal() is fired and finally
void MainWindow::turnon_terminal() is called.
However, there are some small details the header file is called terminal_.h, not Terminal.h turnonPLC is not defined. terminal is created by not displayed (no show-call).
I guess, there are simply some many small logic errors. Try to use debugger or trace the chain of expected calls with qDebug.

How do I declare objects from my main window in Qt Creator?

This question should hopefully be easy to answer. I created a few buttons in my MainWindow using Qt Creator, and when I go to write the functions for the buttons, the compiler says they were not declared in this scope. What do I need to #include for these objects to be declared? The compiler error for the following would be 'baseDir' was not declared in this scope. baseDir is the objectName for a lineEdit in my window.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "ui_mainwindow.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void getDir();
void createProj();
private slots:
void on_findDir_clicked();
void on_create_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "functions.h"
#include <QtGui/QApplication>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_findDir_clicked()
{
QString path;
path = QFileDialog::getOpenFileName(
this,
"Choose a file to open",
QString::null,
QString::null );
baseDir->setText( path );
}
The items you define in your .ui file are not added directly to your main window class, they are added to its ui membre.
Try with:
ui->baseDir->setText( path );
Look at the ui_mainwindow.h file that is generated during the build if you're curious.