PDA

View Full Version : problems in a small dialog



franky
18th October 2016, 09:14
I wanted to create a small dialog that using buttons we can add some numbers.
First I designed a form by Qt Designer using Dialog Without Buttons template like this:

12183

Then I wrote a calculator.h file like this:



#ifndef CALCULATOR_H
#define CALCULATOR_H

#include<QDialog>
#include "ui_Calculator.h"

class Calculator : public QDialog, public Ui::Calculator
{
Q_OBJECT

public:
Calculator(QWidget* parent = 0);

private slots:
void myslot();
};

#endif // CALCULATOR_H


Then, a calculator.cpp this way:



#include <QtWidgets>
#include "calculator.h"

Calculator::Calculator(QWidget *parent)
:QDialog(parent)
{
setupUi(this);

connect(oneButton,SIGNAL(clicked(bool)), lineEdit, SLOT(myslot()));
}

void Calculator::myslot(){
lineEdit -> setText("1");
}



And finally the main.cpp this way:


#include <QApplication>
#include <QDialog>

#include "ui_Calculator.h"

int main(int argc, char* argv[])
{
QApplication app(argc, argv);

Ui::Calculator ui;
QDialog* dialog = new QDialog;
ui.setupUi(dialog);
dialog -> show();

return app.exec();
}


Now the code runs without any error but not as expected! That is when I click on '1' button nothing will be printed out onto the lineEdit.
Why please and how to solve it?

anda_skoa
18th October 2016, 16:58
You main() never creates an instance of Calculator, so there is no chance any of its could could ever be executed.

Instead of all the code between the QApplication creation and the return line, create an object of type Calculator and show it.

Cheers,
_

P.S.: additional suggestion would be to use the generated class as a member instead of inheriting from it

franky
19th October 2016, 14:46
Do you mean instead of:

int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Ui::Calculator ui;
QDialog* dialog = new QDialog;
ui.setupUi(dialog);
dialog -> show();

return app.exec();
}

I should write:


int main(int argc, char* argv[])
{
QApplication app(argc, argv);

Calculator calc;
calc.show();

return app.exec();
}

?

Can it be running?

anda_skoa
19th October 2016, 19:46
Yes, that is exactly what I meant and what you are intending to do.

Cheers.
_

franky
20th October 2016, 07:34
Thanks for the reply.
I made that changes but I got these errors:

1- C:\Users\Me\Documents\Qt\Calculator\main.cpp:9: error: 'Calculator' was not declared in this scope
Calculator calc;
^
2- C:\Users\Me\Documents\Qt\Calculator\main.cpp:10: error: 'calc' was not declared in this scope
calc.show();
^

Ginsengelf
20th October 2016, 09:02
Hi, you need to #include "calculator.h" in main.cpp

Ginsengelf

franky
20th October 2016, 10:14
Thank you.The problem is solved. :)