PDA

View Full Version : Public variables



eltecprogetti
30th March 2012, 10:46
Hi,

I am a QT project with 3 forms (mainwindow, form2, form3).

I am also a lot of variables in use in the mainwindow, and I need to read and write these variables into form2 and form3.

I have to define my variables public in the main() (I think so), but I do not know how to do it.

Thanks.

aamer4yu
30th March 2012, 11:07
You can make the variables part of MainWindow.. then provide some setter functionsi n form2 and form3.
This way you can set them in the forms.

Other way is to use signals and slots

eltecprogetti
30th March 2012, 11:12
I provide some setter functions in form2 and form3? what it means?
Can you give an example?

aamer4yu
30th March 2012, 11:17
You will have some class for your forms, right ?
Lets say
class MyWidget : public QWidget
{
int m_x;
public:
void setVariableV1(int x);
}

Then you can use object of the widget from your mainwindow-
objMyWidget->setVariableV1(newVariableValue);

Hope you get the hint :)

eltecprogetti
30th March 2012, 11:34
This in my mainwindows.h


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

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



Now, in my Form2 I want to write the variable "Test".

MainWindow::Test=3;



This is the compiler answer:

.....illegal reference to non-static member 'MainWindow::Test

aamer4yu
30th March 2012, 12:03
I guess you need to work a little on C++.
Give some time to learning and you will be able to solve yourself.

Charvi
5th April 2012, 11:47
You must be having a main.cpp right?

How are you accessing your main window class? You must have created an object of the main window class some where int he main.cpp and then called mainwindow.show().
Similarly you can access the variables of that class by creating object of the class.

Surendil
5th April 2012, 15:07
I think you may use signal/slot mechanism to set these variables in form2 and form3 from mainwindow.
If your variables are of the same type, you may want to use QHash< VariableName, VariableValue > to store variable data -- in this case you need one signal from mainwindow and only oneslot in form2 and form3.

amleto
6th April 2012, 12:58
looks like eltec really needs to learn some basics of OOP and c++.


Variables etc that are members of a class need an *instance* to be available. To set/get members, or use member functions, an *instance* must be available.



class MyClass
{
public:
int x;
};

int main()
{
MyClass myclass; // make an instance!
myclass.x = 5; // set the variable
int x = myclass.x; // get the variable


MyClass::x; // wrong!
myclass->x; // wrong! myclass is not a pointer.

MyClass.x // wrong! MyClass is not an instance
}


OP, please learn a little (well, ok more than a little) about c++ - this will also involve learning some about oop.