Use UI array in a function Qt C++

天涯浪子 提交于 2019-12-25 18:14:42

问题


In my Windows forms code, ui is used to define graphical element by default. But I want to modify them in a function, like this:

The problems is that the debug tool tells me that ui is not declared in this scope.

#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "datawindow.h"

void getData(ui){
    QFile inputFile("C:\\pepoles.txt");
        if (inputFile.open(QIODevice::ReadOnly)){
           QTextStream in(&inputFile);



           while ( !in.atEnd() ){
              QString line = in.readLine();
              ui->listWidgetData->addItem(line);
           }
        }
        else{
            QMessageBox::critical(this, "Erreur", "Une erreur s'est produite :(");
        }
    inputFile.close();
}

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

}

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

void MainWindow::on_actionNouvellesDonnees_triggered() {
    w.show();
}

回答1:


void getData(ui){

That line starts definition of getData function, which takes one variable, with type ui and no name (so it can't be accessed in the function code).

Add type...

void getData(MainWindow::Ui *ui){



回答2:


Make getData() a member of MainWindow:

void MainWindow::getData()
{
    QFile inputFile("C:\\pepoles.txt");
    if (inputFile.open(QIODevice::ReadOnly)) {
        QTextStream in(&inputFile);
        while ( !in.atEnd() ) {
            QString line = in.readLine();
            ui->listWidgetData->addItem(line);
        }
    } else {
        QMessageBox::critical(this, "Erreur", "Une erreur s'est produite :(");
    }
    inputFile.close();
}

Then, in your constructor:

ui->setupUi(this);
getData();

I recommend this approach since ui contains private members, so it's best to have a member function modify it.

Don't forget to declare getData() in the header file of your MainWindow class. You should probably make it private.

And btw, ui is not an array. It's an object pointer.



来源:https://stackoverflow.com/questions/13350338/use-ui-array-in-a-function-qt-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!