1. 程式人生 > >Qt學習之路之 QTextEdit 重溫

Qt學習之路之 QTextEdit 重溫

其實,QTextEdit 也有對文字的編輯函式, 剪下,複製,撤銷..... 

看看下面的這個簡單的例子:


控制元件一目瞭然。按鈕 + QTextedit 物件 , 垂直佈局。

--------------------------------------------------

環境:Windows 8.1

QT版本:5.4.0

開發環境:VS2013

---------------------------------------------------

程式碼:

標頭檔案

#ifndef EDIT_WIDGET
#define EDIT_WIDGET

#include <QTextEdit>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>

class EditWidget : public QWidget
{
	Q_OBJECT
public:
		explicit EditWidget(QWidget *parent = 0);
		~EditWidget();

private:
	QTextEdit *textEdit;
	///-----------------
	QPushButton *cutBtn;
	QPushButton *copyBtn;
	QPushButton *undoBtn;
	QPushButton *pasteBtn;
	QPushButton *selectAllBtn;
};

#endif	//EDIT_WIDGET
.cpp檔案
#include "eidt_widget.h"

EditWidget::EditWidget(QWidget *parent /*= 0*/) :QWidget(parent)
{
	//---視窗大小  
	resize(600, 400);
	///---設定視窗標題
	setWindowTitle("QTextEdit");

	///------ 例項化 QTextEdit
	textEdit = new QTextEdit();
	textEdit->setFixedSize(600, 400);

	///---------------------------------------------
	cutBtn = new QPushButton("cut");
	copyBtn = new QPushButton("copy");
	pasteBtn = new QPushButton("paste");
	undoBtn = new QPushButton("undo");
	selectAllBtn = new QPushButton("select All");

	///---繫結訊號與槽
	QObject::connect(cutBtn, SIGNAL(clicked()), textEdit, SLOT(undo()));
	QObject::connect(copyBtn, SIGNAL(clicked()), textEdit, SLOT(copy()));
	QObject::connect(pasteBtn, SIGNAL(clicked()), textEdit, SLOT(paste()));
	QObject::connect(undoBtn, SIGNAL(clicked()), textEdit, SLOT(undo()));
	QObject::connect(selectAllBtn, SIGNAL(clicked()), textEdit, SLOT(selectAll()));


	///---水平佈局按鈕
	QHBoxLayout *hLayout = new QHBoxLayout();
	hLayout->addWidget(copyBtn);
	hLayout->addWidget(cutBtn);
	hLayout->addWidget(pasteBtn);
	hLayout->addWidget(undoBtn);
	hLayout->addWidget(selectAllBtn);
	hLayout->setSpacing(10);
	hLayout->setContentsMargins(10, 10, 10, 10);

	///----將按鈕 ,  textEdit 垂直佈局
	QVBoxLayout *vLayout = new QVBoxLayout();
	vLayout->addLayout(hLayout);
	vLayout->addWidget(textEdit);
	vLayout->setSpacing(10);
	vLayout->setContentsMargins(10, 10, 10, 10);

	///---顯示佈局
	this->setLayout(vLayout);
}

///---解構函式 
EditWidget::~EditWidget()
{

}

main.cpp
#include <QtWidgets/QApplication>
#include "eidt_widget.h"

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);

	EditWidget win;
	win.show();

	return a.exec();
}

這裡只是枚舉了簡單的幾項操作,關於QTextEdit 對文字的字型選擇,字型顏色等操作,請參考QT Assistant