1.在mainwindow.h 添加声明
cpp
class QLineEdit;
class QDialog;
void textFind(); //查找文本
void textNext(); //查找下一个
2.在cpp里面进行添加、布局、定义
添加查找和布局窗口
cpp
//查找
QAction *action_textfind = new QAction("查找",this);
connect(action_textfind,&QAction::triggered,
this,&MainWindow::textFind);
ui->mainToolBar->addAction(action_textfind);
m_findDialg = new QDialog(this); //查找对话框
m_lineEdit = new QLineEdit(m_findDialg); //查找输入框
QPushButton *btn = new QPushButton(m_findDialg);
btn->setText("查找下一个");
connect(btn,&QPushButton::clicked,
this,&MainWindow::textNext);
//进行垂直布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_lineEdit);
layout->addWidget(btn);
m_findDialg->setLayout(layout);
对第一步的声明进行定义
cpp
void MainWindow::textFind()
{
m_findDialg->show();
}
void MainWindow::textNext()
{
QString strFind = m_lineEdit->text();
bool isFind = ui->textEdit->find(strFind,QTextDocument::FindBackward);
if(isFind){
qDebug()<<QString("行号:%1,列号:%2")
.arg(ui->textEdit->textCursor().blockNumber())
.arg(ui->textEdit->textCursor().columnNumber());
}
}