Qt5/Qt-Creator Opening Files in TextEdit
--D. Thiebaut (talk) 18:30, 24 February 2014 (EST)
This tutorial shows how to create a simple Qt5 GUI window with two buttons and a TextEdit where the contents of a text file is displayed with fixed-size font.
The GUI
- Create a GUI with two buttons, a horizontal spacer, and a textEdit, and group them in a grid.
- Label the two buttons Clear and Go
- Connect the Clicked() signal of the Clear button to the clear() slot of the textEdit.
- Connect the Clicked() signal of the Go button to a new slot of the MainWindow application.
Source Files
The files below are generated automatically by Qt5 Creator. Just the highlighted parts need to be added (but make sure you let Qt5 Creator create the slot on_pushButton_2_clicked() otherwise it will not be called when the button is pressed. A lot of code is generated in the background for this slot to respond to the button's clicked() signal!
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
The highlighted sections show code added to set the font of the textEdit to courier, and to open a file with a dialog and display its contents in the textEdit.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QFile>
#include <QString>
#include <QTextStream>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
QFont font;
font.setFamily("Courier");
font.setStyleHint(QFont::Monospace);
font.setFixedPitch(true);
font.setPointSize(10);
ui->textEdit->setFont(font);
}
MainWindow::~MainWindow() {
delete ui;
}
// SLOT
// Reads a maze and displays it
void MainWindow::on_pushButton_2_clicked() {
QString fileName = QFileDialog::getOpenFileName(this,
"Open Maze File", ".", "Maze files (*.dat)" );
if ( fileName.isEmpty() )
return;
QFile file( fileName );
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in( &file );
while (!in.atEnd()) {
QString line = in.readLine();
ui->textEdit->append( line );
}
}
maze.pro
#-------------------------------------------------
#
# Project created by QtCreator 2014-02-24T16:46:20
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = maze
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui