I'm working on car sharing project. So, I've done login and registration, after login the main menu is opening. In main menu I need to output a balance of an account. I do like this:
mainwindow.h
#include <QMainWindow>
#include <QMessageBox>
#include <string>
#include <QDebug>
#include "mainmenu.h"
using namespace std;
class RegData;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
RegData& givedata(); // the object of class from which I will get balance and output it in main menu
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_button_reg_clicked();
void on_button_log_clicked();
private:
Ui::MainWindow *ui;
Mainmenu *second; // the error is in this line
};
class RegData
{
private:
QString login;
QString email;
QString password;
int balance;
public:
RegData(QString log = "", QString mail = "", QString pass = "", int bal=0) : login(log), email(mail), password(pass), balance(bal)
{
}
void output()
{
qDebug() << login<<email<<password<<balance;
}
QString getLogin()
{
return login;
}
QString getEmail()
{
return email;
}
QString getPassword()
{
return password;
}
int getBalance()
{
return balance;
}
void setLogin(QString log)
{
login = log;
}
void setEmail(QString mail)
{
email = mail;
}
void setPassword(QString pass)
{
password = pass;
}
void setBalance(int balanc)
{
balance = balanc;
}
};
Ok, how I did registration:
Receiving data from file into QVector data;
Receiving data from login/pass lines etc.
If login hasn't registered yet, put the data into file
So, there are a part of code in login system. The part checks is account registered, if it is, do something. In my case I change 'givedata()' values
for(QVector<RegData>::iterator it = data.begin(); it<data.end(); it++)
{
if(loginline == it->getLogin() && passwordline == it->getPassword() || loginline == it->getEmail() && passwordline == it->getPassword())
{
islog = true;
givedata().setLogin(loginline);
givedata().setEmail(it->getEmail());
givedata().setPassword(passwordline);
givedata().setBalance(it->getBalance());
break;
}
else
{
islog = false;
}
}
but I have an error
C:\Users\david\Documents\Carsharring_files\mainwindow.h:33: ошибка: 'Mainmenu' does not name a type
Mainmenu *second;
^
What is the line for? This is for main menu window object
I need to do some things with 'givedata()' in another window, there is why I do it
mainmenu.h is included
#ifndef MAINMENU_H
#define MAINMENU_H
#include <QDialog>
#include <QMessageBox>
#include "addmoney.h"
#include "mainwindow.h"
namespace Ui {
class Mainmenu;
}
class Mainmenu : public QDialog
{
Q_OBJECT
public:
explicit Mainmenu(QWidget *parent = 0);
~Mainmenu();
private slots:
void on_plus_clicked();
private:
Ui::Mainmenu *ui;
};
#endif // MAINMENU_H
I changed nothing in mainmenu.h, but includes
You have a cyclic dependency of header files.
mainmenu,h includes mainwindow.h
mainwindow.h includes mainmenu.h
That's trouble (and note that couldn't be determined without seeing both header files).
Related
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 months ago.
I am working on a project that utilizes a whole suite of custom widget that my company uses.
I am trying to subclass the QLineEdit QWidget so that I can override the default arrow key behavior. It should just behave like a regular QLineEdit.
I then want to use this custom QLineEdit (that I named DataLineEdit), in place of the standard QLineEdits that I dynamically created in another Widget, DataWidget.
I have followed tutorial after tutorial on subclassing, but cannot avoid the error:
undefined reference to "DataLineEdit::DataLineEdit(QWidget*)
My code is below.
datalineedit.h
#ifndef DATALINEEDIT_H
#define DATALINEEDIT_H
#include <QLineEdit>
#include <QWidget>
class DataLineEdit: public QLineEdit
{
Q_OBJECT
public:
explicit DataLineEdit(QWidget *parent = 0);
~DataLineEdit();
protected:
void keyPressEvent(QKeyEvent* event);
signals:
void leftRightOverrideKeyPress(int state);
private:
};
#endif // CUSTOMLINEEDIT_H
datalineedit.cpp
#include "datalineedit.h"
#include<QKeyEvent>
DataLineEdit::DataLineEdit(QWidget*parent) : QLineEdit(parent)
{
}
DataLineEdit::~DataLineEdit()
{
}
void DataLineEdit::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Left && this->cursorPosition() == 0)
{
emit leftRightOverrideKeyPress(0);
}
else if(event->key() == Qt::Key_Right && this->cursorPosition() == 2)
{
emit leftRightOverrideKeyPress(1);
}
else
{
QLineEdit::keyPressEvent(event);
}
}
datawidget.h
#define DATAWIDGET_H
#include <QFile>
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#include <QLineEdit>
#include <QObject>
#include <QtCore>
#include <QtGui>
#include <QKeyEvent>
#include <QMainWindow>
#include "datalineedit.h"
extern int focusRow;
extern int focusCol;
extern int numRows;
extern int numBottomRowCols;
extern QLineEdit *focusedLineEdit;
namespace Ui{
class DataWidget;
}
class QLineEdit;
class QLabel;
class DataWidget : public QWidget
{
Q_OBJECT
public:
explicit DataWidget(QWidget *parent = 0);
~DataWidget();
QString data;
protected:
bool eventFilter(QObject *object, QEvent *event);
public slots:
void focusChanged(QWidget *old, QWidget *now);
void arrowKeyNavigation(int state);
void on_applyChangePushButton_clicked();
void setData(QString text);
QString getData();
private slots:
void updateDataGridVisibility();
void on_payloadLineEdit_textChanged(const QString &arg1);
void on_savePushButton_clicked();
void on_openPushButton_clicked();
void on_presetComboBox_currentIndexChanged(int index);
private:
Ui::DataWidget *ui;
QString currentFile = "";
};
#endif // DATAWIDGET_H
datawidget.cpp
#include "datawidget.h"
#include "datawidget.h"
#include "datalineedit.h"
#include <QGridLayout>
#include <QLineEdit>
#include <QGroupBox>
#include <QKeyEvent>
#include <QIntValidator>
int focusRow;
int focusCol;
int numRows;
int numBottomRowCols;
QLineEdit *focusedLineEdit;
enum key_directions
{
arrowLeft = 0,
arrowRight = 1,
arrowUp = 2,
arrowDown = 3
};
enum presets
{
preset1 = 0,
preset2 = 1,
preset3 = 2,
preset4 = 3,
preset5 = 4,
clean = 5,
zeroes = 6
};
DataWidget::DataWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::DataWidget)
{
ui->setupUi(this);
this->installEventFilter(this);
connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(focusChanged(QWidget*,QWidget*)));
//payloadLineEdit
ui->payloadLineEdit->setValidator(new QIntValidator(0,64, this));
ui->payloadLineEdit->setFixedSize(20,20);
ui->payloadLineEdit->setTextMargins(0,0,0,0);
//dataGridLayout
ui->dataGridLayout->setAlignment(Qt::AlignLeft);
ui->dataGridLayout->setAlignment(Qt::AlignTop);
for(int i=0; i<4; i++)
{
for(int j=0; j<16; j++)
{
DataLineEdit *lineEdit = new DataLineEdit();
lineEdit->setText("00");//set data default
lineEdit->setInputMask("Hh");//limit to hex values
lineEdit->setFixedSize(20,20);
lineEdit->setTextMargins(0,0,0,0);
lineEdit->setAlignment(Qt::AlignCenter);
lineEdit->setAlignment(Qt::AlignCenter);
connect(lineEdit, SIGNAL(leftRightOverrideKeyPress(int)), this, SLOT(arrowKeyNavigation(int)));
ui->dataGridLayout->addWidget(lineEdit, i, j);
}
}
updateDataGridVisibility();
}
DataWidget::~DataWidget()
{
delete ui;
}
void DataWidget::arrowKeyNavigation(int state)
{
//does something
}
You could edit the class in the following form:
class DataLineEdit: public QLineEdit
{
Q_OBJECT
public:
explicit DataLineEdit(QWidget* parent = 0);
...
and
DataLineEdit::DataLineEdit(QWidget* parent) : QLineEdit(parent)
{
}
Thank you for all the help, it was definitely a linker issue but since I am working within a much larger project, I didn't want to mess with imports or .pro files too much. DataLineEdit is specific to DataWidget, so I simply moved the entire datalineedit.h file into the datawidget.h file at the bottom, and the same for the .cpp files. This avoids any linking all together and keeps things tidier based on the project's file hierarchy.
So, I am learning my way around Q_PROPERTY, QMetaObject and QMetaProperty.
I have built a working GUI, but whenever I run the script, I get an error
Can anyone tell me what I did wrong/am doing wrong?
The QDout() function, as mentioned, is only there to display something if I successfully connected the 'Print' Button with the QDout() function.
Below I have my files that associate with the Qt Project I am working on.
This is nothing serious, only for me to learn how to do it.
qt.core.qobject.connect: QObject::connect: No such slot FileInput::writeToFile()
My Header Files:
fileinput.h
#ifndef FILEINPUT_H
#define FILEINPUT_H
#include <QWidget>
#include <QPushButton>
#include "person.h"
class FileInput : public QWidget
{
Q_OBJECT
public:
FileInput(QWidget *parent = nullptr);
void set_GUI();
public slots:
void writeToFile(QObject *obj);
void QDout(); //just a test function to test my 'connect' part
private:
QPushButton *xx;
QPushButton *pp;
};
#endif // FILEINPUT_H
person.h
#ifndef PERSON_H
#define PERSON_H
#include <QObject>
#include <QDate>
class Person : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName WRITE setName)
Q_PROPERTY(QDate birth READ getBirth WRITE setBirth)
public:
Person();
Person(QString n, QDate d);
QString getName() const;
QDate getBirth() const;
void setName(QString n);
void setBirth(QDate d);
private:
QString name;
QDate birthDate;
};
class Product : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName WRITE setName)
Q_PROPERTY(double price READ getPrice WRITE setPrice)
public:
Product();
Product(QString n, double d);
QString getName() const;
double getPrice() const;
void setName(QString n);
void setPrice(double d);
private:
QString name;
double price;
};
#endif // PERSON_H
And then i have 3 .cpp files
filminput.cpp
#include "fileinput.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QMetaObject>
#include <QMetaProperty>
#include <QFile>
#include <QTextStream>
FileInput::FileInput(QWidget *parent)
: QWidget(parent)
{
}
void FileInput::set_GUI()
{
QWidget *w = new QWidget;
w->resize(250,250);
w->setWindowTitle("Q Meta Nonsence");
Product lem = Product();
lem.setName("PHIL");
lem.setPrice(16.45);
xx = new QPushButton("Exit");
pp = new QPushButton("Print");
QVBoxLayout *ll = new QVBoxLayout;
ll->addWidget(xx);
ll->addWidget(pp);
ll->setSpacing(25);
w->setLayout(ll);
w->show();
connect(xx,SIGNAL(clicked()),w,SLOT(close()));
connect(pp,SIGNAL(clicked()),this,SLOT(writeToFile(lem)));
}
void FileInput::QDout() //just prints 'success' when pressing the 'print' button
{
qDebug() << "success";
}
//this next function is supposed to write to the data.txt file
void FileInput::writeToFile(QObject *obj)
{
QFile file("C:/Users/marti/Documents/Qt/QM/data.txt");
if(!file.open(QFile::WriteOnly|QFile::Text|QFile::Append))
{
qDebug() << "Already open or there is another issue";
file.close();
}
QTextStream toFile(&file);
const QMetaObject *mo = obj->metaObject();
for(int i=mo->propertyOffset(); i<mo->propertyCount(); i++)
{
const QMetaProperty prop = mo->property(i);
QString name = prop.name();
QVariant value = prop.read(obj);
QString valStr = value.toString();
toFile << name << ": " << valStr << "\n";
}
file.close();
}
person.cpp
#include "person.h"
Person::Person()
{
name = QString();
birthDate = QDate();
}
Person::Person(QString n, QDate d)
{
name = n;
birthDate = d;
}
QString Person::getName() const
{
return name;
}
QDate Person::getBirth() const
{
return birthDate;
}
void Person::setName(QString n)
{
name = n;
}
void Person::setBirth(QDate d)
{
birthDate = d;
}
Product::Product()
{
name = QString();
price = 0.0;
}
Product::Product(QString n, double d)
{
name = n;
price = d;
}
QString Product::getName() const
{
return name;
}
double Product::getPrice() const
{
return price;
}
void Product::setName(QString n)
{
name = n;
}
void Product::setPrice(double d)
{
price = d;
}
main.cpp
#include "fileinput.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FileInput w;
w.set_GUI();
return a.exec();
}
You're using the older connect syntax which masks the problem that you're connecting a signal with no parameters to a slot that wants a parameter. To fix it use the new syntax and use a lambda to provide the extra parameter.
connect(pp, &QPushButton::clicked, this, [=](){ writeToFile(lem); });
I've been having this problem for few weeks, still didn't found a solution anywhere. I did everything I could to find the problem, everything looks good but for some reason it doesn't work.
I tested the connection, between the loginFailed() signal, and handleLoginFailed() slot, it returned True, printed the object info, it shows the connections. Tried different Qt::connectionTypes, nothing works.
The two objects are defined bellow.
LoginService.h
#ifndef LOGINSERVICE_H
#define LOGINSERVICE_H
#include <QObject>
#include <QVariant>
#include "libs/qubeapi/QubeAPI.h"
#include "libs/qubeapi/LoginCommand.h"
#include "libs/qubeapi/APIBridge.h"
#include "libs/mge-users/User.h"
#include "libs/mge-users/permissionfactory.h"
#include "Utils/serverstate.h"
#include "Utils/singleton.h"
#include "Utils/baseservice.h"
class LoginService : public QObject
{
Q_OBJECT
QubeAPI* api;
APIBridge* bridge;
LoginCommand* loginCmd;
QString m_userType;
QString m_firstName;
QString m_lastName;
User *m_user;
public:
explicit LoginService(QObject *parent = nullptr);
Q_PROPERTY(QString userType READ userType WRITE setUserType NOTIFY userTypeChanged)
Q_PROPERTY(QString firstName READ firstName WRITE setFirstName NOTIFY firstNameChanged)
Q_PROPERTY(QString lastName READ lastName WRITE setLastName NOTIFY lastNameChanged)
Q_PROPERTY(User* user READ user WRITE setUser NOTIFY userChanged)
const QString &userType() const;
void setUserType(const QString &newUserType);
const QString &firstName() const;
void setFirstName(const QString &newFirstName);
const QString &lastName() const;
void setLastName(const QString &newLastName);
User *user() const;
void setUser(User *newUser);
signals:
void success(QString token);
void loginFailed();
void userTypeChanged();
void firstNameChanged();
void lastNameChanged();
void staffLogout();
void userTypeRecived();
void userChanged();
public slots:
void requestLogin(QString userName, QString password);
void loginResponse(QString jsonData);
void doClose();
void prepareGetUserType();
void loadUserType(QString jsonData);
};
#endif // LOGINCONTROLLER_H
The function that emits the signal:
void LoginService::loginResponse(QString jsonData)
{
QSignalSpy spy(this,SIGNAL(loginFailed()));
if(jsonData == "") {
emit Singleton<ServerState>::GetInstance().offlineServer();
return;
}
QJsonDocument doc = QJsonDocument::fromJson(jsonData.toUtf8());
QString token = doc["data"]["tokenAuth"]["token"].toString();
if(!token.isEmpty()) {
UserSession::getInstance()->setAuthToken(token);
emit success(token);
prepareGetUserType();
} else {
qDebug() << "Urmeaza eroare";
QString errorMsg = doc["errors"][0]["message"].toString();
emit loginFailed();
qDebug() << spy.count();
}
}
The controller class that has the slot:
#ifndef LOGINCONTROLLER_H
#define LOGINCONTROLLER_H
#include <Utils/basecontroller.h>
#include <Utils/enginefactory.h>
#include <Utils/singleton.h>
#include <QQuickWindow>
#include <QQuickItem>
#include <QThread>
#include <QProperty>
#include <QQmlProperty>
#include "loginservice.h"
#include "draggableviewhelper.h"
#include <QMouseEvent>
class LoginController : public BaseController
{
Q_OBJECT
private:
QQuickWindow* window;
QQuickItem* login;
QQuickItem* userTextField;
QQuickItem* passwordTextField;
DraggableViewHelper* draggableViewHelper;
QQuickItem* mouseArea;
LoginService* service;
QPointF lastMousePosition;
public:
explicit LoginController(QObject *parent = nullptr);
// BaseController interface
void initialize();
// void setService(BaseService* s);
void setService(LoginService* s);
void setLastMousePosition(QPointF lastMousePosition);
public slots:
void handleLoginResponseSuccess(QString loginResponse);
void handleLoginResponseFailed();
void handlePositionChanged();
void handleLogout();
};
#endif // LOGINCONTROLLER_H
The initializer methods
void LoginController::initialize()
{
this->engine = Singleton<EngineFactory*>::GetInstance()->createEngine("qrc:/qml/LoginWindow.qml");
this->window = qobject_cast<QQuickWindow*>(this->engine->rootObjects().first());
// Create a draggable view helper, use window as input
// Get the view from the engine
this->draggableViewHelper = new DraggableViewHelper(this->window);
this->window->setFlags(Qt::Window | Qt::FramelessWindowHint);
this->login = window->findChild<QQuickItem*>("login");
this->userTextField = QQmlProperty::read(this->login,"user").value<QQuickItem*>();
this->passwordTextField = QQmlProperty::read(this->login,"password").value<QQuickItem*>();
// Set the mouseArea with the mainMouseArea item of the window
this->mouseArea = window->findChild<QQuickItem*>("mainMouseArea");
// Connect onClicked from mouse area, to handleMove of this
QObject::connect(this->mouseArea,SIGNAL(positionMoved()),this,SLOT(handlePositionChanged()));
}
void LoginController::setService(LoginService *s)
{
this->service = s;//new LoginService;
connect(this->service,SIGNAL(loginFailed()),this,SLOT(handleLoginResponseFailed()));
connect(this->service,SIGNAL(success(QString)),this,SLOT(handleLoginResponseSuccess(QString)));
connect(login,SIGNAL(doLogin(QString,QString)),this->service,SLOT(requestLogin(QString,QString)));
this->dumpObjectInfo();
this->service->dumpObjectInfo();
}
The slot
void LoginController::handleLoginResponseFailed()
{
qDebug() << "Failed";
QQmlProperty::write(this->userTextField,"state",QVariant::fromValue(QString{"default-error"}));
QQmlProperty::write(this->passwordTextField,"state",QVariant::fromValue(QString{"password-error"}));
}
This is the main.cpp file, where the objects are created
QApplication app1(argc, argv);
LoginController* loginCtrl = new LoginController;
LoginService* loginService = new LoginService;
QObject::connect(loginService, &LoginService::userTypeRecived,[&](){
qDebug() << "Failed to login";
});
qDebug() << loginService;
loginCtrl->initialize();
loginCtrl->setService(loginService);
//This will trigger the signal
// loginService->loginResponse("{\"errors\":[{\"message\":\"Please enter valid credentials\",\"locations\":[{\"line\":1,\"column\":12}],\"path\":[\"tokenAuth\"]}],\"data\":{\"tokenAuth\":null}}");
return app1.exec();
Data Appending Problem While sending the data through Namedpipe using QT
localserver.h
#ifndef LOCALSERVER_H
#define LOCALSERVER_H
#include "QLocalSocket"
#include "QLocalServer"
class QLocalSocket;
class LocalServer : public QLocalServer
{
Q_OBJECT
public:
explicit LocalServer(QObject *parent = 0);
void send(QString &msj);
QLocalSocket *mSocket;
private slots:
void receive();
private:
};
#endif // LOCALSERVER_H
localserver.cpp
#include "localserver.h"
#include "QLocalSocket"
#include "QTextStream"
#include "QMessageBox"
LocalServer::LocalServer(QObject *parent) : QLocalServer(parent)
{
mSocket = nullptr;
connect(this,&LocalServer::newConnection,[&](){
mSocket = nextPendingConnection();
});
qDebug()<<"Hello World";
}
void LocalServer::send(QString &msj)
{
qDebug()<<"Sending Data";
if(mSocket)
{
QTextStream T(mSocket);
T<<msj.toStdString().c_str();
mSocket->flush();
}
}
void LocalServer::receive()
{
qDebug()<<"Im here";
QDataStream in(mSocket);
in.setVersion(QDataStream::Qt_5_2);
mSocket->readAll();
qDebug()<<"Data Received";
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "QProcess"
#include "QTimer"
#include "QLocalSocket"
#include "localserver.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void Connection();
private slots:
void on_start_clicked();
void on_send_clicked();
void on_quit_clicked();
void detect_connection();
void connect_terminate();
void connected();
void send_data();
void receive_data();
QString RandomData();
void on_pbtn_Stop_clicked();
private:
Ui::Widget *ui;
LocalServer *mLocalServer;
QTimer *timer;
QLocalSocket *mSocket;
bool first;
QString data_received;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "QProcess"
#include "QDebug"
#include "localserver.h"
#include "QMessageBox"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
Connection();
first = true;
}
void Widget::Connection()
{
mLocalServer = new LocalServer(this);
mLocalServer->listen("Server1");
connect(mLocalServer,SIGNAL(newConnection()),this,SLOT(detect_connection()));
first = true;
timer = new QTimer(this);
timer->setInterval(8);
connect(timer,SIGNAL(timeout()),this,SLOT(send_data()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_start_clicked()
{
timer->start();
}
void Widget::on_send_clicked()
{
timer->stop();
}
void Widget::on_quit_clicked()
{
timer->stop();
this->close();
}
void Widget::detect_connection()
{
qDebug()<<"Write Pipe Established";
mSocket = new QLocalSocket(this);
mSocket->connectToServer("Server2");
connect(mSocket,SIGNAL(disconnected()),this,SLOT(connect_terminate()));
connect(mSocket,SIGNAL(connected()),this,SLOT(connected()));
qDebug()<<"Connection Established, Ready to Read";
connect(mSocket,&QLocalSocket::readyRead, [&]() {
QTextStream T(mSocket);
ui->receivedText->addItem(T.readAll());
});
}
void Widget::connect_terminate()
{
qDebug()<<"Read Server Connection Terminated";
QString string = "Stop_Session";
mLocalServer->send(string);
ui->sentText->addItem(string);
}
void Widget::connected()
{
qDebug()<<"Socket Connected to Server";
QString s=" Connection Done ";
mLocalServer->send(s);
}
void Widget::send_data()
{
QString string = RandomData();
mLocalServer->send(string);
ui->sentText->addItem(string);
}
QString Widget::RandomData()
{
srand(time(NULL));
int random_number = rand()%(1920-0 + 1) + 0; // rand() return a number between 0 and RAND_MAX
int random_number1 = rand()%(1080-0 + 1) + 0;
int random_number2 = rand()%(10-0 + 1) + 0;
QString s="Contour,"+QString::number(random_number)+","+QString::number(random_number1)+","+QString::number(random_number2);
// Basically this data in "s" gives the actual contours detected data but am using a random generator to test the Local Server and Socket .
return s;
}
void Widget::receive_data()
{
QString string;
QTextStream T(mSocket);
T.readLine();
if(T.readAll()=="Stop")
{
qDebug()<<"Socket About to Close";
QString string = "Stop";
mLocalServer->send(string);
}
else
{
qDebug()<<"Program can continue"<<T.readAll();
}
}
void Widget::on_pbtn_Stop_clicked()
{
timer->stop();
}
At Receiver SIde Program
Receiver.cpp
void Receiver ::Declaration_Of_Server2()
{
// Declaration Of LocalServer i.e Server2
ServerIS = new LocalServer(this);
ServerIS->listen("Server2");
// Connect To a LocalSocket TO The Above LocalServer i.e Server_IS with Server_VS
connect(ServerIS,SIGNAL(newConnection()),this,SLOT(DetectConnection_WithServer1()));
}
void CoFire_MainPage::DetectConnection_WithServer1()
{
// Declaration of LocalSocket i.e Server_VS
SocketIS = new QLocalSocket(this);
SocketIS->connectToServer("Server1");
connect(SocketIS,SIGNAL(readyRead()),this,SLOT(Receiving_VS_Data()));
}
void CoFire_MainPage::Receiving_VS_Data()
{
// Receiving Vs Data From Socket "Socket_IS"
QTextStream msg(SocketIS);
QString str = msg.readLine();
qDebug()<<" VS DATA : "<<str;
}
By this am trying to send data ( example : Contour,1000,800,1 ) from one program to other program
with a speed of 1 data / 8msec but in real scenario it might even go to 1msec data transfer.
but by this at receving end every now and then incomming data is been appended
(example: Contour,1000,800,1Contour,200,400,1Contour,500,650,1 etc... ).
But actually expentected data is
1st
Contour,1000,800,1
next
Contour,200,400,1
next
Contour,500,650,1
etc....
This way the data is getting appeneded before i capture and process the data at receiver .
By this am loosing the precious information .
how do i solve this issue .
readLine() waits for an end-of-line ("\n" or "\r\n"), but in your case you do not send it, you must change to the following:
QString Widget::RandomData(){
srand(time(NULL));
int random_number = rand()%(1920-0 + 1) + 0; // rand() return a number between 0 and RAND_MAX
int random_number1 = rand()%(1080-0 + 1) + 0;
int random_number2 = rand()%(10-0 + 1) + 0;
return QString("Contour,%1,%2,%3\n")
.arg(random_number)
.arg(random_number1)
.arg(random_number2);
}
On the other hand it is not necessary to use the reference of the QString, and also it is unnecessary to use toStdString().c_str().
void LocalServer::send(const QString &msj)
{
qDebug()<<"Sending Data";
if(mSocket)
{
QTextStream T(mSocket);
T << msj;
mSocket->flush();
}
}
I'm learning about using QFtp.
I'd like to connect to a remote ftp server and list its content.
This what I wrote so far:
// libftp.cpp
#include "libftp.h"
libFTP::libFTP(QObject *parent) :
QObject(parent)
{
}
void libFTP::open(QString host)
{
connect(&ftp,SIGNAL(commandFinished(int,bool)),this,SLOT(status(int,bool)));
connect(&ftp,SIGNAL(listInfo(QUrlInfo)),this,SLOT(dir(QUrlInfo)));
ftp.setTransferMode(QFtp::Active);
ftp.connectToHost(host);
ftp.list();
ftp.cd("USER");
}
void libFTP::disconnect()
{
ftp.abort();
ftp.deleteLater();
}
void libFTP::download(QString filename)
{
ftp.get(filename);
}
void libFTP::upload(QString path,QString filename)
{
QString fullpath=path+filename;
try
{
QFile *f= new QFile(fullpath);
if(f->exists())
{
qDebug()<<"File Trovato";
ftp.mkdir("test");
//ftp.put(f,filename);
f->close();
f->deleteLater();
}
}
catch(std::exception x)
{
qDebug()<<"Errore " << x.what();
}
}
void libFTP::status(int id,bool error)
{
if(error)
{
qDebug()<<"Errore";
}
else
qDebug()<<"Status ID " << QString(id);
}
void libFTP::dir(QUrlInfo directory)
{
qDebug()<<directory.name();
}
// libftp.h
#ifndef LIBFTP_H
#define LIBFTP_H
#include <QObject>
#include <QtCore>
#include <QFtp>
#include <QUrlInfo>
class libFTP : public QObject
{
Q_OBJECT
public:
explicit libFTP(QObject *parent = 0);
void open(QString host);
void disconnect();
void download(QString filename);
void upload(QString path,QString filename);
private:
QFtp ftp;
signals:
public slots:
void status(int id,bool error);
void dir(QUrlInfo directory);
};
#endif // LIBFTP_H
And I call it from main:
#include <libftp.h>
int main()
{
libFTP *ftp = new libFTP();
ftp->open("10.20.xx.xxx");
ftp->deleteLater();
}
The server I'm connecting to accepts anonymous login.
When I try to debug this code, I notice that no slots are called and I don't see any FTP packets in my wireshark capture. In every example code I saw that's the way QFtp is used, what am I missing?
Found the issue, that wasn't immediate for a qt newbie, it didn't show any info.
I had to run QFtp in a QApplication. I think this is needed by the event loop
calling QApplication in main() solved it.