0

I'm a beginner in C++. I was making a test application in Qt and came across this problem: Where do I have to declare a variable in order to use it in a function like on_pushButton_clicked() ?

I tried making a main function and declaring the variable there and always got this error when changing the variable in another function: error: reference to non-static member function must be called; did you mean to call it with no arguments? Then I tried declaring the variable directly (not in any function) but that didn't work either.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

int main() {

    int x = 0;

    return 0;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    x++; //here's the error
    ui->label->setText("number is:");
}

Is there a way to declare that variable (x) so that I can access it through on_pushButton_clicked()?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
CJames
  • 59
  • 2
  • 9
  • 2
    Create the variable in your class not in main. Remember that the variable in main will only be visible inside main. This is about scope. – drescherjm Jun 25 '19 at 19:00
  • `x` is local to the scope of `main()` and cannot be acessed from `void MainWindow::on_pushButton_clicked()`. You may want to have a global variable instead (not that I'd really recommend to do so). – πάντα ῥεῖ Jun 25 '19 at 19:02
  • Here is more about scope: https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm – drescherjm Jun 25 '19 at 19:02
  • 1
    I removed the [tag:qt] tag, since there's no QT specific behavior described in the code. – πάντα ῥεῖ Jun 25 '19 at 19:05
  • @drescherjm what class do I create the variable in? – CJames Jun 25 '19 at 19:09
  • 2
    It seems you could benefit from reading [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or two.. I'd recommend doing that. – Jesper Juhl Jun 25 '19 at 19:09
  • 1
    `ui` is a variable in your class. However if you have to ask this question you are getting way ahead of yourself programming in `Qt` since you don't know the basic `c++`. I recommend spending several weeks minimum learning `c++` before continuing writing `GUI` code in `Qt`. – drescherjm Jun 25 '19 at 19:13
  • Here is a tutorial about how to add variables to a class in `c++`: http://www.cplusplus.com/doc/tutorial/classes/ – drescherjm Jun 25 '19 at 19:17

1 Answers1

0

I managed to make it work: the problem was that I couldn't find, at first, the header file containing the class. That's where I should have declared my variable.

CJames
  • 59
  • 2
  • 9