问题描述
在我的Windows窗体代码中,ui用于默认定义图形元素。但是我想在一个函数中修改它们,像这样:
问题是调试工具告诉我ui不在这个范围内声明。
#include< QMessageBox>
#include< QFile>
#include< QTextStream>
#includemainwindow.h
#includeui_mainwindow.h
#includedatawindow.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 MainWindow)
{
ui-> setupUi(this);
getData(ui);
}
MainWindow ::〜 MainWindow()
{
delete ui;
}
void MainWindow :: on_actionNouvellesDonnees_triggered(){
w.show();
}
解决方案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();
}
然后,在你的构造函数中:
ui-> setupUi(this);
getData();
我推荐这种方法,因为 ui 包含私有成员,所以最好有一个成员函数修改它。 p>
不要忘记在MainWindow类的头文件中声明 getData() 。
而btw, ui 不是数组,而是一个对象指针。
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(); }解决方案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.
这篇关于在函数Qt C ++中使用UI数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!