1.在mainwindow.cpp添加工具按钮
//添加工具按钮
QAction *action_textTable = new QAction("表格",this);
QAction *action_textList = new QAction("列表",this);
QAction *action_textIamge = new QAction("图片",this);
//进行连接
connect(action_textTable,&QAction::triggered,
this,&MainWindow::insertTable);
connect(action_textList,&QAction::triggered,
this,&MainWindow::insertList);
connect(action_textIamge,&QAction::triggered,
this,&MainWindow::insertIamge);
//添加到工具栏上
ui->mainToolBar->addAction(action_textTable);
ui->mainToolBar->addAction(action_textList);
ui->mainToolBar->addAction(action_textIamge);
2.在头文件里面添加槽函数
void insertTable(); //插入表格
void insertList(); //插入列表
void insertIamge(); //插入图片
3.对槽函数进行定义
void MainWindow::insertTable()
{
//对文本进行操作首先要获取光标
QTextCursor cursor = ui->textEdit->textCursor();
QTextTableFormat format; //表格格式
format.setCellSpacing(2); //表格外边白
format.setCellPadding(10); //表格内边白
cursor.insertTable(3,3,format); //三行三列
}
void MainWindow::insertList()
{
//列表格式
QTextListFormat format;
//数字编号
format.setStyle(QTextListFormat::ListDecimal);
ui->textEdit->textCursor().insertList(format);
}
void MainWindow::insertIamge()
{
QString filepath = QFileDialog::getOpenFileName(this,
"选择图片",
".",
"JPEG(*.jpg *.jpeg);;"
"GIF(*.gif);;"
"PNG(*.png)");
QUrl url(QString("file://%1").arg(filepath));
QImage image = QImageReader(filepath).read();
QTextDocument* document = ui->textEdit->document();
//文档添加图片资源
document->addResource(QTextDocument::ImageResource,
url,QVariant(image));
QTextCursor cursor = ui->textEdit->textCursor();
QTextImageFormat imgFormat;
imgFormat.setWidth(image.width());
imgFormat.setHeight(image.height());
imgFormat.setName(url.toString());
cursor.insertImage(imgFormat);
}