Allan Vindel
Allan Vindel

Reputation: 1

Creating a global object in QT GUI

I am trying to create an object called x from a class "Fan" inside the QT GUI mainwindow file, where I want it to be global. I want QT's button slot functions to be able to perform operations on the object. However, a compiler error "error: C4430: missing type specifier - int assumed" always occurs. Here is the header file:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_btOn_clicked();

    void on_btOff_clicked();

private:
    Ui::MainWindow *ui;
    Fan x; // This doesn't work
    Fan * x; // This doesn't either
    int x; // This does work
};

#endif // MAINWINDOW_H

And here is the cpp file:

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

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

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

void MainWindow::on_btOn_clicked()
{
    ui->lblState->setText("Fan is on");
}

void MainWindow::on_btOff_clicked()
{
    x.turnOff(); // This does not work of course
    x->turnOff(); // Or this
    ui->lblState->setText("Fan is off");
}

I already told the cpp file to include the Fan class from the fan.h file. If I create the object within the window constructor, it initializes fine but is not global. Also, there is no circular inclusion of header files. Fan class does not include mainwindow.

Perhaps I don't know how to search for it, but I've already done some research into it to no avail. Any help is appreciated.

Edit: Here is the fan.cpp file

#include "fan.h"

Fan::Fan(){
    speed = 0;
    isOn = false;
}
void Fan::setSpeed(int s){
    speed = s;
}
int Fan::getSpeed(){
    return speed;
}
void Fan::turnOn(){
    isOn = true;
    speed = 1;
}
void Fan::turnOff(){
    isOn = false;
    speed = 0;
}
bool Fan::getState(){
    return isOn;
}

And the fan.h file:

#ifndef FAN_H
#define FAN_H


class Fan
{
private:
    int speed;
    bool isOn;
public:
    Fan();
    void setSpeed(int);
    void turnOn();
    void turnOff();
    int getSpeed();
    bool getState();
};

#endif // FAN_H

Upvotes: 0

Views: 861

Answers (1)

Marcus
Marcus

Reputation: 1930

You forget to include or declare the class Fan in your Header File. If you use

Fan * x;

You could use

class Fan;

as a forward declaration at the beginning of your Header File. The Compiler only need to know that there is a class called Fan but inside the Header you only use a pointer. Butt don't forget to #include the real file in your CPP file.

If you use

Fan x;

you have to #include the Fan.h in your Header-File

Upvotes: 1

Related Questions