Using one variable in another class
-
I want to use QString username from mainwindow in the employee.cpp file and display it on a label. However when i declare it in the employeeinfo.cpp file i get this error:
Invalid use of non static member.
How can i access username variable in employeeinfo.cpp from mainwindow.hmainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include<QLabel> #include <QMainWindow> #include<QPushButton> #include<QSqlDatabase> #include "employeeinfo.h" namespace Ui { class MainWindow; } class employeeinfo; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QString username,password; <<< this variable private slots: private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
employeeinfo.h
#ifndef EMPLOYEEINFO_H #define EMPLOYEEINFO_H #include <QMainWindow> #include "mainwindow.h" namespace Ui { class employeeinfo; } class MainWindow; class employeeinfo : public QMainWindow { Q_OBJECT public: explicit employeeinfo(QWidget *parent = 0); ~employeeinfo(); private slots: private: Ui::employeeinfo *ui; }; #endif // EMPLOYEEINFO_H
employeeinfo.cpp
#include "employeeinfo.h" #include "ui_employeeinfo.h" employeeinfo::employeeinfo(QWidget *parent) : QMainWindow(parent), ui(new Ui::employeeinfo) { ui->setupUi(this); QString a = MainWindow::username; <<< i get the error here } employeeinfo::~employeeinfo() { delete ui; }
-
good design practice require that employeeinfo should not even know MainWindow exists.
Pass the username as an argument to the employeeinfo constructor.
explicit employeeinfo(const QString& username, QWidget *parent = 0);
employeeinfo::employeeinfo(const QString& username, QWidget *parent) : QMainWindow(parent), ui(new Ui::employeeinfo) { ui->setupUi(this); QString a = username; <<< i get the error here }
-
@VRonin
Hey ThanksBut now i get this error : no matching function call to 'employeeinfo::employeeinfo()'
when i declare an object to show employeeinfo window from mainwindow
employeeinfo *emp = new employeeinfo();i declared this is mainwindow.cpp
-
that's because there is where you need to pass the username
employeeinfo *emp = new employeeinfo(username);
Given the doubts you are having my advice is to take a quick look to a general C++ tutorial like http://www.cplusplus.com/doc/tutorial/ before diving into Qt