I'm trying a very, very simple QT networking program. For some reason it crashes when executing without any error message, since it's not printing out any of the outputs to the command line as expected. Here's the code:
qtTCPservertest.pro
QT += core
QT += network
QT -= gui
TARGET = qtTCPservertest
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
theserver.cpp
HEADERS += \
theserver.h
theServer.h
#ifndef THESERVER_H
#define THESERVER_H
#include <QTcpServer>
#include <stdio.h>
class theServer : public QTcpServer{
Q_OBJECT
public:
theServer();
~theServer();
void goOnline();
};
#endif // THESERVER_H
theServer.cpp
#include "theserver.h"
theServer::theServer()
{
}
theServer::~theServer()
{
}
void theServer::goOnline()
{
bool status = false;
unsigned int portNum = 5200;
status = this->listen(QHostAddress::Any, portNum );
// Check, if the server did start correctly or not
if( status == true )
printf("Server up\n");
else
printf("Server down\n");
}
and the main.cpp
#include <QCoreApplication>
#include <stdio.h>
#include "theserver.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
printf("Test\n");
theServer* aServer = new theServer();
aServer->goOnline();
aServer->~theServer();
return a.exec();
}
Has anyone an idea, where I went wrong? Since there is no error I'm total clueless. It just doesn't print out anything, it just tells me to hit any key to close the window, as if it came to an end as usual.
Thanks for any advise.
Here is the code that compiles and works for me (Qt 5.5):
TheServer.h
#ifndef THESERVER_H
#define THESERVER_H
#include <QTcpServer>
class TheServer : public QTcpServer
{
Q_OBJECT
public:
TheServer(QObject *pParent = nullptr);
void goOnline();
};
#endif // THESERVER_H
TheServer.cpp
#include <QDebug>
#include "TheServer.h"
TheServer::TheServer(QObject *pParent)
: QTcpServer(pParent)
{
}
void TheServer::goOnline()
{
bool status = listen(QHostAddress::Any, 5200);
if (status) {
qDebug() << "Server up";
} else {
qDebug() << "Server down";
}
}
main.cpp
#include <QCoreApplication>
#include "TheServer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TheServer server;
server.goOnline();
return a.exec();
}
Related
I have been facing issues with a simple C++ group project I am working on. I am trying to create a thread that does a background job while my UI and the main app is working perfectly fine. I tried to the same thing on a test file before and it worked fine, however doing it in the Qt Project doesn't works somehow. I do not have much idea about Qt for ref. Here's my code. I am trying to update the progress bar repeatedly till my app runs.
Here's my code for more over view
test code
#include <thread>
#include <iostream>
#include <windows.h>
int getRamUsage() {
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
return statex.dwMemoryLoad;
}
void ramUsage() {
while (true) {
std::cout << "RAM usage: " << getRamUsage() << "%" << std::endl;
Sleep(1000);
}
}
int main() {
auto ramLoop = [=]() {
while (true) {
std::cout << "RAM usage: " << getRamUsage() << "%" << std::endl;
Sleep(1000);
}
};
std::thread t1(ramLoop);
t1.join();
}
It works, But it doesn't in the Front Ended Qt one I mentioned. May I know any other ideas to make this work.
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ramUsage.h"
#include <thread>
#include <windows.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto ramLoop = [=]() {
while (true) {
ui->ramBar->setValue(getRamUsage());
Sleep(1000);
}
};
std::thread t(ramLoop);
t.join();
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include "mainwindow.h"
#include <stdio.h>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
ramUsage.cpp
#include <windows.h>
#include "../ramUsage.h"
int getRamUsage() {
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
return statex.dwMemoryLoad;
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
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;
};
#endif // MAINWINDOW_H
ramUsage.h
#pragma once
#ifndef RAMUSAGE_H
#define RAMUSAGE_H
int getRamUsage();
#endif // RAMUSAGE_H
I tried using QProcess and the basic threading options for windows which doesn't seem to work
As described on https://wiki.qt.io/How_to_create_a_library_with_Qt_and_use_it_in_an_application I would like to create dll (Windows 10) and load it dynamically be using QLibrary as plugin.
In Dependency Walker I see that exports and dll could be loaded. But resolve gives me always 0. I tried several examples and hinds in web, but no success. What do I wrong?
.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
TEMPLATE = lib
HEADERS += eurolite_dmx512_pro_mk2.h \
Eurolite_DMX512_Pro_MK2_global.h
SOURCES += eurolite_dmx512_pro_mk2.cpp
DEFINES += EUROLITE_DMX512_PRO_MK2_LIBRARY
global.h
#ifndef EUROLITE_DMX512_PRO_MK2_GLOBAL_H
#define EUROLITE_DMX512_PRO_MK2_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(EUROLITE_DMX512_PRO_MK2_LIBRARY)
# define EUROLITE_DMX512_PRO_MK2 Q_DECL_EXPORT
#else
# define EUROLITE_DMX512_PRO_MK2 Q_DECL_IMPORT
#endif
#endif // EUROLITE_DMX512_PRO_MK2_GLOBAL_H
.h
#ifndef SHARED_H
#define SHARED_H
#include "Eurolite_DMX512_Pro_MK2_global.h"
#include <QDebug>
class Device
{
public:
Device();
void Testdll() {qDebug("OK");}
};
extern "C" EUROLITE_DMX512_PRO_MK2 int getVersion();
extern "C" EUROLITE_DMX512_PRO_MK2 QWidget *createWidget1();
int EUROLITE_DMX512_PRO_MK2 libStart(void)
{
Device device;
return 0;
}
#endif // SHARED_H
.cpp
#include <QWidget>
#include "eurolite_dmx512_pro_mk2.h"
Device::Device() {}
int getVersion()
{
return 3;
}
QWidget *createWidget1()
{
QWidget *widget = new QWidget();
widget->resize(100, 100);
return widget;
}
plugintest.c++
#include "dmxservice.h"
#include <QApplication>
#include <QDebug>
#include <QLibrary>
#include <QMessageBox>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
bool dmxLibAktiv = false;
QLibrary dmxlib;
QMessageBox msgBox;
QFile file(QCoreApplication::applicationDirPath()+"/devices/Eurolite_DMX512_Pro_MK2.dll");
if(file.exists()==true)
{
QLibrary dmxlib(QCoreApplication::applicationDirPath()+"/devices/Eurolite_DMX512_Pro_MK2.dll");
if(dmxlib.load()==true)
{
dmxLibAktiv = dmxlib.isLoaded();
msgBox.setText("DLL loaded!\n");
msgBox.exec();
}
else
{
msgBox.setText("DLL not loaded!\n"+dmxlib.errorString());
msgBox.exec();
}
}
else
{
msgBox.setText("DLL not found '"+QCoreApplication::applicationDirPath()+"'!\n");
msgBox.exec();
}
if (dmxLibAktiv) {
typedef QWidget *(*CreateWidgetFunction)();
CreateWidgetFunction cwf = CreateWidgetFunction(dmxlib.resolve("createWidget1"));
if (cwf) {
QWidget *widget = cwf();
if (widget)
widget->show();
} else {
qDebug() << "Could not show widget from the loaded library";
}
}
DmxService w;
w.show();
return a.exec();
}
You created a local QLibrary dmxlib(...); inside the if (file.exists()) branch. So the outer dmxlib instance is never initialized.
ADDED: Do not re-declare the variable inside the if block, use setFileName() instead:
QLibrary dmxlib;
...
if (file.exists()) {
dmxlib.setFileName(QCoreApplication::applicationDirPath()+"/devices/Eurolite_DMX512_Pro_MK2.dll");
if (dmxlib.load())
....
}
// ... use dmxlib
I'm a very very beginner in C++ (QT), normally i used to work with the PHP/MYSQL for web, Python for server tasks etc..., i want to learn C++ and i have a project on my work that needs a daemon, and some clients who talks to each other, i want to create this in C++.
I was searching for some examples for handling SQL returned DATA, i was creating function like get_user(); get_users(); etc..., and i should do something with this, in PHP i just had to put them in an array and voila, returned.
What is the best practice in QT C++ to do that? in the many examples on the web they all do it in the main function, so this didn't help me very much, my Database transactions would be in a separated header/source file (class).
some examples how my code is now:
main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QSqlDatabase>
#include "database_mysql.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
database_mysql db;
// should have here an object or an array so that i could work with it...
db.test_query();
return a.exec();
}
database_mysql.h
#ifndef DATABASE_MYSQL_H
#define DATABASE_MYSQL_H
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QtDebug>
class database_mysql
{
QSqlDatabase m_database;
public:
database_mysql();
~database_mysql();
bool connect();
void disconnect();
//This should not be a bool...
bool test_query();
};
#endif // DATABASE_MYSQL_H
database_mysql.cpp
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QtDebug>
#include "database_mysql.h"
// Constructer
database_mysql::database_mysql()
{
}
// Desctructer
database_mysql::~database_mysql()
{
disconnect();
}
bool database_mysql::connect()
{
bool result = false;
// Connect the database, for the moment still static defined
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("anna");
db.setUserName("anna");
db.setPassword("anna");
if(!db.open()){
qDebug() << "Not Connectd";
}else{
qDebug() << "Database Connected";
result = true;
}
return result;
}
void database_mysql::disconnect()
{
if (m_database.open())
{
m_database.close();
}
}
bool database_mysql::test_query()
{
bool result = false;
if(!connect()){
qDebug() << "Database Not Connected!";
}else{
QSqlQuery query;
query.exec("SELECT * FROM sys_user");
while (query.next()){
QString name = query.value(1).toString();
qDebug() << "Name: " << name;
}
result = true;
}
return result;
}
I really searched the web for this, its very hard to find some of this kind of information, if you have this kind of information, a hint/url would be very appreciated.
Many Thanks,
Ben
As Martin wrote, you can just use an array or list. Here's a sample with QList.
I choosed to hand the list over as a reference parameter, so you still have the bool as return value as success indicator.
main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QSqlDatabase>
#include <QList>
#include "database_mysql.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
database_mysql db;
QList<QString> names;
db.test_query(names);
for_each(QString name, names){
qDebug()<< "Name: " << name;
}
return a.exec();
}
database_mysql.h
#ifndef DATABASE_MYSQL_H
#define DATABASE_MYSQL_H
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QtDebug>
class database_mysql
{
QSqlDatabase m_database;
public:
database_mysql();
~database_mysql();
bool connect();
void disconnect();
//This should not be a bool...
bool test_query(QList<QString>& namesList);
};
#endif // DATABASE_MYSQL_H
database_mysql.cpp
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QtDebug>
#include "database_mysql.h"
// Constructer
database_mysql::database_mysql()
{
}
// Desctructer
database_mysql::~database_mysql()
{
disconnect();
}
bool database_mysql::connect()
{
bool result = false;
// Connect the database, for the moment still static defined
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("anna");
db.setUserName("anna");
db.setPassword("anna");
if(!db.open()){
qDebug() << "Not Connectd";
}else{
qDebug() << "Database Connected";
result = true;
}
return result;
}
void database_mysql::disconnect()
{
if (m_database.open())
{
m_database.close();
}
}
bool database_mysql::test_query(QList<QString>& namesList)
{
bool result = false;
namesList.clear();//clear possible old entries
if(!connect()){
qDebug() << "Database Not Connected!";
}else{
QSqlQuery query;
query.exec("SELECT * FROM sys_user");
while (query.next()){
QString name = query.value(1).toString();
namesList.append(name);
}
result = true;
}
return result;
}
I am doing an exercise qt console application on threading, here is the code:
// make two thread, one checking on the state of the other
//////////////////////////////////////
// main.cpp
#include "mytimer.h"
#include "mythread.h"
#include "checkthread.h"
#include <QCoreApplication>
#include <QString>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread mThread1;
mThread1.name = "thread 1";
mThread1.start(QThread::HighestPriority);
CheckThread mCheck(&mThread1);
mCheck.start();
return a.exec();
}
///////////////////////////////////////
// mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QtCore>
class MyThread : public QThread
{
public:
MyThread();
void run();
QString name;
bool stop;
int sum;
};
#endif // MYTHREAD_H
//////////////////////////////////////
// mythread.cpp
#include "mythread.h"
MyThread::MyThread()
{
sum = 0;
}
void MyThread::run()
{
qDebug() << this->name << " running...";
for(int i=0; i<1000; i++) {
this->sum += i;
qDebug() << this->name << " counting " << sum;
this->sleep(1);
if(this->stop) {
break;
}
}
}
//////////////////////////////////////
// checkthread.h
#ifndef CHECKTHREAD_H
#define CHECKTHREAD_H
#include <QThread>
#include "mythread.h"
class CheckThread : public QThread
{
Q_OBJECT
public:
explicit CheckThread(QObject *parent = 0);
explicit CheckThread(MyThread *tocheck);
void run();
MyThread *tocheck_;
};
#endif // CHECKTHREAD_H
//////////////////////////////////////
// checkthread.cpp
#include "checkthread.h"
CheckThread::CheckThread(QObject *parent) :
QThread(parent)
{
}
CheckThread::CheckThread(MyThread *tocheck) :
tocheck_(tocheck)
{
}
void CheckThread::run() {
while(true) {
this->sleep(1);
if(tocheck_->sum > 15) {
tocheck_->stop = true;
}
}
}
The expected behavior is that mThread1 shoud count to 15 and then stop,
but instead it is stuck at 0.
Interestingly, if I add the following code into the main.cpp file, then it runs
ok:
void Write(QString Filename)
{
QFile fh(Filename);
if(!fh.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "Could not open file for writing";
return;
}
QTextStream out(&fh);
out << "hi world";
fh.flush();
fh.close();
}
void Read(QString Filename)
{
QFile fh(Filename);
if(!fh.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "Could not open file for writing";
return;
}
QTextStream in(&fh);
QString mtext = in.readAll();
qDebug() << mtext;
}
I am using qt 4.8 on a kubuntu 13.10 machine, and the ide is qt creator 3.0.1
The problem is the member var stop in mythread.h was not initialized.
But this does not explain why the Read and Write functions in main.cpp solves the problem. Very puzzling.
I have written a QT - webkit application. this application fires a callback when my pSeudo driver gets the character 'l'. However, the application crashes during a firecallback - it says - QObject::setParent: Cannot set parent, new parent is in a different thread. I don't know to fix this, I tried doing moveToThread, but it doesn't help. Please help me here.
#include <QtGui/QApplication>
#include <QApplication>
#include <QDebug>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
#include <QThread>
#include <unistd.h>
#include <fcntl.h>
class DemoThread;
class MyJavaScriptOperations : public QObject {
Q_OBJECT
public:
QWebView *view;
DemoThread *m_pDemoThread;
MyJavaScriptOperations();
void firecb();
bool slot_installed;
signals:
void alert_script_signal();
public slots:
void JS_ADDED();
void loadFinished(bool);
private:
};
class DemoThread : public QThread {
public:
DemoThread( MyJavaScriptOperations *pJavascriptOp);
protected:
void run();
private :
MyJavaScriptOperations *m_pJavascriptOp;
};
DemoThread::DemoThread(MyJavaScriptOperations *pJavascriptOp):m_pJavascriptOp(pJavascriptOp)
{
}
void DemoThread:: run()
{
int filedesc = open("/dev/pSeudoDrv", O_RDONLY);
if(filedesc < 0)
{
qDebug()<<"Couldn't open Driver.";
}
unsigned char buff;
while(1)
{
read(filedesc,&buff, 1);
qDebug()<<"The code received is "<< buff;
if ( (m_pJavascriptOp->slot_installed == true) && (buff == 166))
{
m_pJavascriptOp->firecb();
}
qDebug()<<"Running Thread.";
sleep(6);
}
}
void MyJavaScriptOperations::JS_ADDED()
{
qDebug()<<__PRETTY_FUNCTION__;
view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", this);
}
void MyJavaScriptOperations::loadFinished(bool oper)
{
qDebug()<<__PRETTY_FUNCTION__<< oper;
slot_installed = true;
// firecb();
}
void MyJavaScriptOperations::firecb()
{
qDebug()<<__PRETTY_FUNCTION__;
view->page()->mainFrame()->evaluateJavaScript("JavaScript_function()");
}
MyJavaScriptOperations::MyJavaScriptOperations()
{
qDebug()<<__PRETTY_FUNCTION__;
view = new QWebView();
view->resize(400, 500);
connect(view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(JS_ADDED()));
connect(view, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
view->load(QUrl("./index.html"));
view->show();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyJavaScriptOperations *jvs = new MyJavaScriptOperations;
DemoThread *thread = new DemoThread(jvs);
jvs->moveToThread(thread);
thread->start();
return a.exec();
}
#include "main.moc"
This is the crash-error I get -
./QT_DEMO
MyJavaScriptOperations::MyJavaScriptOperations()
loaded the Generic plugin
The code received is 156
Running Thread.
The code received is 166
void MyJavaScriptOperations::firecb()
QObject::setParent: Cannot set parent, new parent is in a different thread
There are few articles on internet how to make multithreaded applications in Qt. Best explanation can be found here:
http://blog.debao.me/2013/08/how-to-use-qthread-in-the-right-way-part-1/
You could read also other articles:
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong
http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
Well, I got a solution for my problem. Please tell me, am I complicating the solution.
I am using signal and slot. The thread will emit the signal and the slot of other class will emit the callback to the Qtwebkit - the javascript function. IS it right?
Because, I have suggestion using event loop - exec().
#include <QtGui/QApplication>
#include <QApplication>
#include <QDebug>
#include <QWebFrame>
#include <QWebPage>
#include <QWebView>
#include <QThread>
/** for reading my driver **/
#include <unistd.h>
#include <fcntl.h>
class DemoThread;
class MyJavaScriptOperations : public QObject
{
Q_OBJECT
public:
QWebView *view;
DemoThread *m_pDemoThread;
MyJavaScriptOperations();
void firecb();
bool slot_installed;
signals:
void alert_script_signal();
public slots:
void JsAdded();
void alertReceived();
void loadFinished(bool);
private:
};
class DemoThread : public QThread
{
Q_OBJECT
private:
MyJavaScriptOperations *m_pJavascriptOp;
public:
DemoThread( MyJavaScriptOperations *pJavascriptOp);
protected:
void run();
signals:
void alertSendSignal();
};
DemoThread::DemoThread(MyJavaScriptOperations *pJavascriptOp):m_pJavascriptOp(pJavascriptOp)
{
connect(this, SIGNAL(alertSendSignal()), m_pJavascriptOp, SLOT(alertReceived()));
}
void DemoThread:: run()
{
int filedesc = open("/dev/pSeudoDrv", O_RDONLY);
if(filedesc < 0)
{
qDebug()<<"Couldn't open Driver.";
}
unsigned char buff;
while(1)
{
if( 1 != read(filedesc,&buff, 1))
{
qDebug()<<"Read Invalid Data";
}
qDebug()<<"The code received is "<< buff;
/** In my laptop, the 166 means the character 'l' **/
if ( (m_pJavascriptOp->slot_installed == true) && (buff == 166))
{
emit alertSendSignal();
}
qDebug()<<"Running Thread.";
}
}
void MyJavaScriptOperations::JsAdded()
{
qDebug()<<__PRETTY_FUNCTION__;
view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", this);
}
void MyJavaScriptOperations::loadFinished(bool oper)
{
qDebug()<<__PRETTY_FUNCTION__<< oper;
slot_installed = true;
}
void MyJavaScriptOperations::alertReceived()
{
qDebug()<<"Sending Firecallback now";
firecb();
}
void MyJavaScriptOperations::firecb()
{
qDebug()<<__PRETTY_FUNCTION__;
view->page()->mainFrame()->evaluateJavaScript("JavaScript_function()");
}
MyJavaScriptOperations::MyJavaScriptOperations()
{
qDebug()<<__PRETTY_FUNCTION__;
view = new QWebView();
view->resize(400, 500);
connect(view->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(JsAdded()));
connect(view, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
view->load(QUrl("./index.html"));
view->show();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyJavaScriptOperations *jvs = new MyJavaScriptOperations;
DemoThread *thread = new DemoThread(jvs);
thread->start();
return a.exec();
}
#include "main.moc"