Qt中使用全局变量的两种方式

原文地址::https://blog.****.net/u014546553/article/details/78558925

相关文章

1、QT 使用全局变量的方法----https://blog.****.net/guoqianqian5812/article/details/49913371

2、QT编程之——使用全局变量----https://blog.****.net/zhenyu5211314/article/details/26210353


1、使用static关键字:

头文件声明:声明为public类型变量

mainwindow.h

[cpp] view plain copy
  1. #ifndef MAINWINDOW_H  
  2. #define MAINWINDOW_H  
  3. #include <QMainWindow>  
  4. namespace Ui {  
  5. class MainWindow;  
  6. }  
  7. class MainWindow : public QMainWindow  
  8. {  
  9.     Q_OBJECT  
  10. public:  
  11.     explicit MainWindow(QWidget *parent = 0);  
  12.     ~MainWindow();     
  13.     static int a;      
  14.     static QString c;  
  15. private:  
  16.     Ui::MainWindow *ui;  
  17. };  
  18. #endif // MAINWINDOW_H  


Qt中使用全局变量的两种方式

源文件定义:注意这里的变量定义,一定要写在函数的外面

mainwindow.cpp

[cpp] view plain copy
  1. #include "mainwindow.h"  
  2. #include "ui_mainwindow.h"  
  3. #include <QtMath>  
  4. #include <qwt_plot.h>  
  5. #include <qwt_plot_curve.h> //是包含QwtPointSeriesData类的头文件  
  6. #include <qwt_plot_grid.h>  
  7.   
  8. int MainWindow::a = 100;  
  9. QString MainWindow::c = "clue";  
  10.   
  11. MainWindow::MainWindow(QWidget *parent) :  
  12.     QMainWindow(parent),  
  13.     ui(new Ui::MainWindow)  
  14. {  
  15.       
  16.     qDebug()<<"a="<< a;  
  17.   
  18.     ui->textBrowser->setText(c);  
  19. //..........................后面代码省略  
Qt中使用全局变量的两种方式

调用方式:在函数里面调用全局变量

Qt中使用全局变量的两种方式

2、使用extern关键字:

cglobal.h  (声明写在类和命名控件的外面)

[cpp] view plain copy
  1. #ifndef CGLOBAL_H  
  2. #define CGLOBAL_H  
  3. extern int testValue;  
  4. #endif // CGLOBAL_H  

cglobal.cpp  (在函数外面定义变量)

[cpp] view plain copy
  1. #include "cglobal.h"  
  2.   
  3. int testValue=1;  

调用方式

[cpp] view plain copy
  1. #include "cglobal.h"  
  2. #include <QDebug>  
  3.   
  4. qDebug()<<testValue;  
  5. testValue=2;  
  6. qDebug()<<testValue;  
墙裂推荐第一种使用static关键字的全局变量,第二种会破坏封装性。