Read text file in textedit Qt C++ - c++

I have this text file:
Name 1 Email 1
Name 2 Email 2
Name 3 Email 3
Name 4 Email 4
Name 5 Email 5
This is a list of employees with their emails. I want to make a list in a dialog window with their names displayed there. I thought this was a good way to print out the text file on the dialog window but it isn't working.
employees_dialog.cpp
#include "employees_dialog.h"
#include "ui_employees_dialog.h"
#include <QtCore/QFile>
#include <QtCore/QTextStream>
employees_dialog::employees_dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::employees_dialog)
{
ui->setupUi(this);
getTextFile();
}
employees_dialog::~employees_dialog()
{
delete ui;
}
void employees_dialog::getTextFile()
{
QFile myFile(":/employees.txt");
myFile.open(QIODevice::ReadOnly);
QTextStream textStream(&myFile);
QString line = textStream.readAll();
myFile.close();
ui->textEdit->setPlainText(line);
}
This is the header file.
#ifndef EMPLOYEES_DIALOG_H
#define EMPLOYEES_DIALOG_H
#include <QDialog>
namespace Ui {
class employees_dialog;
}
class employees_dialog : public QDialog
{
Q_OBJECT
public:
explicit employees_dialog(QWidget *parent = 0);
~employees_dialog();
private slots:
private:
Ui::employees_dialog *ui;
void getTextFile();
};
#endif // EMPLOYEES_DIALOG_H
So the textEdit in the UI should display the text file. But it's just blank white. I have the file in Qt Resources File. The debugger doesn't give any errors the application itself is just working fine but the text won't appear in the textEdit.
By the way, I'm new to Qt.

use this:
QFile file( "myfile.txt" );
if ( !file.exists() )
{
qDebug()<<"doesn't exist the file";
}

Related

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 identify the pressed button in Qt C++?

I have 4 buttons on my main window. Each button opens its own window with its own data. How to identify the pressed button to open right window? For example: I press sales button and it opens a window that shows information about ticket sales.
Mainwindow ui
Here is my code from mainwindow h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <sales.h>
#include <theatres.h>
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 button_pressed();
private:
Ui::MainWindow *ui;
sales *s;
theatres *t;
};
#endif // MAINWINDOW_H
And here is my code from mainwindow cpp:
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "build/sqlite/sqlite3.h"
#include <QtSql/QSqlDatabase>
#include <QTableView>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect((*ui).pushButton,SIGNAL(released()), this, SLOT(button_pressed()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::button_pressed()
{
s = new sales(this);
s -> show();
}
As Andy Newman already answered
the shortest solution is a lambda function
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QHBoxLayout *h_layout = new QHBoxLayout;
centralWidget()->setLayout(h_layout);
for(int c =1; c <= 10; c++)
{
QPushButton *button = new QPushButton(this); // create button
button->setText(QString::number(c)); // set button id
h_layout->addWidget(button); // add a button to the form
// lambda magic
/* connecting a button signal to a lambda function that captures a pointer to a
button and invokes an arbitrary type function. */
connect(button, &QPushButton::clicked, [this, button]() {
pressedButton(button->text());
});
}
}
void MainWindow::pressedButton(const QString &id_button)
{
qDebug("Pressed button: %ls", id_button.utf16());
}
MainWindow::~MainWindow()
{
delete ui;
}
#include "widget.h"
#include "./ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->btn_0,&QPushButton::clicked,this,&Widget::SlotButtonClicked);
connect(ui->btn_1,&QPushButton::clicked,this,&Widget::SlotButtonClicked);
connect(ui->btn_2,&QPushButton::clicked,this,&Widget::SlotButtonClicked);
connect(ui->btn_3,&QPushButton::clicked,this,&Widget::SlotButtonClicked);
}
Widget::~Widget()
{
delete ui;
}
void Widget::SlotButtonClicked()
{
auto sender = this->sender();
if ( sender == ui->btn_0 ) {
// Click btn_0 to open widget0
} else if ( sender == ui->btn_1 ) {
// Click btn_1 to open widget1
} else if ( sender == ui->btn_2 ) {
// Click btn_2 to open widget2
} else if ( sender == ui->btn_3 ) {
// Click btn_3 to open widget3
}
}
If you can use Qt Designer, the best way to do this is to click with button right on the QPushButton (On .ui file in Qt Designer) and click to "Go to Slot", this will create a private slot to this button! In the header file will create the definition, like this:
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
And in the source file (.cpp) will create the "function" clicked pushButton:
void MainWindow::on_pushButton_clicked()
{
}
void MainWindow::on_pushButton_2_clicked()
{
}
void MainWindow::on_pushButton_3_clicked()
{
}
void MainWindow::on_pushButton_4_clicked()
{
}
Inside of the "function" in .cpp, you put the task that you want this button to do, in this case, to open a new window!
When you click "go to slot" in another button, will create another private slot with the respective number (If is the second QPushButton that you create, the private slot will be called by pushButton_2).
The usual way to do this would be to connect the 4 different buttons to 4 different slots. It looks like you are using QtDesigner so that shouldn't be an issue.
If you were generating an array of buttons at run time you'd run into problems and would need a different solution. You could try something like this to pass an array index to the function, for example:
connect(button[x], &QPushButton::clicked, this, [this, x]() { button_pressed(x); });
Or you could do it the Qt way, which would be to call ::setProperty to store data in the button, and then retrieve it from the event, but it's so esoteric that I can't actually remember how to do that...

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

QtWidget Convert HTML to PDF

The code below is based on this question.
But I still can't get it to work. From basic debugging I think there is something wrong with passing the filenames to the function. There is no reaction at all when I clicked on the "Print as PDF" button.
The main code is as below. If you would like to see further, feel free to ask them from me. Thanks.
Part of main.cpp
QApplication app(argc, argv);
//Get filename for all documents
QString filename = get_filename(Var_STR);
QString txt = txt_filename(filename);
QString csv = csv_filename(filename);
QString html = html_filename(filename);
//Print report in .txt, .csv and .html accordingly
heading(txt, csv, html, Var_STR, Var_INT[6], Var_INT[16], Var_INT[17]);
pp_prerinse(txt, csv, html, Var_INT[18], Var_INT[19], Var_INT[20], Var_INT[21], Var_INT[22], Var_INT[23], Var_INT[24], Var_INT[25], Var_INT[26], Var_REAL[11], Var_INT[30], Var_INT[31], Var_INT[32]);
pp_wash(txt, csv, html, Var_STR, Var_INT[33], Var_INT[34], Var_INT[35], Var_INT[36], Var_INT[37], Var_INT[38], Var_REAL[23], Var_INT[41], Var_INT[42], Var_INT[43], Var_REAL[28], Var_INT[47], Var_INT[48], Var_INT[49], Var_INT[50], Var_INT[51], Var_INT[52], Var_INT[53], Var_INT[54], Var_INT[55], Var_REAL[40]);
pp_rinse(txt, csv, html, Var_INT[59], Var_INT[60], Var_INT[61], Var_INT[62], Var_INT[63], Var_INT[64], Var_INT[65], Var_INT[66], Var_INT[67], Var_INT[68], Var_INT[69], Var_INT[70], Var_INT[71], Var_INT[72], Var_INT[73], Var_INT[74], Var_INT[75], Var_INT[76], Var_INT[77], Var_REAL[61]);
phase_prerinse(txt, csv, html, Var_STR, Var_REAL[64], Var_REAL[67], Var_REAL[70]);
wash(txt, csv, html, Var_STR, Var_REAL[73], Var_REAL[75], Var_REAL[77], Var_REAL[79], Var_REAL[81], Var_REAL[83], Var_REAL[85], Var_REAL[87], Var_REAL[89], Var_REAL[91], Var_REAL[94], Var_REAL[97]);
rinse(txt, csv, html, Var_INT[129], Var_STR);
basin_flush(txt, csv, html, Var_STR);
alarms_code(txt, csv, html, Var_REAL[100], Var_REAL[103], Var_REAL[106]);
tail(txt, csv, html);
//Report preview UI and convert .html to .pdf
QDir htmlpath = QFileInfo(html).absoluteDir();
MainWindow mainWindow((htmlpath.absolutePath())+"/"+html, filename);
mainWindow.setWindowTitle("Print Preview");
mainWindow.showMaximized();
return app.exec();
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QObject>
#include <QMainWindow>
#include <QWebView>
#include <QUrl>
#include <QPushButton>
#include <QString>
#include "windows.h"
#include <algorithm>
#include "qt_windows.h"
#include "qwindowdefs_win.h"
#include <ShellAPI.h>
namespace Ui
{
class MainWindow;
class QPrinter;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QString previewfile = "", QString file = "", QWidget *parent = 0);
virtual ~MainWindow();
public slots:
void buttonPrint(QString filepath);
void buttonCancel();
private:
QWebView *m_pWebView; //Preview of the report layout
QPushButton *m_button; //Print button
QPushButton *n_button; //Cancel button
QString printfile;
QString filepath;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "stdafx.h"
#include "mainwindow.h"
#include <QPrinter>
#include <QTextDocument>
#include <QTextStream>
#include <QFile>
#include <QDir>
MainWindow::MainWindow(QString previewfile, QString file, QWidget *parent)
: QMainWindow(parent)
{
//Open html version of report
m_pWebView = new QWebView(this);
//Set position and size
m_pWebView->setGeometry(0, 0, 1000, 735);
m_pWebView->load(QUrl::fromLocalFile(previewfile));
//Create "print" button
m_button = new QPushButton("Print as PDF", this);
//Set location of button
m_button->setGeometry(QRect(QPoint(1100, 150), QSize(75, 23)));
//Print button action
connect(m_button, SIGNAL(clicked()), this, SLOT(buttonPrint(file)));
n_button = new QPushButton("Cancel", this);
n_button->setGeometry(QRect(QPoint(1100, 179), QSize(75, 23)));
connect(n_button, SIGNAL(clicked()), this, SLOT(buttonCancel()));
}
void MainWindow::buttonPrint(QString filepath)
{
QFile htmlfile(filepath+".html");
if(htmlfile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QString htmlContent;
QTextStream in(&htmlfile);
htmlContent = in.readAll();
QTextDocument *document = new QTextDocument();
document->setHtml(htmlContent);
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filepath+".pdf");
document->print(&printer);
delete document;
buttonCancel();
}
}
void MainWindow::buttonCancel()
{
QApplication::quit();
}
MainWindow::~MainWindow()
{
}
I recommend you to porting from QTWebKit to QTWebEngine which use Chromium as native browser, faster and newst. Check for details:
http://doc.qt.io/qt-5/qtwebenginewidgets-qtwebkitportingguide.html
With 5.6, Qt WebKit and Qt Quick 1 will no longer be supported and are dropped from the release. Qt 5.7 integrates printsupport for browser so let's try to use Chromium:
First of all, include:
QT += webengine webenginewidgets printsupport
Now, try something like this:
// Create the webview
QWebEngineView *webView = new QWebEngineView(this);
webView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->centralWidget->layout()->addWidget(webView);
// Path to the HTML file
const QString filePath = QFileDialog::getOpenFileName(this, "Import HTML", ".", "HTML Files (*.html)");
// Check if the file exist
QFileInfo fileInfo(filePath);
if (!fileInfo.isFile()) {
qDebug() << "Warning, file not found!";
}
// Preview the HTML file
webView->load(QUrl::fromLocalFile(fileInfo.filePath()));
// How to print the page?
// Get the path to the pdf file
const QString pdfPath = QFileDialog::getSaveFileName(this, "Export to pdf", ".", "PDF Files (*.pdf)");
// Print the page in pdf format
webView->page()->printToPdf(pdfPath);

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.