一、替换对话框
1、替换对话框的需求分析
(1)、可复用软件部件
(2)、查找文本框中指定的字符
(3)、替换单个指定的字符
(4)、替换所有指定的字符
附加需求:点击关闭按钮后隐藏
2、替换对话框的设计与实现(继承自FindDialog)
3、替换对话框的界面布局
4、替换单个目标算法流程
5、MainWindow和ReplaceDialog之间的关系图
#ifndef REPLACEDIALOG_H #define REPLACEDIALOG_H #include "FindDialog.h" class ReplaceDialog : public FindDialog { Q_OBJECT QPushButton m_replaceButton; QPushButton m_replaceAllButton; QLabel m_replaceAsLabel; QLineEdit m_replaceEdit; void initControl(); protected slots: void onReplaceButtonClicked(); void onReplaceAllButtonClicked(); public: explicit ReplaceDialog(QWidget *parent = 0, QPlainTextEdit* pText = NULL); }; #endif // REPLACEDIALOG_H
#include "ReplaceDialog.h" ReplaceDialog::ReplaceDialog(QWidget *parent, QPlainTextEdit* pText) : FindDialog(parent, pText) { initControl(); connect(&m_replaceButton, SIGNAL(clicked()), this, SLOT(onReplaceButtonClicked())); connect(&m_replaceAllButton, SIGNAL(clicked()), this, SLOT(onReplaceAllButtonClicked())); setWindowTitle("替换"); setLayout(&m_gLayout); } void ReplaceDialog::initControl() { m_replaceButton.setText("替换"); m_replaceAllButton.setText("全部替换"); m_replaceAsLabel.setText("替换为: "); m_gLayout.removeWidget(&m_checkBox); m_gLayout.removeWidget(&m_gBox); m_gLayout.removeWidget(&m_cancleButton); m_gLayout.addWidget(&m_replaceAsLabel, 1, 0); m_gLayout.addWidget(&m_replaceEdit, 1, 1); m_gLayout.addWidget(&m_replaceButton, 1, 2); m_gLayout.addWidget(&m_replaceAllButton, 2, 2); m_gLayout.addWidget(&m_checkBox, 3, 0); m_gLayout.addWidget(&m_gBox, 3, 1); m_gLayout.addWidget(&m_cancleButton, 3, 2); } void ReplaceDialog::onReplaceButtonClicked() { QString target = m_findLineEdit.text(); QString to = m_replaceEdit.text(); if(m_plainTextEdit != NULL && target !="" && to != "") { QString text = m_plainTextEdit->toPlainText(); QString selText = m_plainTextEdit->textCursor().selectedText(); if(selText == target) { m_plainTextEdit->insertPlainText(to); } onFindButtonClicked(); } } void ReplaceDialog::onReplaceAllButtonClicked() { QString target = m_findLineEdit.text(); QString to = m_replaceEdit.text(); if(m_plainTextEdit != NULL && target !="" && to != "") { QString text = m_plainTextEdit->toPlainText(); text.replace(target, to, m_checkBox.isChecked()? Qt::CaseSensitive : Qt::CaseInsensitive); m_plainTextEdit->clear(); m_plainTextEdit->setPlainText(text); } }
文本编辑器其它修改的地方:
头文件:
UI文件:
Slots.cpp:
二、小结
(1)、替换对话框的功能涵盖了查找对话框的功能
(2)、替换对话框可以继承自查找对话框
(3)、替换功能的实现是基于查找算法完成的
(4)、替换对话框是一个可复用的软件部件