Incrementing a number in qt c++
-
In my code I need to increment an integer used by 2 methods(button clicks)! 1 method is used to display the integer(starting value is 1) in a line edit when a button is clicked! The other button is used to increment the number! I need to declare the integer in the header file to be used by the two methods! But in the header file we can declare only static constant so when I increment the error I get an error! How can I avoid this?
void MainWindow::on_pushButton_2_clicked()
{
ui->lineedit->text(QString::number(i));
}
void MainWindow::on_pushButton_2_clicked(){
i++;
} -
In my code I need to increment an integer used by 2 methods(button clicks)! 1 method is used to display the integer(starting value is 1) in a line edit when a button is clicked! The other button is used to increment the number! I need to declare the integer in the header file to be used by the two methods! But in the header file we can declare only static constant so when I increment the error I get an error! How can I avoid this?
void MainWindow::on_pushButton_2_clicked()
{
ui->lineedit->text(QString::number(i));
}
void MainWindow::on_pushButton_2_clicked(){
i++;
} -
@Lasith Just declare it as member variable in MainWindow class:
class MainWindow { ... private: int i; }
Note: there is no such thing as "qt c++".
-
@jsulm Thanx but I get the error message "only static const integral data members can be initialized within a class” :(
@Lasith I guess you did it like this?
class MainWindow { ... private: int i = 0; }
This is supported in C++11 and newer.
Do it like this:class MainWindow { ... private: int i; } // in mainwindow.cpp MainWindow::MainWindow(): i(0) { }
This are C++ basics, you should really take some time to learn C++.
As alternative you can enable C++11 support (will only work if your compiler supports it!). To do so add this to your pro file:CONFIG += c++11
Run qmake and rebuild.
-
@Lasith I guess you did it like this?
class MainWindow { ... private: int i = 0; }
This is supported in C++11 and newer.
Do it like this:class MainWindow { ... private: int i; } // in mainwindow.cpp MainWindow::MainWindow(): i(0) { }
This are C++ basics, you should really take some time to learn C++.
As alternative you can enable C++11 support (will only work if your compiler supports it!). To do so add this to your pro file:CONFIG += c++11
Run qmake and rebuild.
-
@jsulm Thanx but where is
MainWindow::MainWindow():
{
}to put i(0) ?
I only find
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)in my mainwindow.cpp
-
@Lasith Just extend the existing constructor:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), i(0) { ... }
-
Then please consider upgrading to a more recent version, we are currently at Qt 5.9.
-
@Lasith Just extend the existing constructor:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), i(0) { ... }