Global variable pass the null value - c++

I'm try to pass string value from mainwindow.cpp to userdetails.cpp. I had been used global variable. When the program run it does not pass the variable value to the userdetails.cpp. When I use qDebug( globelusername.toLatin1() ) it does not show any value. What is the error in this code? globelusername mean, the global variable.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "register.h"
#include "userdetails.h"
extern QString globelusername;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
QString globelusername;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui ->loginusername->setPlaceholderText("Username");
ui ->loginpassword->setPlaceholderText("Password");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_2_clicked()
{
//database connection
...........
QString username = ui ->loginusername ->text();
QString password = ui ->loginpassword ->text();
if(db.open()){
//query create
// QMessageBox::information(this, "Sucessfull ","Sucessfully Connect the Database");
QSqlQuery query(QSqlDatabase::database("MyConnect"));
query.prepare(QString("SELECT * FROM user_reg_elec WHERE username = :username AND password = :password"));
query.bindValue(":username", username);
query.bindValue(":password", password);
QString globelusername = username; //globlevariable
}
userdetails.cpp
#include "userdetails.h"
#include "ui_userdetails.h"
#include <QSqlError>
#include "mainwindow.h"
#include <iostream>
Userdetails::Userdetails(QWidget *parent) :
QDialog(parent),
ui(new Ui::Userdetails)
{
ui->setupUi(this);
}
Userdetails::~Userdetails()
{
}
void Userdetails::on_pushButton_4_clicked()
{
{
// database connection
...........
qDebug(globelusername.toLatin1() );

You are not setting globelusername. instead, you are creating a local variable with the following line:
QString globelusername = username; //globlevariable
remove the variable type before setting the value:
globelusername = username; //globlevariable

Related

QTserialport connection

Im trying to use QTserialport to connect to a port via uart
I get QIODevice::read (QSerialPort): device not open this but device is connect as i tested with other applications and with Qserialportinfo I was able to detect the serial port but not connect to it and read from it which part am i doing wrong ??
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m.setBaudRate(QSerialPort::Baud115200);
m.setDataBits(QSerialPort::Data8);
m.setPortName("COM2");
m.setFlowControl(QSerialPort::NoFlowControl);
m.setParity(QSerialPort::NoParity);
m.setStopBits(QSerialPort::OneStop);
m.setReadBufferSize(1000);
qDebug()<<m.portName();
while(1){
qDebug()<<m.readAll();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QSerialPort>
#include <QMainWindow>
#include <QSerialPortInfo>
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;
QSerialPort m;
QSerialPortInfo info;
};
#endif // MAINWINDOW_H
ps. I tried to use //./ & \.\ & ////.// & \\.\ before the port but it didnt worked
I believe you have to open the port before reading from it. Try something like this:
if (m.open(QIODevice::ReadOnly)){
while (1){
if (m.waitForReadyRead(1000)){
qDebug() << m.readAll();
}
}
}
after adding m.open() worked perfectly
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m.setBaudRate(QSerialPort::Baud115200);
m.setDataBits(QSerialPort::Data8);
m.setPortName("COM2");
m.setFlowControl(QSerialPort::NoFlowControl);
m.setParity(QSerialPort::NoParity);
m.setStopBits(QSerialPort::OneStop);
m.setReadBufferSize(1000);
m.open(QIODevice::ReadOnly); //after adding this worked perfectly
qDebug()<<m.portName();
while(1){
qDebug()<<m.readAll();
}
}
MainWindow::~MainWindow()
{
delete ui;
}

[C++][ QT ] is not meant to be copied. Pass it by move instead

I am a beginner in C++. And I don't understand this error. I just need you to explain me.
I try to show a .sqlite database in a QTableview. The problem come from:
model->setQuery(*qry);
I want to use a function called setQuery but in first argument, I set an object with *QSqlQuery type. And this error show up.
ERROR Pics
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlDatabase>
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;
QSqlDatabase DB;
QSqlQueryModel* model;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
DB = QSqlDatabase::addDatabase("QSQLITE");
DB.setDatabaseName("Prices.sqlite");
if (DB.open()) {
qDebug() << "Open";
model = new QSqlQueryModel();
QSqlQuery* qry = new QSqlQuery(DB);
qry->prepare("SELECT * FROM Prices");
qry->exec();
model->setQuery(*qry);
ui->tableView->setModel(model);
qDebug() << "Rows: " << model->rowCount();
DB.close();
}
else {
qDebug() << "Failed connection";
}
}
They want you to move the object behind qry into the function.
The shortest change would be to replace
model->setQuery(*qry);
with
model->setQuery(std::move(*qry));
delete qry;
You don't need to use new/delete in this case though. Just using automatic storage duration works:
QSqlQuery qry(DB);
qry.prepare("SELECT * FROM Prices");
qry.exec();
model->setQuery(std::move(qry));
Then you don't have to worry about forgetting to delete it.
Alternatively, since the QSqlQuery object is not used anywhere else, it might be best to chose the other overload for setQuery like this:
model = new QSqlQueryModel();
model->setQuery("SELECT * FROM Prices", DB);
ui->tableView->setModel(model);

How to send message from child widget to parent window in Qt?

How do I send a message from a child widget to a parent window in qt?
I tried sending a signal from the child widget to the parent window in qt. When I call the function test in subwidget.cpp, the signal is sent but the mainwindow slot does not execute. How can I send the message?
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStackedWidget>
#include <QPushButton>
#include <QProcess>
#include <QDebug>
#include <subwidget.h>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void check_adb_exists();
private:
Ui::MainWindow *ui;
QStackedWidget *stack;
QPushButton *start_btn;
SubWidget *f2;
private slots:
void StartApplication();
void ReceiveCustomMessage(const QString &msg);
};
#endif // MAINWINDOW_H
subwidget.h
#define SUBWIDGET_H
#include <QWidget>
namespace Ui {
class SubWidget;
}
class SubWidget : public QWidget
{
Q_OBJECT
public:
explicit SubWidget(QWidget *parent);
~SubWidget();
void test();
private:
Ui::SubWidget *ui;
signals:
void SendCustomMessage(const QString& msg);
};
#endif // SUBWIDGET_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
// #include <formcustomnew.h>
#include <subwidget.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
stack = MainWindow::findChild<QStackedWidget *>("stackedWidget");
start_btn = MainWindow::findChild<QPushButton *>("start_btn");
stack->setCurrentIndex(0);
connect(start_btn,SIGNAL(released()),this,SLOT(StartApplication()));
f2 = new SubWidget(this);
//connect(f2,SIGNAL(SendCustomMessage(QString)),this,SLOT(ReceiveCustomMessage(QString)));
//f2->test();
//auto f1 = new FormCustomNew(this);
//connect(f1,SIGNAL(sendMessageNewMessage(QString)),this,SLOT(receiveMessage(QString)));
//f1->test();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::StartApplication(){
//check_adb_exists();
f2->test();
}
void MainWindow::ReceiveCustomMessage(const QString &msg){
qDebug("Recieved message from child");
qDebug("Message: " + msg.toLatin1());
}
void MainWindow::check_adb_exists(){
QProcess *p = new QProcess();
connect(p,&QProcess::readyReadStandardOutput,[&](){
auto data = p->readAllStandardOutput();
qDebug("Stdout: " + data);
});
connect(p,&QProcess::readyReadStandardError,[&](){
auto data = p->readAllStandardError();
qDebug("Error: " + data);
if(data.toStdString().compare("File Not Found")){
qDebug("File Not Found is the error");
}
});
QStringList args;
args << "/c dir C:\\Users\\%USERNAME%\\AppData\\Local\\Android\\Sdk";
p->setArguments(args);
p->setProgram("C:\\Windows\\System32\\cmd.exe");
p->start();
}
subwidget.cpp
#include "subwidget.h"
#include "ui_subwidget.h"
SubWidget::SubWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::SubWidget)
{
ui->setupUi(this);
qDebug("parent: " + parent->objectName().toLatin1());
connect(this,SIGNAL(SendCustomMessage(QString)),parent,SLOT(ReceiveCustomMessage(QString)));
}
SubWidget::~SubWidget()
{
delete ui;
}
void SubWidget::test(){
emit SendCustomMessage("trial message");
}
void SubWidget::SendCustomMessage(const QString &msg){
qDebug("Sending Message: " + msg.toLatin1());
}
Signals must not be defined in Qt.
From the Qt wiki on Signal & Slots:
Signals are automatically generated by the moc and must not be implemented in the .cpp file
Remove your implementation and this should work. However you should not be binding the signal within subclass as that reduces encapsulation and reusability (parent must have a ReceiveCustomMessage(QString) slot). Instead bind it outside, as you have in your commented out code.

QT Cuncurrent With mail Client

Hi I already asked my question here and understand why it's not working, now I have modified source code by moving the Smptp object as class variable , but still not working.
What I need to implement is send mail from a thread I chose QtConcurrent::run() for doing this but the slot not getting called after sending button clicked.
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QSettings"
#include "QFuture"
#include "QtConcurrent/QtConcurrent"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->sendBtn, SIGNAL(clicked()),this, SLOT(test()));
connect(ui->exitBtn, SIGNAL(clicked()),this, SLOT(close()));
connect(ui->browseBtn, SIGNAL(clicked()), this, SLOT(browse()));
}
void MainWindow::browse()
{
files.clear();
QFileDialog dialog(this);
dialog.setDirectory(QDir::homePath());
dialog.setFileMode(QFileDialog::ExistingFiles);
if (dialog.exec())
files = dialog.selectedFiles();
QString fileListString;
foreach(QString file, files)
fileListString.append( "\"" + QFileInfo(file).fileName() + "\" " );
ui->file->setText( fileListString );
}
void MainWindow::test(){
QFuture<void> f4 = QtConcurrent::run(this,&MainWindow::sendMail); // this not work
//sendMail(); // this works
}
void MainWindow::sendMail()
{
smtp = new Smtp(ui->uname->text(), ui->paswd->text(), ui->server->text(), ui->port->text().toInt());
connect(smtp, SIGNAL(status(QString)), this, SLOT(mailSent(QString)));
if( !files.isEmpty() )
smtp->sendMail(ui->uname->text(), ui->rcpt->text() , ui->subject->text(),ui->msg->toPlainText(), files );
else
smtp->sendMail(ui->uname->text(), ui->rcpt->text() , ui->subject->text(),ui->msg->toPlainText());
}
void MainWindow::mailSent(QString status)
{
if(status == "Message sent")
QMessageBox::warning( 0, tr( "Qt Simple SMTP client" ), tr( "Message sent!\n\n" ) );
delete smtp;
}
MainWindow::~MainWindow()
{
delete ui;
}
mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "smtp.h"
#include <QtWidgets/QMessageBox>
#include <QFileDialog>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void sendMail();
void mailSent(QString);
void browse();
void test();
private:
Ui::MainWindow *ui;
QStringList files;
Smtp* smtp ;
};
#endif // MAINWINDOW_H
If I call sendMail(); directly it works, but using QFuture<void> f4 = QtConcurrent::run(this,&MainWindow::sendMail); it's not working, not working means the slot not get called, how can I resolve this issue?
I am referring the code from here https://github.com/xcoder123/SimpleSmtp_SSL_QT5/tree/master/smtp_attachements
Thanks
Haris
A solution as I already mentioned here is to use a QThread instead of QtConcurrent::run.
There is a detailed example contained in the Qt documentation: http://doc.qt.io/qt-5/qthread.html#details
The following code adapts this example to your use case.
smtp is moved to the workerThread. The communication between the main thread and the workerThread is done using signals and slots.
Be aware that you are not allowed to call any GUI related functions (such as showing message boxes etc.) in Smtp anymore!
This has to be done in the main thread.
User name, password etc. should probably also be passed through the signal to Smtp::sendMail.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtWidgets/QMessageBox>
#include <QFileDialog>
#include <QThread>
namespace Ui {
class MainWindow;
}
class Smtp;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void sendMailButtonClicked();
void mailSent(QString);
void browse();
private:
Ui::MainWindow *ui;
QStringList files;
Smtp* smtp;
QThread workerThread;
signals:
void sendMail(const QString &from, const QString &to, const QString &subject, const QString &body, QStringList files);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "smtp.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->sendBtn, SIGNAL(clicked()),this, SLOT(sendMailButtonClicked()));
connect(ui->exitBtn, SIGNAL(clicked()),this, SLOT(close()));
connect(ui->browseBtn, SIGNAL(clicked()), this, SLOT(browse()));
smtp = new Smtp(ui->uname->text(), ui->paswd->text(), ui->server->text(), ui->port->text().toInt());
smtp->moveToThread(&workerThread);
connect(this, SIGNAL(sendMail(QString,QString,QString,QString,QStringList)), smtp, SLOT(sendMail(QString,QString,QString,QString,QStringList)));
connect(smtp, SIGNAL(status(QString)), this, SLOT(mailSent(QString)));
workerThread.start();
}
void MainWindow::browse()
{
files.clear();
QFileDialog dialog(this);
dialog.setDirectory(QDir::homePath());
dialog.setFileMode(QFileDialog::ExistingFiles);
if (dialog.exec())
files = dialog.selectedFiles();
QString fileListString;
foreach(QString file, files)
fileListString.append( "\"" + QFileInfo(file).fileName() + "\" " );
ui->file->setText( fileListString );
}
void MainWindow::mailSent(QString status)
{
if(status == "Message sent")
QMessageBox::warning( 0, tr( "Qt Simple SMTP client" ), tr( "Message sent!\n\n" ) );
}
MainWindow::~MainWindow()
{
workerThread.quit();
workerThread.wait();
delete ui;
}
void MainWindow::sendMailButtonClicked()
{
emit sendMail(ui->uname->text(), ui->rcpt->text() , ui->subject->text(),ui->msg->toPlainText(), files );
}
in smtp.h: set sendMail to be a slot:
public slots:
void sendMail( const QString &from, const QString &to,
const QString &subject, const QString &body,
QStringList files = QStringList());

Cannot get QString data from another header file

I have a login window where users input some text.
login.cpp:
#include "login.h"
#include "ui_login.h"
#include "mainwindow.h"
login::login(QWidget *parent) :
QDialog(parent),
ui(new Ui::login)
{
ui->setupUi(this);
this->setFixedSize(320,212);
connect(ui->_login, SIGNAL(clicked()), this, SLOT(rLogin()));
connect(ui->_close, SIGNAL(clicked()), this, SLOT(rClose()));
}
login::~login()
{
delete ui;
}
void login::rLogin()
{
prefix = ui->_prefix->text();
site = ui->_site->text();
dbname = ui->_database->text();
user = ui->_username->text();
QString pass = ui->_password->text();
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(site);
db.setDatabaseName(prefix + dbname);
db.setUserName(prefix + user);
db.setPassword(pass);
bool logged = db.open();
if (logged) {
rOpen();
} else {
int warning = QMessageBox::warning(this, tr("Hostel ERP Error"),
tr("Could not connect to database.\n"
"Please check your inputs."),
QMessageBox::Ok);
}
}
void login::rOpen()
{
mainwindow* openwindow = new mainwindow();
openwindow->show();
this->close();
}
void login::rClose()
{
this->close();
}
prefix, site, dbname, and user are defined as QString in login.h
login.h:
#ifndef LOGIN_H
#define LOGIN_H
#include <QDialog>
namespace Ui {
class login;
}
class login : public QDialog
{
Q_OBJECT
public:
explicit login(QWidget *parent = 0);
void rOpen();
QString prefix;
QString site;
QString dbname;
QString user;
~login();
I am trying to access prefix, site, dbname, and user from mainwindow.cpp
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QMessageBox>
#include <QPushButton>
#include <QAction>
#include <QMainWindow>
#include <QSqlRecord>
#include <login.h>
namespace Ui {
class mainwindow;
}
class mainwindow : public QMainWindow
{
Q_OBJECT
public:
explicit mainwindow(QWidget *parent = 0);
void rPopulate();
QPushButton *button;
login * log;
~mainwindow();
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "login.h"
#include "newbooking.h"
#include <qaction.h>
//somecode
login *log = new login;
QString table_schema = log->prefix + log->dbname;
however both log->prefix and log->dbname are empty. There is default text in ui->_prefix->text(); and ui->_database->text(); so they shouldn't be empty.
You are likely trying to access mainwindow::log i.e the log that is a member of mainwindow. You probably call rLogin on this function.
However you are getting empty values because you are creating a new object which has default values.
login *log = new login;
This line is part of the problem I assume. We wont know more before you show us how you call rLogin, but you want to check from the same object that you call it on.
Needed to declare QString as global var at the top of login.h in between #include "mainwindow.h" and login::login(QWidget *parent):, then in login.cpp define the QStrings.
eg. login.h
#include ...
extern QString site; //this
login::login(QWidget *parent) :
login.cpp
#include ...
QString example; //this
login::login(QWidget *parent) :
after that you can simply call them from whatever file you want. Silly me.