Introduction to QTextEdit
QTextEdit is an advanced text viewer, editor that can display images, lists and tables. In industry, TextEditu is generally used for windows that display textual information. The parent class of QTextEdit is QAbstractScrollArea. When the text information is too large, it will automatically adjust the display interface through the scroll bar.
Common APIs
Set the text alignment, the alignment is Qt::AlignLeft, Qt::AlignRight, Qt::AlignJustify and Qt::AlignCenter (horizontal center).
void setAlignment()
Format the current font
void setCurrentFont(const QFont &f)```
set font size
void setFontPointSize(qreal s)
Set the background color of the text
void setTextBackgroundColor(const QColor &c)
set font color
void setTextColor(const QColor &c)
Insert text at the current position of the cursor
void insertPlainText(const QString &text)
Append text, it appends text directly after text regardless of cursor position (starts on a new line)
void append(const QString &text)
clear all text
void clear()
set read-only mode
void setReadOnly(bool ro)
Effect
.h file
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_btn_append_clicked();
void on_btn_insert_clicked();
void on_btn_clear_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
.cpp file
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//设置文本对齐方式
ui->textEdit->setAlignment(Qt::AlignVCenter);
//设置只读模式
ui->textEdit->setReadOnly(true);
//设置字体大小
ui->textEdit->setFontPointSize(20.0);
//设置字体颜色
ui->textEdit->setTextColor(QColor(45,30,20));
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btn_append_clicked()
{
//设置文本背景颜色
ui->textEdit->setTextBackgroundColor(QColor(145,160,110));
QString str = ui->lineEdit->text();
ui->textEdit->append(str);
}
void Widget::on_btn_insert_clicked()
{
//设置文本背景颜色
ui->textEdit->setTextBackgroundColor(QColor(245,230,220));
QString str = ui->lineEdit_2->text();
ui->textEdit->insertPlainText(str);
}
void Widget::on_btn_clear_clicked()
{
ui->textEdit->clear();
}
ui layout