This happens when i enter the code to the slots of my buttons
when i debug the app normally ,all functions etc everything is ok.
but when i try use my code in UI something brokes down.
I'm making the Parking System for my uni classes ,
i got one parent class vehicle and 4 child classes which inherits by public.
here's the code from the UI source file :
#include "datain.h"
#include "ui_datain.h"
#include <QMessageBox>
#include <car.h>
#include <bike.h>
#include <motorbike.h>
#include <tir.h>
#include <vehicle.h>
#include <iostream>
using namespace std;
dataIn::dataIn(QWidget *parent) :
QDialog(parent),
ui(new Ui::dataIn)
{
ui->setupUi(this);
}
dataIn::~dataIn()
{
delete ui;
}
dataIn siema;
void dataIn::on_lineEdit_textEdited(const QString &arg1)
{
siema.rejestracja=arg1;
}
void dataIn::on_lineEdit_2_textEdited(const QString &arg1)
{
siema.marka=arg1;
}
void dataIn::on_car_clicked()
{
Vehicle *wsk;
string reje,mareczka;
reje=siema.rejestracja.toStdString();
mareczka=siema.marka.toStdString();
Car obj(reje,mareczka);
wsk=&obj;
wsk->add();
}
void dataIn::on_motorcycle_clicked()
{
Vehicle *wsk;
string reje,mareczka;
reje=siema.rejestracja.toStdString();
mareczka=siema.marka.toStdString();
Motorbike obj(reje,mareczka);
wsk=&obj;
wsk->add();
}
void dataIn::on_bike_clicked()
{
Vehicle *wsk;
string reje,mareczka;
reje=siema.rejestracja.toStdString();
mareczka=siema.marka.toStdString();
Bike obj(reje,mareczka);
wsk=&obj;
wsk->add();
}
void dataIn::on_tir_clicked()
{
Vehicle *wsk;
string reje,mareczka;
reje=siema.rejestracja.toStdString();
mareczka=siema.marka.toStdString();
Tir obj(reje,mareczka);
wsk=&obj;
wsk->add();
}
Here's the main:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
dataIn code:
#ifndef DATAIN_H
#define DATAIN_H
#include <QString>
#include <iostream>
#include <QDialog>
using namespace std;
namespace Ui {
class dataIn;
}
class dataIn : public QDialog
{
Q_OBJECT
QString rejestracja;
QString marka;
public:
explicit dataIn(QWidget *parent = 0);
~dataIn();
private slots:
void on_lineEdit_textEdited(const QString &arg1);
void on_lineEdit_2_textEdited(const QString &arg1);
void on_car_clicked();
void on_motorcycle_clicked();
void on_bike_clicked();
void on_tir_clicked();
private:
Ui::dataIn *ui;
};
#endif // DATAIN_H
You may not declare
dataIn siema;
and you should not refer to it - remove all siema.... references from your dataIn functions (replace siema. with nothing or with this->).
When you need your dialog for the first time, create it in (and as child of) MainWindow:
void MainWindow::whateverEvent() {
dataIn *siema = new dataIn(this);
siema->show();
}
If you need to reference it again or want do prevent it from being created twice, store the pointer in a member of your MainWindow.
Related
I'm writing QT deskop app and I have a small issue.
I want to open new tab with text that I put from a file.
I have two class one in mainwindow.h and second in form.h
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();
public slots:
void on_open_file_clicked();
void on_search_keyword_clicked();
void on_search_tag_clicked();
void on_tabWidget_tabCloseRequested(int index);
void show_tab(QString keywords);
QString return_text();
public:
Ui::MainWindow *ui;
private slots:
void on_actionOpen_file_triggered();
void on_actionShow_text_file_triggered();
QVector<QString>find_logs_keywords(QString keywords);
private:
QString text = "example text";
};
#endif // MAINWINDOW_H
form.h
#ifndef FORM_H
#define FORM_H
#include <QWidget>
namespace Ui {
class Form;
}
class Form : public QWidget
{
Q_OBJECT
public:
explicit Form(QWidget *parent = nullptr);
~Form();
public slots:
void on_pushButton_2_clicked();
void text_to_plain(QString& text);
private:
Ui::Form *ui;
};
#endif // FORM_H
mainwindow.cpp
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QDir>
#include <QVector>
#include <QStringList>
#include <iostream>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "search_keyword.h"
#include "search_tag.h"
#include "form.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_open_file_clicked()
{
QString filter = "log file (*log) ;; Tex File (*.txt)";
QString file_name = QFileDialog::getOpenFileName(this, "Open a file", QDir::homePath(), filter);
QMessageBox::information(this,"..",file_name);
QFile file(file_name);
if (!file.open(QFile::ReadOnly | QFile::Text)) QMessageBox::warning(this,"title","file not open");
else
{
QTextStream in(&file);
text = in.readAll();
ui->plainTextEdit->setPlainText(text);
ui->lineEdit->setPlaceholderText(file_name);
}
file.close();
}
void MainWindow::on_actionShow_text_file_triggered()
{
show_tab("all logs");
Form Fr;
Fr.text_to_plain(text);
}
void MainWindow::show_tab(QString keywords)
{
ui->tabWidget->addTab(new Form(), QString("%1").arg(keywords));
ui->tabWidget->setCurrentIndex(ui->tabWidget->count()-1);
}
form.cpp
#include "form.h"
#include "ui_form.h"
Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
}
Form::~Form()
{
delete ui;
}
void Form::text_to_plain(QString& text)
{
ui->plainTextEdit->setPlainText(text);
}
My problem is after call method void MainWindow::on_actionShow_text_file_triggered() plain text in QWidget in Form is still empty i tried: this->update, this->repaint, Form::update(); Form::repaint(), QWidget::repaint(); QWidget::update();. Everything fail.
the problem is that your Form exists only in this function scope.
void MainWindow::on_actionShow_text_file_triggered()
{
show_tab("all logs");
Form Fr;
Fr.text_to_plain(text);
}
Here -> Form Fr; the Form is created: constructor(explicit Form(QWidget *parent = nullptr);) of the class Form is called
And at this place -> } your Form is deleted: destructor(~Form();) of class Form is called.
This happens because you create your Form instance on the function stack. So Fr is local object and exist only in the scope of the function on_actionShow_text_file_triggered() after the function is executed/finished all local variables are freed/destructed.
if your Fr object should exist not just in this function you need to create it on the heap instead of stack.
P.S.: for case study read about stack vs heap for example hear: What and where are the stack and heap?
Your on_actionShow_text_file_triggered function should then look like this:
void MainWindow::on_actionShow_text_file_triggered()
{
show_tab("all logs");
Form * Fr = new Form(this); //if you set parent object your Form will be automatically deleted/destructed then MainWindow is deleted/destructed
Fr->text_to_plain(text);
Fr->show(); // you should call show() function of QWidget class and subclasses to get your widget visible
}
This Form * Fr = new Form(this); will create new form pointer every time. Would not it be better to create one global pointer to the form, call the functions and delete it later?
I would like share a string between two instances of QWidget.
In main.cpp, two objects are instantiated and shown like this:
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w1,w2; //Derived from QWidget
w1.show();
w2.show();
return a.exec();
}
I would introduce SharedState class:
// shared_state.h
#ifndef SHARED_STATE_HPP
#define SHARED_STATE_HPP
#include <QObject>
class SharedState : public QObject
{
Q_OBJECT
public:
SharedState(QString initialValue = "")
: currentValue(initialValue)
{}
QString getCurrentValue()
{
return currentValue;
}
public slots:
void setValue(QString newValue)
{
if(currentValue != newValue)
{
currentValue = newValue;
emit valueChanged(currentValue);
}
}
signals:
void valueChanged(QString);
private:
QString currentValue;
};
#endif // SHARED_STATE_HPP
Now I would provide reference to SharedState in Dialog's constructor,
// dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QWidget>
#include "shared_state.h"
namespace Ui {
class Dialog;
}
class Dialog : public QWidget
{
Q_OBJECT
public:
explicit Dialog(SharedState& state, QWidget *parent = 0);
~Dialog();
private slots:
void handleTextEdited(const QString&);
public slots:
void handleInternalStateChanged(QString);
private:
Ui::Dialog *ui;
SharedState& state;
};
#endif // DIALOG_H
You may have noticed that I have added two slots, one to handle the case when the text is manually edited and one when shared state will inform us that we are out of date.
Now in Dialog's constructor I had to set initial value to textEdit, and connect signals to slots.
// dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(SharedState& state, QWidget *parent) :
QWidget(parent),
ui(new Ui::Dialog),
state(state)
{
ui->setupUi(this);
ui->textEdit->setText(state.getCurrentValue());
QObject::connect(ui->textEdit, SIGNAL(textEdited(QString)),
this, SLOT(handleTextEdited(QString)));
QObject::connect(&state, SIGNAL(valueChanged(QString)),
this, SLOT(handleInternalStateChanged(QString)));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::handleTextEdited(const QString& newText)
{
state.setValue(newText);
}
void Dialog::handleInternalStateChanged(QString newState)
{
ui->textEdit->setText(newState);
}
Now the change in the main function:
// main.cpp
#include "dialog.h"
#include "shared_state.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
SharedState state("Initial Value");
Dialog w1(state), w2(state);
w1.show();
w2.show();
return a.exec();
}
I'd appreciate it, when someone could help me. I am not used to C++. I am new to it.
My problem: I want to make an object "player" usable for another class. I don't get how to archive this.
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#include <QMainWindow>
#include <QMediaPlayer>
#include <QDebug>
#include "Leap.h"
#include <leapmotionlistener.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QMediaPlayer* player;
private slots:
....
private:
Ui::MainWindow *ui;
void initialize();
Controller controller;
LeapMotionListener leapMotionListener;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSound>
#include <iostream>
#include <QfileDialog>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
player = new QMediaPlayer(this);
connect(player, &QMediaPlayer::positionChanged, this, &MainWindow::on_positionChanged);
connect(player, &QMediaPlayer::durationChanged, this, &MainWindow::on_durationChanged);
initialize();
}
QString path;
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initialize(){
controller.addListener(leapMotionListener);
leapMotionListener.setPlayer(player);
controller.setPolicy(Leap::Controller::POLICY_BACKGROUND_FRAMES);
}
...
leapmotionlistener.h
#ifndef LEAPMOTIONLISTENER
#define LEAPMOTIONLISTENER
#include <iostream>
#include <cstring>
#include "Leap.h"
#include <QFile>
#include <QAudioOutput>
#include <QMediaPlayer>
using namespace Leap;
class LeapMotionListener : public Listener {
public:
LeapMotionListener();
void setPlayer(QMediaPlayer&);
//... some more methods
private:
QMediaPlayer player;
};
#endif // LEAPMOTIONLISTENER
leapmotionlistener.cpp
//calls the player object in one method like the following
player.stop();
My main questions are: What am I doing wrong while referencing and instantiating? And how can leapmotionlistener access the same player object (I want to influence the audio)?
I get the Error:
MusicPlayer\mainwindow.cpp:32: Error: C2664: 'void LeapMotionListener::setPlayer(QMediaPlayer &)' : converting from argument 1 'QMediaPlayer *' in 'QMediaPlayer &' not possible
This little project is downloadable for a quick view with the following link:
https://www.dropbox.com/s/igr7ywnvicdlxxd/MusicPlayer.zip?dl=0
Thanks in advance!
All you need to do is
leapMotionListener.setPlayer(*player);
An lvalue reference binds to an object, not to the pointer to the object. In order to get the object from a pointer to it, you need to dereference the pointer using the *.
Among other problems, the QMediaPlayer you're trying to pass to setPlayer is a pointer, not a reference to an object.
You can either instantiate your player object like this:
QMediaPlayer player;
Or you can change your setPlayer function signature to this:
void setPlayer(QMediaPlayer* mplayer);
If you update your function signature, you'll also need fix other function signatures and leave the ampersands out of your connect() statements when you're referencing the player.
the following worked now:
in MainWindow.h:
public:
QMediaPlayer* player;
in MainWindow.cpp:
player = new QMediaPlayer(this);
leapMotionListener.setPlayer(player);
controller.addListener(leapMotionListener);
in LeapMotionListener.h:
private:
QMediaPlayer *player;
public:
void setPlayer(QMediaPlayer *mplayer);
in LeapMotionListener.cpp:
LeapMotionListener::LeapMotionListener()
: player(0)
{}
void LeapMotionListener::setPlayer(QMediaPlayer *mplayer){
player = mplayer;
}
i'm trying to make a simple currency converter and I have some problems with my class designed to make the calculations.
I want to create an object of this class in my MainWindow to use the total variable for displaying the result in a widget on my appi form.
Member functions aren't all here yet, but the problem I have is that i get a
'Calculator' : no appropriate default constructor available error in mainwindow.cpp
While I do know what that means, I don't know how to avoid (solve) the issue because i kind of need the reference on the map to get the echange rates needed.
.cpp
#include <QObject>
#include <QString>
#include <QDebug>
#include <ui_mainwindow.h>
class Calculator
{
public:
explicit Calculator(QMap<QString,double> ¤cy_map);
void multiply(double x, double y);
void getValues(QString strFrom, QString strTo);
private:
double total, firstCurr, secondCurr;
QMap<QString,double> ↦
};
.h
#include "calculator.h"
Calculator::Calculator(QMap<QString,double> ¤cy_map):map(currency_map)
{
total = 0;
firstCurr = 0;
secondCurr= 0;
}
void Calculator::getValues(QString strFrom, QString strTo)
{
QMapIterator<QString, double> i(map);
while(i.hasNext())
{
if(i.key() == strFrom)
firstCurr=i.value();
if(i.key() == strTo)
secondCurr = i.value();
}
}
void Calculator::multiply(double x, double y)
{
total = x * y;
}
and now im trying to create an object of that class in my MainWindow class:
#include <QMainWindow>
#include <ui_mainwindow.h>
#include "calculator.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QMap<QString,double> ¤cy_map, QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
parser currency_parser;
Calculator calc; // error
};
MainWindow.h
MainWindow::MainWindow(QMap<QString, double> ¤cy_map, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->from_Combox->addItems(currency_parser.currency_list);
ui->to_Combox->addItems(currency_parser.currency_list);
}
the idea behind was that i have a Map in my main in which i save all my data needed and pass the map around to classes that use it.
i'll post my main even tho im not sure if it's needed
#include "downloader.h"
#include "mainwindow.h"
#include "parser.h"
#include "calculator.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMap<QString,double> currency_map;
downloader d;
d.Do_download();
parser p;
p.read_line(currency_map);
MainWindow w(currency_map);
w.show();
return a.exec();
};
The error occurs, because you don't specify the appropriate constructor for class Calculator in the MainWindow constructors member initializer list (the compiler want's to use the default constructor then):
MainWindow::MainWindow(QMap<QString, double> ¤cy_map, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, calc(currency_map) // <<<<<<<<<<<<<<
{
// ...
}
char totalbuffer[2048] = {0};
this is the initialization of array I want. I had tried to put in main.cpp and my header file,qt creator keep show the error.
this is my .h header file code :
#ifndef QTPROJECT2_H
#define QTPROJECT2_H
#include <QDialog>
#include <QMainWindow>
#include <QtNetwork/QHostAddress>
#include <QLabel>
#include <QPushButton>
#include <QUdpSocket>
#include <QString>
#include <QTcpSocket>
#include <QDataStream>
#include <qstring.h>
#include <QStandardItem>
namespace Ui {
class QtProject2;
}
class QtProject2 : public QDialog
{
Q_OBJECT
public:
explicit QtProject2(QWidget *parent = 0);
~QtProject2();
void start(QString address, quint16 port);
char totalbuffer[2048]={0};
QStandardItemModel* ListModel;
private slots:
void on_pushButton_clicked();
public slots:
void startTransfer();
void disconnected();
void readyRead();
signals:
void socketReady();
private:
Ui::QtProject2 *ui;
QTcpSocket *client;
};
#endif // QTPROJECT2_H
this is my main.cpp coding:
#include "qtproject2.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtProject2 w;
w.show();
char totalbuffer[2048]={0};
return a.exec();
}
this is my project qtproject2.cpp:
#include "qtproject2.h"
#include "ui_qtproject2.h"
QtProject2::QtProject2(QWidget *parent) :
QDialog(parent),
ui(new Ui::QtProject2)
{
ui->setupUi(this);
}
QtProject2::~QtProject2()
{
delete ui;
QtProject2 Client2;
Client2.close();
}
void QtProject2::startTransfer()
{
ui->slabel->setText("Connected!");
}
void QtProject2::disconnected()
{
ui->slabel->setText("Disconnected!");
}
void QtProject2::readyRead()
{
client->waitForBytesWritten(1000);
client->waitForReadyRead(3000);
char CustomerData_MacAdd[][18]={"14:13:12:11:67:11","52:22:22:22:22:22", "14:22:44:55:22" };
char CustomerData_Username[][10]={"Robert","Alex","Ivan"};
QByteArray buffer1 = client->readLine();
char *temp = buffer1.data();
char buffer[1024]={0};
if (strncmp(temp,"*CLIENT",6)==0)
{
int j;
for(j=9;j<26;j++)
{ buffer[j-9]=temp[j];}
}else if(strncmp(temp,"*ALERT",5)==0)
{
int j;
for(j=8;j<25;j++)
{buffer[j-8]=temp[j];}
}
//char totalbuffer[2048]={0};
int k;
for (k=0;k<3;k++){
if (strncmp(buffer,CustomerData_MacAdd[k],16)==0){
strncat(totalbuffer,"User is in Queue : ",19);
strncat (totalbuffer,CustomerData_Username[k],size_t(CustomerData_Username[k]));
strncat(totalbuffer,"\n",2);
ui->label->setText(totalbuffer);
}}
ui->slabel->setText(buffer1);
}
void QtProject2::on_pushButton_clicked()
{
client = new QTcpSocket(this);
connect(client, SIGNAL(connected()),this, SLOT(startTransfer()));
connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(client, SIGNAL(readyRead()), this, SLOT(readyRead()));
/*Connect to User Define Port Address*/
client->connectToHost("127.0.0.1", 1234);
}
Focus for the char totalbuffer[2048]={0}; , i really no idea where i should put it.
I had searched with google and stackoverflow, all the method is using class and call in the .cpp file. but my one is GUI application,that's different with console.
What should i do? I really need a help. Appreciate the helps and thanks you guys~
EDITED***
this is the error shows.
error assigning to an array from an initializer list
I think the initialize list can't put in the header file and main.cpp so how i going to initialize an array? like C++ visual studio by using public variable....
You can use the memset or bzero functions
memset((void*)&totalbuffer, 0, sizeof(totalbuffer));
or
bzero((void*)&totalbuffer, sizeof(totalbuffer));
This is not related to Qt, but basic C++.
Class members are initialized in the constructor. You can just use std::fill there.