Use UI array in a function Qt C++ - c++

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();
}

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){

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.

Related

QT c++ multiple definition and first defined here error

I added a part in the main.cpp file that asks for a password before the window opens. It gets what it needs from the help.h and cnstnt.h files. Then I created a dialog named settings and tried to change the password here. It was working fine in my previous test project, but when I used the same things in this project, I encountered a first defined here error. I checked, I did run qmake and rebuild but nothing changed. How can I fix this problem? I'm new to C++ and QT.
here is my codes
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include "cnstnt.h"
#include "help.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle("fusion");
a.setQuitOnLastWindowClosed(false);
MainWindow w;
QString login = QInputDialog::getText(NULL, "Login","username",QLineEdit::Normal);
if (login == cnstnt::username)
{
QString getPassword = QInputDialog::getText(NULL, "Login","password",QLineEdit::Password);
QString hashpassword = hlpr::hashPassword(getPassword.toUtf8());
if(hashpassword == hlpr::getTxtPassword()){
w.show();
}else{
QMessageBox::warning(nullptr, "error!", "wrong password!");
}
}
else
{
QMessageBox::warning(nullptr, "error!", "wrong username!");
}
return a.exec();
}
cnstnt.h
#ifndef CNSTNT_H
#define CNSTNT_H
#include <QtWidgets>
namespace cnstnt {
QString TEXT_DIR = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/test/password.txt";
QString username = "admin";
}
#endif // CNSTNT_H
help.h
#ifndef HELP_H
#define HELP_H
#include <QCryptographicHash>
#include "cnstnt.h"
namespace hlpr {
// login actions
QString hashPassword(QByteArray str){
QByteArray step1 = QCryptographicHash::hash((str),QCryptographicHash::Md5).toHex();
QString lastHash = QString(QCryptographicHash::hash((step1),QCryptographicHash::Sha512).toHex());
return lastHash;
}
QString getTxtPassword(){
QString currentPassword;
QFile file(cnstnt::TEXT_DIR);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream in(&file);
currentPassword = in.readLine();
file.close();
}
return currentPassword;
}
bool setTxtPassword(QString newPass){
QFile file(cnstnt::TEXT_DIR);
if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
QTextStream stream(&file);
QByteArray newPassType = newPass.toUtf8();
stream << hashPassword(newPassType);
file.close();
return true;
}
return false;
}
}
#endif // HELP_H
settingdialog.h
#ifndef SETTINGDIALOG_H
#define SETTINGDIALOG_H
#include <QDialog>
#include <QMessageBox>
#include "help.h"
namespace Ui {
class settingDialog;
}
class settingDialog : public QDialog
{
Q_OBJECT
public:
explicit settingDialog(QWidget *parent = nullptr);
~settingDialog();
private slots:
void on_pushButton_8_clicked();
private:
Ui::settingDialog *ui;
};
#endif // SETTINGDIALOG_H
settingdialog.cpp
#include "settingdialog.h"
#include "ui_settingdialog.h"
settingDialog::settingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::settingDialog)
{
ui->setupUi(this);
}
settingDialog::~settingDialog()
{
delete ui;
}
void settingDialog::on_pushButton_8_clicked()
{
QString TEXT_DIR = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/test/password.txt";
QString savedPassword = hlpr::getTxtPassword();
QString curPassword = ui->oldPassBox->text();
QString newPass = ui->newPassBox->text();
QString confirmPass = ui->confirmPass->text();
QByteArray curHash = curPassword.toUtf8();
if(newPass != confirmPass) {
QMessageBox::information(this, "Bilgi", "Yeni şifreniz ile tekrarı eşleşmiyor!");
}else if(newPass == curPassword){
QMessageBox::information(this, "Bilgi", "Mevcut şifreniz ile yeni şifreniz ile aynı olamaz!");
}else if(savedPassword != hlpr::hashPassword(curHash)) {
QMessageBox::information(this, "Bilgi", "Mevcut şifreniz hatalı!");
}else{
bool status = hlpr::setTxtPassword(newPass);
if(status){
ui->oldPassBox->clear();
ui->newPassBox->clear();
ui->confirmPass->clear();
QMessageBox::information(this, "Başarılı", "Şifreniz başarıyla güncellendi.");
}else{
QMessageBox::warning(this, "Hata!", "Şifreniz güncellenirken hata oluştu!");
}
}
}
errors
X:\DataLoggerQT\QtSerialMonitor-master\src\help.h:11: error:
multiple definition of hlpr::passwordHash(QByteArray)' debug/mainwindow.o: In function ZSt19__iterator_categoryIPK7QStringENSt15iterator_traitsIT_E17iterator_categoryERKS4_':
X:\DataLoggerQT\QtSerialMonitor-master\build-QtSerialMonitor-Desktop_Qt_5_15_2_MinGW_32_bit-Debug/../src/help.h:11:
multiple definition of `hlpr::passwordHash(QByteArray)'
X:\DataLoggerQT\QtSerialMonitor-master\src\help.h:11: first defined
here
X:\DataLoggerQT\QtSerialMonitor-master\src\help.h:28: error: multiple definition of hlpr::setTxtPassword(QString)' debug/moc_mainwindow.o: In function ZN4hlpr14setTxtPasswordE7QString':
X:\DataLoggerQT\QtSerialMonitor-master\build-QtSerialMonitor-Desktop_Qt_5_15_2_MinGW_32_bit-Debug/debug/../../src/help.h:28: multiple definition of `hlpr::setTxtPassword(QString)'
You have included helper.h in two header files - settingdialog.h and main.cpp, mainwindow.h is included in main.cpp and, I suppose, includes settingdialog.h itself. Or, maybe, it's included through any other included header. So you've got multiple definition error, one per include.
To avoid such kind of errors, functions in helper.h file should be declared with extern keyword and their implementation should be moved to helper.cpp file. It would prevent you from any potential problems in future. And you should always declare functions in this way.
And at last, you do not need to include helper.h in settingdialog.h as you use it's functions in cpp. Move include to settingdialog.cpp. Keep it in mind to include files only there, where they are really used, it would minimize compilation time.

How do I get the text from a QTableView cell into a QlineEdit on click Qt5 C++

So I have been trying all day to find a working example of how to retrieve the data from a QtableView into a lineEdit as a QString. I think I have tried every example code online and have had zero success, I can not even figure out how to pull the row and column numbers from the tableView. Everything I have tried fails and I get the error that index is a unused parameter. This has got to be something simple that I am missing but I have not used QT or done any C++ programing since version 3 and am completely baffled. mainWindow.cpp is below. Thanks in advance for any help you can give me. BTW everything works fine except for the clicked slot.
#include <QDebug>
#include <QAbstractTableModel>
#include <QModelIndex>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->setupUi(this);
// Create a data model for the mapping table from a CSV file
csvModel = new QStandardItemModel(this);
csvModel->setColumnCount(2);
//csvModel->setHorizontalHeaderLabels(QStringList() << "Name" << "Number");
ui->tableView->setModel(csvModel);
// Open the file
QFile file("/home/foo.csv");
if ( !file.open(QFile::ReadOnly | QFile::Text) ) {
qDebug() << "File not exists";
} else {
// Create a thread to retrieve data from a file
QTextStream in(&file);
//Read to end
while (!in.atEnd())
{
QString line = in.readLine();
QList<QStandardItem *> standardItemsList;
for (QString item : line.split(",")) {
standardItemsList.append(new QStandardItem(item));
}
csvModel->insertRow(csvModel->rowCount(), standardItemsList);
}
file.close();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
qDebug() << "test";
}
Header code below
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStandardItemModel>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_tableView_clicked(const QModelIndex &index);
private:
Ui::MainWindow *ui;
QStandardItemModel *csvModel;
};
#endif // MAINWINDOW_H
I think this is just a basic misunderstanding with regard to how signals/slots operate. Unless you're using the auto connect feature you need to manually connect a signal to a slot using one of the QObject::connect overloads. So in your constructor you need something like...
connect(ui->tableView, &QTableView::clicked, this, &MainWindow::[on_tableView_clicked);

How to get QString from one window to another window, via pressing a button in a 3rd window

New to C++ and Qt as part of a research project (biology) and have been struggling with presumably some quite simple stuff. I'd really appreciate someone's help.
I'm working with a GUI for a pre-existing programme and I'm trying to transfer a QString variable from the QLineEdit of one of the windows (inputform), to the QLineEdit of a second window (output form).
The bit I'm stuck with is that I need the output form to appear, with it's LineEdit pre-populated, when I click a button on a third window (filedialog).
Problem:
At start up --> two windows appear: filedialog and inputform.
User enters data into inputform's QLineEdit
User presses 'transferButton' on filedialog window
On button press --> outputform appears, with a QLineEdit pre-populated with the user's data (from the inputform).
I assume the problem is of the getter/setter variety and my variable is probably going out of scope, but I've tried following lots of similar examples but can't make it work.
Thanks in advance.
Here's my code:
Main.cpp
#include "filedialog.h"
#include "inputform.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FileDialog w;
InputForm w2;
w.show();
w2.show();
return a.exec();
}
filedialog.h
#ifndef FILEDIALOG_H
#define FILEDIALOG_H
#include <QDialog>
namespace Ui {
class FileDialog;
}
class FileDialog : public QDialog
{
Q_OBJECT
public:
explicit FileDialog(QWidget *parent = nullptr);
~FileDialog();
void setFileName();
QString getFileName();
private slots:
void on_transferButton_clicked();
private:
Ui::FileDialog *ui;
QString fileName;
};
#endif // FILEDIALOG_H
filedialog.ccp
#include "filedialog.h"
#include "ui_filedialog.h"
#include "inputform.h"
#include "ui_inputform.h"
#include "outputform.h"
#include "ui_outputform.h"
FileDialog::FileDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::FileDialog)
{
ui->setupUi(this);
}
FileDialog::~FileDialog()
{
delete ui;
}
void FileDialog::setFileName()
{
InputForm *inputform = new InputForm;
fileName = inputform->ui->inputLineEdit->text();
}
QString FileDialog::getFileName()
{
return fileName;
}
void FileDialog::on_transferButton_clicked()
{
setFileName();
OutPutForm *outputform = new OutPutForm;
outputform->ui->outputLineEdit->setText(getFileName());
outputform->show();
}
inputform.h
#ifndef INPUTFORM_H
#define INPUTFORM_H
#include <QWidget>
namespace Ui {
class InputForm;
}
class InputForm : public QWidget
{
Q_OBJECT
public:
explicit InputForm(QWidget *parent = nullptr);
~InputForm();
Ui::InputForm *ui;
};
#endif // INPUTFORM_H
inputform.ccp
#include "inputform.h"
#include "ui_inputform.h"
InputForm::InputForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::InputForm)
{
ui->setupUi(this);
}
InputForm::~InputForm()
{
delete ui;
}
outputform.h
#ifndef OUTPUTFORM_H
#define OUTPUTFORM_H
#include <QWidget>
namespace Ui {
class OutPutForm;
}
class OutPutForm : public QWidget
{
Q_OBJECT
public:
explicit OutPutForm(QWidget *parent = nullptr);
~OutPutForm();
Ui::OutPutForm *ui;
};
#endif // OUTPUTFORM_H
outputform.ccp
#include "outputform.h"
#include "ui_outputform.h"
OutPutForm::OutPutForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::OutPutForm)
{
ui->setupUi(this);
}
OutPutForm::~OutPutForm()
{
delete ui;
}
Thank you for your brief pointer.
After some playing around:
Setup mainwindow (or in my case main dialog window). Generate inputform instance, connect button to inputform.
FileDialog::FileDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::FileDialog)
{
ui->setupUi(this);
InputForm *inputForm = new InputForm;
connect(ui->transferButton,SIGNAL(clicked()),inputForm,SLOT(getLineEditTextFunc()));
inputForm->show();
}
FileDialog::~FileDialog()
{
delete ui;
}
void FileDialog::on_transferButton_clicked()
{
}
Then from the input form:
Define a function to get the input form's LineEdit text (fileName); and then also generate an output form and populate it's LineEdit with the fileName variable.
InputForm::InputForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::InputForm)
{
ui->setupUi(this);
}
InputForm::~InputForm()
{
delete ui;
}
void InputForm::getLineEditTextFunc()
{
fileName = this->ui->inputLineEdit->text();
OutPutForm *outputform = new OutPutForm;
outputform->ui->outputLineEdit->setText(fileName);
outputform->show();
}

QT With C++: How to implement Save As

I'm trying to add a save as feature to a simple text editor I'm making with C++ and QT. I'm attempting to close the current tab when you save your file and open a new tab with the same index and has the name of the new file as the tab title. This is my code:
QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), "", tr("All Files (*)"));
if (fileName.isEmpty())
return;
else
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QTextStream out (&file);`
out << ui->plainTextEdit->toPlainText();
QFileInfo FileData(file);
int currentTab = ui->tabWidget->currentIndex();
ui->tabWidget->removeTab(currentTab);
QTextStream InputData(&file);
ui->tabWidget->insertTab(currentTab, new Form(), FileData.fileName());
ui->tabWidget->setCurrentIndex(currentTab);
ui->plainTextEdit->setPlainText(InputData.readAll());
file.flush();
file.close();
}
When I try to save the new file, it saves the file to the selected location and replaces the current tab with the file name, but it doesn't write the file to the text window. Any help would be great.
Here is my demo code and it seems to work:
form.cpp which has a plainTextEdit
#include "form.h"
#include "ui_form.h"
Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
}
Form::~Form()
{
delete ui;
}
QString Form::GetText()
{
return ui->plainTextEdit->toPlainText();
}
void Form::SetText(QString text)
{
ui->plainTextEdit->setPlainText(text);
}
And the mainwindow.cpp which contains a QTabWidget
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "form.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
ui->tabWidget->insertTab(0, new Form(), "My File");
ui->tabWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_2_clicked()
{
int currentIndex = ui->tabWidget->currentIndex();
//Save the text to a file or a variable...
QString content = static_cast<Form*>(ui->tabWidget->widget(currentIndex))->GetText();
ui->tabWidget->removeTab(currentIndex);
ui->tabWidget->insertTab(currentIndex, new Form(), "Saved File");//new name
static_cast<Form*>(ui->tabWidget->widget(currentIndex))->SetText(content);
ui->tabWidget->setCurrentIndex(currentIndex);
}
It is working for me, please try.
Thank You.

How to get file name in Qt?

I have modified the Text Finder example which I got from a Qt Tutorial and made a Text Viewer. In this program, the user types in the address of the file and clicks the Search button. The program then displays the content of the text file. Below is my code.
text_finder.cpp:
#include "text_finder.h"
#include "ui_text_finder.h"
#include <QHBoxLayout>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
Text_Finder::Text_Finder(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Text_Finder)
{
ui->setupUi(this);
}
Text_Finder::~Text_Finder()
{
delete ui;
}
void Text_Finder::loadFile(QFile file){ // I have to pass the file name as parameter.
QFile inputFile(file);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString line = in.readAll();
inputFile.close();
ui->read->setText(line);
QTextCursor cursor = ui->read->textCursor();
cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1);
}
void Text_Finder::on_search_clicked()
{
// Code that gets the path from the text box.
loadFile();//Parameters not passed yet.
}
I have not yet entered the code which gets the name of the file from the address of the text box. I will have to pass the file to the loadFile() function which will enter the contents into the Text Edit in the center of the program. I want a solution to get the name of the file of which the user enters. For example, the user might enter, "/home/user/input.txt". The program should get the contents of that file and forward it to loadFile(). An solution with an explanation on how the various parts work is needed. I am using Qt Creator on Ubuntu 15.04 (Beta).
If i understand you correctly, the user types the full path or address of the file in the text box and you want to get just the name of the file out of the full path the user entered.
EDIT: I realized using 'QFileDialog' was the ideal way to get the file name. So this
is how i redesigned the whole code;
text_finder.h
#ifndef TEXT_FINDER_H
#define TEXT_FINDER_H
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
class Text_Finder : public QWidget{
Q_OBJECT
public:
Text_Finder(QWidget *parent = 0);
~Text_Finder();
public slots:
void on_search_clicked();
void open();
//void loadFile(QString const &filename);
private:
void loadFile(QString const &filename);
QLineEdit *txtFileName;
QTextEdit *txtFileContents;
QString fileName;
QPushButton *search;
QPushButton *openFile;
};
#endif
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
};
#endif // MAINWINDOW_H
text_finder.cpp
#include "text_finder.h"
Text_Finder::Text_Finder(QWidget *parent) : QWidget(parent) {
openFile = new QPushButton("Open File");
connect(openFile, SIGNAL(clicked()), this, SLOT(open()));
txtFileName = new QLineEdit;
search = new QPushButton("&Search");
txtFileContents = new QTextEdit;
QHBoxLayout *dialogAndViewLayout = new QHBoxLayout;
dialogAndViewLayout->addWidget(openFile);
dialogAndViewLayout->addWidget(txtFileName);
dialogAndViewLayout->addStretch();
dialogAndViewLayout->addWidget(search);
QVBoxLayout *layout = new QVBoxLayout;
layout->addLayout(dialogAndViewLayout);
layout->addWidget(txtFileContents);
connect(search, SIGNAL(clicked()), this, SLOT(on_search_clicked()));
setLayout(layout);
}
Text_Finder::~Text_Finder(){
delete txtFileName;
delete txtFileContents;
delete search;
delete openFile;
}
void Text_Finder::loadFile(QString const &filename){
QFile inputFile(filename);
inputFile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream textStream(&inputFile);
QString contents = textStream.readAll();
inputFile.close();
txtFileContents->setPlainText(contents);
}
void Text_Finder::on_search_clicked() {
loadFile(fileName);
}
/*this slot opens a file dialog. After the file has been selected, it sets
the file to the text text edit box*/
void Text_Finder::open() {
fileName = QFileDialog::getOpenFileName(this, "Open text", "/home/",
"");
txtFileName->setText(fileName);
}
mainwindow.cpp
#include "mainwindow.h"
#include "text_finder.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
Text_Finder *textFinder = new Text_Finder;
setCentralWidget(textFinder);
}
MainWindow::~MainWindow() {
}
Finally
main.cpp
#include "text_finder.h"
#include <QApplication>
int main(int argc, char **argv){
QApplication app(argc, argv);
Text_Finder *window = new Text_Finder;
window->show();
return app.exec();
}
Unless you're going to do some programmatic editing, you do not need to use QTextCursor at all.
I suggest you have a browse through the reference manual before trying to carry on since it's clear that you are not familiar with the bare-basics of the graphical widgets you're using.
If you're only reading in a file name and then displaying the contents in plain text format, this is all you need to do. (I'm assuming your filename is entered into a QLineEdit widget and ui->read is a QTextEdit widget)
void Text_Finder::loadFile(QString const &filename){ // I have to pass the file name as parameter.
QFile inputFile(filename);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString contents = in.readAll();
inputFile.close();
ui->read->setPlainText(contents);
}
void Text_Finder::on_search_clicked()
{
QString filename = ui->filename->text();
loadFile(filename);
}
EDIT:
I've created a fully-functional remake of your code, incorporating the changes I suggested. I have compiled and tested it and it is working as per your description.
Note: In the absence of your UI file, I've created the user interface manually.
text_finder.h
#ifndef TEXT_FINDER_H
#define TEXT_FINDER_H
#include <QMainWindow>
class QLineEdit;
class QTextEdit;
class Text_Finder : public QMainWindow{
Q_OBJECT
public:
Text_Finder(QWidget *parent = 0);
~Text_Finder();
public slots:
void on_search_clicked();
private:
void loadFile(QString const &filename);
QLineEdit *txtFileName;
QTextEdit *txtFileContents;
};
#endif // TEXT_FINDER_H
main.cpp
#include "text_finder.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
Text_Finder::Text_Finder(QWidget *parent) :
QMainWindow(parent)
{
QWidget *ui = new QWidget(this);
QHBoxLayout *hLayout = new QHBoxLayout;
txtFileName = new QLineEdit(this);
QPushButton *loadButton = new QPushButton("Load File", this);
connect(loadButton, &QPushButton::clicked, this, &Text_Finder::on_search_clicked);
hLayout->addWidget(txtFileName);
hLayout->addWidget(loadButton);
QVBoxLayout *vLayout = new QVBoxLayout(this);
vLayout->addLayout(hLayout);
txtFileContents = new QTextEdit(this);
vLayout->addWidget(txtFileContents);
ui->setLayout(vLayout);
setCentralWidget(ui);
}
Text_Finder::~Text_Finder(){
// It's not necessary to explicitly delete any widgets.
// QObject implements the Composite Pattern, which takes care of all this automatically
}
void Text_Finder::loadFile(QString const &filename){
QFile inputFile(filename);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString contents = in.readAll();
inputFile.close();
txtFileContents->setPlainText(contents);
}
void Text_Finder::on_search_clicked()
{
QString filename = txtFileName->text();
loadFile(filename);
}
int main(int argc, char **argv){
QApplication app(argc, argv);
Text_Finder w;
w.show();
return app.exec();
}
HINT for future questions: You will get better answers quicker if you include an SSCCE in your question. What I've included in this edit is a suitable example.