The code in this example compares the three built in GUI widgets which are used to edit text. Each of these controls offers slightly different functionality and features.
#include <QtCore>
#include <QtGui>
class MainWindow : public QWidget
{
public:
MainWindow();
};
The only required declaration is the MainWindow() constructor.
MainWindow::MainWindow()
{
setMinimumSize(600, 400);
//
QLabel *label_1 = new QLabel("Line Edit:");
QLineEdit *text_1 = new QLineEdit();
text_1->setText("Single line of text");
//
QLabel *label_2 = new QLabel("Text Edit:");
QTextEdit *text_2 = new QTextEdit();
text_2->setText(
"Multiple lines using html text formatting."
"<br>"
"<span style=\"color:#aa00ff;\">"
"Show text in magenta</span>"
"<br>"
"<span style=\"font-size:10pt;\">"
"Set 10 pt font</span>");
text_2->setMaximumHeight(100);
//
QLabel *label_3 = new QLabel("Plain Text:");
QPlainTextEdit *text_3 = new QPlainTextEdit();
text_3->setPlainText("Multiple lines, no formatting");
text_3->setMaximumHeight(100);
QPushButton *pb_1 = new QPushButton();
pb_1->setText("Close");
QGridLayout *layout1 = new QGridLayout();
layout1->setVerticalSpacing(20);
layout1->addWidget(label_1, 0, 1);
layout1->addWidget(text_1, 0, 2);
layout1->addWidget(label_2, 1, 1, Qt::AlignTop);
layout1->addWidget(text_2, 1, 2);
layout1->addWidget(label_3, 2, 1, Qt::AlignTop);
layout1->addWidget(text_3, 2, 2);
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->addStretch();
layout2->addWidget(pb_1);
layout2->addStretch();
QVBoxLayout *layoutMain = new QVBoxLayout(this);
layoutMain->setContentsMargins(45, 35, 45, 15);
layoutMain->addLayout(layout1);
layoutMain->addSpacing(20);
layoutMain->addLayout(layout2);
connect(pb_1, &QPushButton::clicked,
this, &QWidget::close);
}
There are three different widgets which can be used to add or edit text in a GUI application. The QLineEdit class declared on line 8 is the most basic control. It allows the user to enter a single line of non-formatted text. This is the most commonly used text edit control.
On line 14 is the declaration for a QTextEdit widget. This control offers the most features and flexibility. It supports multiple lines of text and a subset of HTML tags like line breaks, span, lists, and tables. For a full list of the supported formatting commands, refer to the API documentation.
The QPlainTextEdit declared on line 28 is also multi line however you can not specify any formatting commands.
These widgets can be used on any user interface form in any combination.
Main Function
Since the source code for main() has not changed there is no need to show it again. Refer to example 3 or download the full source for this example.
Running the Example
To build and run this example use the same CMake build file and commands as we showed for the first example. The only suggested modification is on line 2 of the CMakeLists.txt file, change “example_1” to “example_18”.