Home > Enterprise >  How to reach variable from another page in Qt C ?
How to reach variable from another page in Qt C ?

Time:08-30

I have 2 function in different c files. I need reach one variable from another cpp file. How Can I do this?

I need reach excelBuffer located on parser.cpp on inside void MainWindow::exportexcel() function located on mainwindow.cpp

parser.cpp

void Parser::parse(QString inputString)
{
      
QStringList excelBuffer =inputString.split(",");// I need reach excell buffer 
qDebug()<< excelBuffer[1]; 
   
}

mainwindow.cpp

void MainWindow::exportexcel() {
  
     //I need reach excelbuffer from here     
    }
 

CodePudding user response:

I think you can do this 2 ways. The first would be to change the signature of the function as suggested by @John in the comment section and the other would be to create a variable in the Parser class to hold the output of parse function.

First way

//in your header file

QStringList parser(QString inputString);

// in your cpp file

QStringList Parser::parser(QString input)
{
    QStringList excelBuffer =inputString.split(",");
    return excelBuffer;
}

Second way

First, you should create a public (depending on your OOP structure it might change) variable.

//in your header file
public:
    QStringList output;

// in your cpp file

void Parser::parse(QString inputString)
{
    QStringList excelBuffer =inputString.split(",");
    this->output = excelBuffer ;
}

Then you should create a variable of type Parser in the MainWindow class to reach its fields and attributes.

// in your MainWindow.h file 
Parser parser;

// In the function wherever you need

void MainWindow::exportexcel()
{
    for (QString b : parser.output)
    {
        qDebug() << b << "\n";
    }
}

Last comment, I personally prefer to use the first approach since, in my opinion, it is more controlled, like in the second approach output variable can be changed in other functions too, you cannot simply be sure whether the output is the one output that you are looking for.

CodePudding user response:

If Parser is a child of mainwindow simply do this:

void Parser::parse(QString inputString)
{
    QStringList excelBuffer = inputString.split(u',');
    parent()->setProperty("exelBuffer", exelBuffer);
}

and in your MainWindow:

void MainWindow::exportexcel()
{
    const QStringList exelBuffer = property("exelBuffer").toStringList();
}

and if Parser isnt a child of MainWindow use qApp->property() instead.

  •  Tags:  
  • c qt
  • Related