最近在自学Qt,利用闲暇时间写了一个非常简单的写字板,可以实现文字编辑,文字查找,显示当前行号并高亮的功能。

实现主窗口的notemainwindow类

notemainwindow.h

 

 
  
  1. #ifndef NOTEMAINWINDOW_H 
  2. #define NOTEMAINWINDOW_H 
  3. #include <QtGui> 
  4. #include "finddialog.h" 
  5. #include "editor.h" 
  6. QT_BEGIN_NAMESPACE 
  7. class QAction; 
  8. class QLabel; 
  9. class QMenu; 
  10. class QPlainTextEdit; 
  11. class FindDialog; 
  12. QT_END_NAMESPACE 
  13.  
  14. class NoteMainWindwow : public QMainWindow 
  15.     Q_OBJECT 
  16. public
  17.     NoteMainWindwow(); 
  18.  
  19.  
  20. protected
  21.     void  closeEvent(QCloseEvent *event); 
  22.     void dragEnterEvent(QDragEnterEvent *event); 
  23.     void dropEvent(QDropEvent *event); 
  24.  
  25.  
  26. private slots: 
  27.     void newFile(); 
  28.     void open(); 
  29.     bool save(); 
  30.     bool saveAs(); 
  31.  
  32.     void windowModified(); 
  33.     void about(); 
  34.     void setColor(); 
  35.     void setFont(); 
  36.  
  37.  
  38.     void find(); 
  39.     void findStr(const QString &str); 
  40.  
  41.  
  42. private
  43.     void createActions(); 
  44.     void createMenus(); 
  45. //    void createContextMenu(); 
  46.     void createToolBars(); 
  47.     void createStatusBar(); 
  48.     void readSettings(); 
  49.     void writeSettings(); 
  50.     bool okToContinue(); 
  51.     bool loadFile(const QString &fileName); 
  52.     bool saveFile(const QString &fileName); 
  53.     void setCurrentFile(const QString &fileName); 
  54.     QString strippedName(const QString &fullFileName); 
  55.  
  56.      CodeEditor  *textEdit; //find string 
  57.  
  58.     QAction *newAction; 
  59.     QAction *openAction; 
  60.     QAction *saveAction; 
  61.     QAction *saveAsAction; 
  62.     QAction *exitAction; 
  63.  
  64.     QAction *copyAction; 
  65.     QAction *pasteAction; 
  66.     QAction *cutAction; 
  67.     QAction *aboutAction; 
  68.     QAction *aboutQtAction; 
  69.  
  70.     QAction *findAction; 
  71.  
  72.     QAction *colorAction; 
  73.     QAction *fontAction; 
  74.  
  75.     QMenu *fileMenu; 
  76.     QMenu *editMenu; 
  77.     QMenu *helpMenu; 
  78.     QMenu *toolMenu; 
  79.  
  80.     QToolBar *fileToolBar; 
  81.     QToolBar *editToolBar; 
  82.  
  83.     QString curFile; 
  84.  
  85.     FindDialog *findDialog; 
  86.     bool isFirstTime; 
  87.     QWidget lineNumberArea; 
  88. //    QStringList recentFile; 
  89. //    enum{MaxRecentFile=5}; 
  90.  
  91. }; 
  92.  
  93. #endif 

notemainwindow.cpp

 

 
  
  1. #include "notemainwindwow.h" 
  2. NoteMainWindwow::NoteMainWindwow() 
  3.        textEdit=new CodeEditor; 
  4.  
  5.        setCentralWidget(textEdit); 
  6.  
  7.        createActions(); 
  8.        createMenus(); 
  9. //       createContextMenu(); 
  10.        createToolBars(); 
  11.        createStatusBar(); 
  12.  
  13.        readSettings(); 
  14.  
  15.        connect(textEdit->document(),SIGNAL(contentsChanged()),this,SLOT(windowModified())); 
  16.  
  17.        setCurrentFile(""); 
  18.  
  19.        findDialog=0; 
  20.  
  21.        setFixedSize(850,550); 
  22.        setMaximumSize(900,700); 
  23.        setWindowIcon(QIcon(":/p_w_picpaths/note.png")); 
  24.  
  25.        isFirstTime=true
  26.  
  27.        setAcceptDrops(true); 
  28.        textEdit->setAcceptDrops(false); 
  29.  
  30.  
  31.  
  32. void NoteMainWindwow::createActions() 
  33.         newAction=new QAction(tr("&New"),this); 
  34.         newAction->setIcon(QIcon(":/p_w_picpaths/new.png")); 
  35.         newAction->setShortcut(QKeySequence::New); 
  36.         newAction->setStatusTip(tr("Create new file")); 
  37.         connect(newAction,SIGNAL(triggered()),this,SLOT(newFile())); 
  38.  
  39.         copyAction=new QAction(tr("&Copy"),this); 
  40.         copyAction->setIcon(QIcon(":/p_w_picpaths/copy.png")); 
  41.         copyAction->setShortcuts(QKeySequence::Copy); 
  42.         connect(copyAction,SIGNAL(triggered()),textEdit,SLOT(copy())); 
  43.  
  44.         pasteAction=new QAction(tr("&Paste"),this); 
  45.         pasteAction->setIcon(QIcon(":/p_w_picpaths/paste.png")); 
  46.         pasteAction->setShortcut(QKeySequence::Paste); 
  47.         connect(pasteAction,SIGNAL(triggered()),textEdit,SLOT(paste())); 
  48.  
  49.         cutAction=new QAction(tr("C&ut"),this); 
  50.         cutAction->setIcon(QIcon(":/p_w_picpaths/cut.png")); 
  51.         cutAction->setShortcut(QKeySequence::Cut); 
  52.         connect(cutAction,SIGNAL(triggered()),textEdit,SLOT(cut())); 
  53.  
  54.         saveAction=new QAction(tr("&Save"),this); 
  55.         saveAction->setIcon(QIcon(":/p_w_picpaths/save.png")); 
  56.         saveAction->setShortcut(QKeySequence::Save); 
  57.         saveAction->setStatusTip(tr("Save the file")); 
  58.         connect(saveAction,SIGNAL(triggered()),this,SLOT(save())); 
  59.  
  60.         saveAsAction=new QAction(tr("*save &As"),this); 
  61.         saveAsAction->setIcon(QIcon(":/p_w_picpaths/save.png")); 
  62.         saveAsAction->setShortcut(QKeySequence::SaveAs); 
  63.         connect(saveAsAction,SIGNAL(triggered()),this,SLOT(saveAs())); 
  64.  
  65.         openAction=new QAction(tr("&Open"),this); 
  66.         openAction->setIcon(QIcon(":/p_w_picpaths/open.png")); 
  67.         openAction->setShortcut(QKeySequence::Open); 
  68.         connect(openAction,SIGNAL(triggered()),this,SLOT(open())); 
  69.  
  70.         aboutAction=new QAction(tr("&About"),this); 
  71.         connect(aboutAction,SIGNAL(triggered()),this,SLOT(about())); 
  72.  
  73.         aboutQtAction=new QAction(tr("about &Qt"),this); 
  74.         connect(aboutQtAction,SIGNAL(triggered()),qApp,SLOT(aboutQt())); 
  75.  
  76.         colorAction=new QAction(tr("&Color"),this); 
  77.         colorAction->setIcon(QIcon(":/p_w_picpaths/color.png")); 
  78.         connect(colorAction,SIGNAL(triggered()),this,SLOT(setColor())); 
  79.  
  80.         fontAction=new QAction(tr("&Font"),this); 
  81.         fontAction->setIcon(QIcon(":/p_w_picpaths/font.png")); 
  82.         connect(fontAction,SIGNAL(triggered()),this,SLOT(setFont())); 
  83.  
  84.         exitAction=new QAction(tr("&Exit"),this); 
  85.         exitAction->setIcon(QIcon(":/p_w_picpaths/exit.png")); 
  86.         connect(exitAction,SIGNAL(triggered()),this,SLOT(close())); 
  87.  
  88.  
  89.         findAction=new QAction(tr("&Find"),this); 
  90.         findAction->setIcon(QIcon(":/p_w_picpaths/find.png")); 
  91.         connect(findAction,SIGNAL(triggered()),this,SLOT(find())); 
  92.  
  93.         cutAction->setEnabled(false); 
  94.         copyAction->setEnabled(false); 
  95. //        fontAction->setEnabled(false); 
  96. //        fontAction->setEnabled(false); 
  97.         connect(textEdit, SIGNAL(copyAvailable(bool)), 
  98.                 cutAction, SLOT(setEnabled(bool))); 
  99.         connect(textEdit, SIGNAL(copyAvailable(bool)), 
  100.                 copyAction, SLOT(setEnabled(bool))); 
  101. //        connect(textEdit,SIGNAL(copyAvailable(bool)),fontAction,SLOT(setEnabled(bool))); 
  102. //        connect(textEdit,SIGNAL(copyAvailable(bool)),colorAction,SLOT(setEnabled(bool))); 
  103.  
  104.  
  105. void NoteMainWindwow::createMenus() 
  106.         fileMenu=menuBar()->addMenu(tr("&File")); 
  107.         fileMenu->addAction(openAction); 
  108.         fileMenu->addAction(newAction); 
  109.         fileMenu->addAction(saveAction); 
  110.         fileMenu->addAction(saveAsAction); 
  111.         fileMenu->addAction(exitAction); 
  112.  
  113.         editMenu=menuBar()->addMenu(tr("&Edit")); 
  114.         editMenu->addAction(copyAction); 
  115.         editMenu->addAction(cutAction); 
  116.         editMenu->addAction(pasteAction); 
  117.         editMenu->addAction(colorAction); 
  118.         editMenu->addAction(fontAction); 
  119. //        editMenu->addAction(findAction); 
  120.  
  121.         menuBar()->addSeparator(); 
  122.  
  123.         toolMenu=menuBar()->addMenu(tr("&Tool")); 
  124.         toolMenu->addAction(findAction); 
  125.  
  126.         helpMenu=menuBar()->addMenu(tr(("&Help"))); 
  127.         helpMenu->addAction(aboutAction); 
  128.         helpMenu->addAction(aboutQtAction); 
  129.  
  130.  
  131. //void NoteMainWindwow::createContextMenu() 
  132. //{ 
  133. //        addAction(cutAction); 
  134. //        addAction(copyAction); 
  135. //        addAction(pasteAction); 
  136. //        addAction(colorAction); 
  137. //        setContextMenuPolicy(Qt::ActionsContextMenu); 
  138. //} 
  139.  
  140. void NoteMainWindwow::createToolBars() 
  141.         fileToolBar=addToolBar(tr("&File")); 
  142.         fileToolBar->addAction(newAction); 
  143.         fileToolBar->addAction(openAction); 
  144.         fileToolBar->addAction(saveAction); 
  145.  
  146.         editToolBar=addToolBar(tr("&Edit")); 
  147.         editToolBar->addAction(copyAction); 
  148.         editToolBar->addAction(cutAction); 
  149.         editToolBar->addAction(pasteAction); 
  150.         editToolBar->addAction(colorAction); 
  151.         editToolBar->addAction(fontAction); 
  152.         editToolBar->addAction(findAction); 
  153.  
  154.  
  155. void NoteMainWindwow::createStatusBar() 
  156.    statusBar()->showMessage(tr("Ready")); 
  157.  
  158. void NoteMainWindwow::readSettings() 
  159.         QSettings settings("Software Inc.","Notepad"); 
  160.         QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); 
  161.         QSize size = settings.value("size", QSize(400, 400)).toSize(); 
  162.         resize(size); 
  163.         move(pos); 
  164.  
  165. void NoteMainWindwow::writeSettings() 
  166.         QSettings settings("Trolltech""Application Example"); 
  167.         settings.setValue("pos", pos()); 
  168.         settings.setValue("size", size()); 
  169.  
  170. bool NoteMainWindwow::okToContinue() 
  171.         if(textEdit->document()->isModified()){ 
  172.                 int r=QMessageBox::warning(this,tr("Notepad"),tr("The text has been modified.\n""Do you want to save your changes?"),QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel); 
  173.                 if(r==QMessageBox::Save) 
  174.                 {        return save(); 
  175.                }else if(r==QMessageBox::Cancel){ 
  176.                         return false
  177.                 } 
  178.         } 
  179.         return true
  180.  
  181. bool NoteMainWindwow::loadFile(const QString &fileName) 
  182.         QFile file(fileName); 
  183.         if(!file.open(QIODevice::ReadOnly)){ 
  184.                 QMessageBox::warning(this,tr("Notepad"),tr("Can't open the file %1:\n %2.").arg(file.fileName()).arg(file.errorString())); 
  185.                 return false
  186.         } 
  187.  
  188.         QTextStream in(&file); 
  189.  
  190. #ifndef QT_NO_CURSOR 
  191.     QApplication::setOverrideCursor(Qt::WaitCursor); 
  192. #endif 
  193.     textEdit->setPlainText(in.readAll()); 
  194. #ifndef QT_NO_CURSOR 
  195.     QApplication::restoreOverrideCursor(); 
  196. #endif 
  197.  
  198.     setCurrentFile(fileName); 
  199.     statusBar()->showMessage(tr("loaded %1").arg(fileName),2000); 
  200.  
  201.     return 0; 
  202.  
  203.  
  204. bool NoteMainWindwow::saveFile(const QString &fileName) 
  205.         QFile file(fileName); 
  206.         if(!file.open(QIODevice::WriteOnly)){ 
  207.                 QMessageBox::warning(this,tr("Notepad"),tr("Can't write file %1 \n %2").arg(file.fileName()).arg(file.errorString())) ; 
  208.                 return false
  209.         } 
  210.  
  211.         QTextStream out(&file); 
  212. #ifndef QT_NO_CURSOR 
  213.     QApplication::setOverrideCursor(Qt::WaitCursor); 
  214. #endif 
  215.     out<<textEdit->toPlainText(); 
  216. #ifndef QT_NO_CURSOR 
  217.     QApplication::restoreOverrideCursor(); 
  218. #endif 
  219.  
  220.        setCurrentFile(fileName); 
  221.       statusBar()->showMessage(tr("Saved file %1").arg(fileName)); 
  222.  
  223.        return 0; 
  224.  
  225. void NoteMainWindwow::setCurrentFile(const QString &fileName) 
  226.         curFile=fileName; 
  227.  
  228.         textEdit->document()->setModified(false); 
  229.         setWindowModified(false); 
  230.  
  231.         QString showname=tr("Untitled"); 
  232.         if(!curFile.isEmpty()){ 
  233.                 showname=strippedName(curFile); 
  234.         } 
  235.         setWindowTitle(tr("%1[*] - %2").arg(showname).arg(tr("Notepad"))); 
  236.  
  237. QString NoteMainWindwow::strippedName(const QString &fullFileName) 
  238.         return QFileInfo(fullFileName).fileName(); 
  239.  
  240. void  NoteMainWindwow::newFile() 
  241.         if(okToContinue()){ 
  242.                 textEdit->clear(); 
  243.                 setCurrentFile(""); 
  244.         } 
  245.  
  246. void  NoteMainWindwow::open() 
  247.         if(okToContinue()){ 
  248.                 QString filename=QFileDialog::getOpenFileName(this,tr("Open notepad"),"/",tr("text file(*.*)")); 
  249.                 if(!filename.isEmpty()){ 
  250.                         loadFile(filename); 
  251.  
  252.                 } 
  253.         } 
  254.  
  255.  
  256. bool NoteMainWindwow::save() 
  257.         if(curFile.isEmpty()){ 
  258.                 return saveAs(); 
  259.         }else
  260.                 return saveFile(curFile); 
  261.         } 
  262.  
  263. bool NoteMainWindwow::saveAs() 
  264.         QString fileName=QFileDialog::getSaveFileName(this,tr("Save document"),"/",tr("text file(*.text)")); 
  265.         if(fileName.isEmpty()) 
  266.         { 
  267.                 return false
  268.         } 
  269.         return saveFile(fileName); 
  270.  
  271. //void NoteMainWindwow::copy() 
  272. //{ 
  273. //        QString str=copy(); 
  274. //        QApplication::clipboard()->setText(str); 
  275. //} 
  276.  
  277.  
  278. //void NoteMainWindwow::paste() 
  279. //{ 
  280. //        QString str=QApplication::clipboard()->text(); 
  281.  
  282. //} 
  283.  
  284. //void NoteMainWindwow::cut() 
  285. //{ 
  286. //        copy(); 
  287. //        del(); 
  288. //} 
  289.  
  290. void NoteMainWindwow::windowModified() 
  291.         setWindowModified(textEdit->document()->isModified()); 
  292.  
  293.  
  294. //void NoteMainWindwow::del() 
  295. //{ 
  296.  
  297. //} 
  298.  
  299. void NoteMainWindwow::about() 
  300.         QMessageBox::about(this,tr("About Notepad"),tr("<h2>Notepad 1.0</h2>" 
  301.                                                        "<p>Copyright &copy; Awind Software Inc." 
  302.                                                        "<p>Notepad is a small application that" 
  303.                                                        "demonstrates QAction,QMainWindow,QMenuBar," 
  304.                                                        "QStatusBar,QToolBar and many other" 
  305.                                                        "Qt classes.")); 
  306.  
  307. void NoteMainWindwow::closeEvent(QCloseEvent *event) 
  308.         if(okToContinue()){ 
  309.                 writeSettings(); 
  310.                 if(findDialog){ 
  311.                         delete findDialog; 
  312.                 } 
  313.                 event->accept(); 
  314.         }else
  315.                 event->ignore(); 
  316.         } 
  317.  
  318. void NoteMainWindwow::setColor() 
  319.         QPalette palette=textEdit->palette(); 
  320.         const QColor &color=QColorDialog::getColor(palette.color(QPalette::Base),this); 
  321.         if(color.isValid()){ 
  322.                palette.setColor(QPalette::Text,color); 
  323.                textEdit->setPalette(palette); 
  324.         } 
  325.  
  326. void NoteMainWindwow::setFont() 
  327.         bool ok; 
  328.         QFont font=QFontDialog::getFont(&ok,QFont("symbol",10),this); 
  329.         if(ok){ 
  330.                 textEdit->setFont(font); 
  331.         } 
  332.  
  333. void NoteMainWindwow::find() 
  334.         if(!findDialog){ 
  335.                 findDialog=new FindDialog(); 
  336.                 connect(findDialog,SIGNAL(findStr(QString)),this,SLOT(findStr(QString))); 
  337.         } 
  338.  
  339.         findDialog->show(); 
  340.         findDialog->raise(); 
  341.         findDialog->activateWindow(); 
  342.  
  343.  
  344.  
  345. void NoteMainWindwow::findStr(const QString &str) 
  346. //        QString searchString=findDialog->str(); 
  347.         QTextDocument *document=textEdit->document(); 
  348.  
  349.         bool found=false
  350.         if (isFirstTime == false
  351.             document->undo(); 
  352.  
  353.         QTextCursor highlightCursor(document); 
  354.         QTextCursor cursor(document); 
  355.  
  356.         cursor.beginEditBlock(); 
  357.  
  358.         QTextCharFormat plainFormat(highlightCursor.charFormat()); 
  359.         QTextCharFormat colorFormat=plainFormat; 
  360.         colorFormat.setForeground(Qt::red); 
  361.  
  362.          while(!highlightCursor.isNull()&&!highlightCursor.atEnd()){ 
  363.                   highlightCursor=document->find(str,highlightCursor,QTextDocument::FindWholeWords); 
  364.  
  365.                    if(!highlightCursor.isNull()){ 
  366.                                  found=true
  367.                                  highlightCursor.movePosition(QTextCursor::WordRight,QTextCursor::KeepAnchor); 
  368.                                  highlightCursor.mergeCharFormat(colorFormat); 
  369.                           } 
  370.  
  371.                   } 
  372.                   cursor.endEditBlock(); 
  373.  
  374.  
  375.                   isFirstTime = false
  376.  
  377.                   if (found == false) { 
  378.                       QMessageBox::information(this, tr("Word Not Found"), 
  379.                           "Sorry, the word cannot be found."); 
  380.           } 
  381.  
  382. void NoteMainWindwow::dragEnterEvent(QDragEnterEvent *event) 
  383.         if(event->mimeData()->hasFormat("text/uri-list")) 
  384.                 event->acceptProposedAction(); 
  385.  
  386. void NoteMainWindwow::dropEvent(QDropEvent *event) 
  387.         QList<QUrl> urls=event->mimeData()->urls(); 
  388.         if(urls.isEmpty()) 
  389.                 return ; 
  390.  
  391.         QString fileName=urls.first().toLocalFile(); 
  392.  
  393.         if(fileName.isEmpty()) 
  394.                 return ; 
  395.         if(loadFile(fileName)) 
  396.                 setWindowTitle(tr("%1 - %2").arg(fileName).arg(tr("Drag File"))); 
  397.                 setCurrentFile(fileName); 
  398.  


用于实现文本编辑的editor.h,其中CodeEditor类继承了QPlainText类
 

 
  
  1. #ifndef CODEEDITOR_H 
  2. #define CODEEDITOR_H 
  3.  
  4. #include <QPlainTextEdit> 
  5. #include <QtGui> 
  6.  
  7. QT_BEGIN_NAMESPACE 
  8. class QPaintEvent; 
  9. class QResizeEvent; 
  10. class QSize; 
  11. class QWidget; 
  12. QT_END_NAMESPACE 
  13.  
  14. class LineNumberArea; 
  15.  
  16. //![codeeditordefinition] 
  17.  
  18. class CodeEditor : public QPlainTextEdit 
  19.     Q_OBJECT 
  20.  
  21. public
  22.     CodeEditor(QWidget *parent=0); 
  23.  
  24.     void lineNumberAreaPaintEvent(QPaintEvent *event); 
  25.     int lineNumberAreaWidth(); 
  26.  
  27. protected
  28.     void resizeEvent(QResizeEvent *event); 
  29.  
  30. private slots: 
  31.     void updateLineNumberAreaWidth(int newBlockCount); 
  32.     void highlightCurrentLine(); 
  33.     void updateLineNumberArea(const QRect &, int); 
  34.  
  35. private
  36.     QWidget *lineNumberArea; 
  37. }; 
  38.  
  39.  
  40. class LineNumberArea:public QWidget 
  41. public
  42.     LineNumberArea(CodeEditor *editor) : QWidget(editor) { 
  43.         codeEditor = editor; 
  44.     } 
  45.  
  46.     QSize sizeHint() const { 
  47.         return QSize(codeEditor->lineNumberAreaWidth(), 0); 
  48.     } 
  49.  
  50. protected
  51.     void paintEvent(QPaintEvent *event) { 
  52.         codeEditor->lineNumberAreaPaintEvent(event); 
  53.     } 
  54.  
  55. private
  56.     CodeEditor *codeEditor; 
  57. }; 
  58. #endif 


editor.cpp

 
  
  1. #include <QtGui> 
  2.  
  3. #include "editor.h" 
  4.  
  5. CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent) 
  6.     lineNumberArea = new LineNumberArea(this); 
  7.  
  8.     connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); 
  9.     connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); 
  10.     connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); 
  11.  
  12.     updateLineNumberAreaWidth(0); 
  13.     highlightCurrentLine(); 
  14.  
  15.  
  16.  
  17. int CodeEditor::lineNumberAreaWidth() 
  18.     int digits = 1; 
  19.     int max = qMax(1, blockCount()); 
  20.     while (max >= 10) { 
  21.         max /= 10; 
  22.         ++digits; 
  23.     } 
  24.  
  25.     int space = 10 + fontMetrics().width(QLatin1Char('9')) * digits; 
  26.  
  27.     return space; 
  28.  
  29.  
  30.  
  31. void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */
  32.     setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); 
  33.  
  34.  
  35.  
  36. void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) 
  37.     if (dy) 
  38.         lineNumberArea->scroll(0, dy); 
  39.     else 
  40.         lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); 
  41.  
  42.     if (rect.contains(viewport()->rect())) 
  43.         updateLineNumberAreaWidth(0); 
  44.  
  45.  
  46.  
  47. void CodeEditor::resizeEvent(QResizeEvent *e) 
  48.     QPlainTextEdit::resizeEvent(e); 
  49.  
  50.     QRect cr = contentsRect(); 
  51.     lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); 
  52.  
  53.  
  54.  
  55. void CodeEditor::highlightCurrentLine() 
  56.     QList<QTextEdit::ExtraSelection> extraSelections; 
  57.  
  58.     if (!isReadOnly()) { 
  59.         QTextEdit::ExtraSelection selection; 
  60.  
  61.         QColor lineColor = QColor(Qt::yellow).lighter(160); 
  62.  
  63.         selection.format.setBackground(lineColor); 
  64.         selection.format.setProperty(QTextFormat::FullWidthSelection, true); 
  65.         selection.cursor = textCursor(); 
  66.         selection.cursor.clearSelection(); 
  67.         extraSelections.append(selection); 
  68.     } 
  69.  
  70.     setExtraSelections(extraSelections); 
  71.  
  72.  
  73.  
  74. void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) 
  75.     QPainter painter(lineNumberArea); 
  76.     painter.fillRect(event->rect(), Qt::lightGray); 
  77.  
  78.  
  79. //    QTextBlock block = firstVisibleBlock(); 
  80. //    int blockNumber = block.blockNumber(); 
  81. //    int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); 
  82. //    int bottom = top + (int) blockBoundingRect(block).height(); 
  83.  
  84. //    while (block.isValid() && top <= event->rect().bottom()) { 
  85. //        if (block.isVisible() && bottom >= event->rect().top()) { 
  86. //            QString number = QString::number(blockNumber + 1); 
  87. //            painter.setPen(Qt::black); 
  88. //            painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), 
  89. //                             Qt::AlignRight, number); 
  90. //        } 
  91.  
  92. //        block = block.next(); 
  93. //        top = bottom; 
  94. //        bottom = top + (int) blockBoundingRect(block).height(); 
  95. //        ++blockNumber; 
  96. //    } 
  97.  
  98.     QTextBlock block = document()->begin(); 
  99.     int top = 0; 
  100.     QTextCursor cursor(block); 
  101.     cursor.setPosition(0);//move to the beginning of the document 
  102. //    qWarning() << document()->lineCount() << document()->blockCount(); 
  103.     int linenum = 0; 
  104.     while(linenum < document()->lineCount()) 
  105.     { 
  106.     forint i = 0 ; i < block.lineCount(); i ++) 
  107.     { 
  108.     QTextLine line = block.layout()->lineAt(i); 
  109.     //qWarning() << line.rect().toRect() << "x,y:" << line.x() << line.y(); 
  110.     int dx = blockBoundingGeometry(block).x(); 
  111.     int dy = blockBoundingGeometry(block).y(); 
  112.     //qWarning()<< "block offset:" << dx << dy << "content offset:" << contentOffset(); 
  113.     top = line.rect().translated(contentOffset()).translated( dx,dy).y(); 
  114.     painter.setPen(Qt::black); 
  115.     painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), 
  116.     Qt::AlignRight, QString::number( linenum +1)); 
  117.     linenum ++; 
  118.     } 
  119.     block = block.next(); 
  120.     if(!block.isValid()) 
  121.     { 
  122.     break
  123.     } 
  124.     } 
  125.  


实现在文本中查找功能的finddialog,用的是书上给的小例子稍加改动加上的 :)

finddialog.h

 

 
  
  1. #ifndef FINDDIALOG_H 
  2. #define FINDDIALOG_H 
  3.  
  4. #include<QDialog> 
  5. #include "notemainwindwow.h" 
  6.  
  7. class NoteMainWindwow; 
  8. class QCheckBox; 
  9. class QLabel; 
  10. class QLineEdit; 
  11. class QPushButton; 
  12.  
  13. class FindDialog:public QDialog 
  14.    Q_OBJECT 
  15.  
  16.  public
  17.     FindDialog(); 
  18.  
  19.  signals: 
  20.     void findStr(const QString &str); 
  21.  private slots: 
  22.     void findClicked(); 
  23.     void enableFindButton(const QString &text); 
  24.  
  25.  private
  26.     QLineEdit *lineEdit; 
  27.     QLabel *label; 
  28.     QPushButton *findButton; 
  29.     QPushButton *closeButton; 
  30. //    bool isFirstTime; 
  31. //    NoteMainWindwow *noteWindow; 
  32. }; 
  33.  
  34.  
  35.  
  36. #endif // FINDDIALOG_H 

 

 
  
  1. #include<QtGui> 
  2. #include "finddialog.h" 
  3.  
  4. FindDialog::FindDialog() 
  5.     label=new QLabel(tr("Find &what:")); 
  6.     lineEdit = new QLineEdit; 
  7.     label->setBuddy(lineEdit); 
  8.  
  9. //    caseCheckBox = new QCheckBox(tr("Match &case")); 
  10. //    backwardCheckBox = new QCheckBox(tr("Search &back")); 
  11.  
  12.     findButton = new QPushButton(tr("&Find")); 
  13.     findButton->setDefault(true); 
  14.     findButton->setEnabled(false); 
  15.  
  16.     closeButton = new QPushButton(tr("Close")); 
  17.  
  18.     connect(lineEdit,SIGNAL(textChanged(const QString &)),this,SLOT(enableFindButton(const QString &))); 
  19.     connect(findButton,SIGNAL(clicked()),this,SLOT(findClicked())); 
  20.     connect(closeButton,SIGNAL(clicked()),this,SLOT(close())); 
  21.  
  22.     QHBoxLayout *topLeftLayout = new QHBoxLayout; 
  23.  
  24.     topLeftLayout->addWidget(label); 
  25.     topLeftLayout->addWidget(lineEdit); 
  26.  
  27.     QVBoxLayout *leftLayout = new QVBoxLayout; 
  28.     leftLayout->addLayout(topLeftLayout); 
  29. //    leftLayout->addWidget(caseCheckBox); 
  30. //    leftLayout->addWidget(backwardCheckBox); 
  31.  
  32.     QVBoxLayout *rightLayout = new QVBoxLayout; 
  33.     rightLayout->addWidget(findButton); 
  34.     rightLayout->addWidget(closeButton); 
  35.     rightLayout->addStretch(); 
  36.  
  37.     QHBoxLayout *mainLayout = new QHBoxLayout; 
  38.     mainLayout->addLayout(leftLayout); 
  39.     mainLayout->addLayout(rightLayout); 
  40.     setLayout(mainLayout); 
  41.  
  42.     setWindowTitle("find"); 
  43.     setFixedHeight(sizeHint().height()); 
  44.  
  45.  
  46. void FindDialog::findClicked() 
  47.         QString text=lineEdit->text(); 
  48.  
  49.          emit findStr(text); 
  50. //    QString searchString=lineEdit->text(); 
  51. //    QTextDocument *document=noteWindow->textEdit->document(); 
  52.  
  53. //    bool found=false; 
  54.  
  55.  
  56. //            QTextCursor highlightCursor(document); 
  57. //            QTextCursor cursor(document); 
  58.  
  59. //            cursor.beginEditBlock(); 
  60.  
  61. //            QTextCharFormat plainFormat(highlightCursor.charFormat()); 
  62. //            QTextCharFormat colorFormat=plainFormat; 
  63. //            colorFormat.setForeground(Qt::red); 
  64.  
  65. //            while(!highlightCursor.isNull()&&!highlightCursor.atEnd()){ 
  66. //                    highlightCursor=document->find(searchString,highlightCursor,QTextDocument::FindWholeWords); 
  67.  
  68. //                    if(!highlightCursor.isNull()){ 
  69. //                            found=true; 
  70. //                            highlightCursor.movePosition(QTextCursor::WordRight,QTextCursor::KeepAnchor); 
  71. //                            highlightCursor.mergeCharFormat(colorFormat); 
  72. //                    } 
  73.  
  74. //            } 
  75. //            cursor.endEditBlock(); 
  76.  
  77.  
  78.             isFirstTime = false; 
  79.  
  80. //            if (found == false) { 
  81. //                QMessageBox::information(this, tr("Word Not Found"), 
  82. //                    "Sorry, the word cannot be found."); 
  83. //    } 
  84.  
  85.  
  86. void FindDialog::enableFindButton(const QString &text) 
  87.     findButton->setEnabled(!text.isEmpty());