教程:C++ 调试
本教程通过TextFinder示例,演示如何在Debug 模式下调试 Qt C++ 应用程序。
TextFinder 将文本文件读入QString ,然后通过QTextEdit 进行显示。要查看 TextFinder 类并查看其中存储的数据:
- 在
textfinder.cpp中,点击行号与窗口边框之间的区域(即我们更改光标位置的那一行),以设置断点。
- 转到“Debug ” > “Start Debugging ” > “Start Debugging of Startup Project ”,或按F5 键。
- 要查看有关断点的信息,请转到“Breakpoints ”视图。

- 要删除断点,请右键单击该断点,然后选择“Delete Breakpoint ”。
- 要查看 TextFinder 类的基类和数据成员,请转到“Locals ”视图。

修改on_findButton_clicked() 函数,使其在光标到达文档末尾时,能够返回文档开头并继续搜索。添加以下代码片段:
void TextFinder::on_findButton_clicked() { QString searchString = ui->lineEdit->text(); QTextDocument *document = ui->textEdit->document(); QTextCursor cursor = ui->textEdit->textCursor(); cursor = document->find(searchString, cursor, QTextDocument::FindWholeWords); ui->textEdit->setTextCursor(cursor); bool found = cursor.isNull(); if (!found && previouslyFound) { int ret = QMessageBox::question(this, tr("End of Document"), tr("I have reached the end of the document. Would you like " "me to start searching from the beginning of the document?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (ret == QMessageBox::Yes) { cursor = document->find(searchString, QTextDocument::FindWholeWords); ui->textEdit->setTextCursor(cursor); } else return; } previouslyFound = found; }
但是,如果编译并运行上述代码,应用程序将因逻辑错误而无法正常工作。要定位此逻辑错误,请使用以下按钮逐步执行代码:
(Stop Debugger )、
(Step Over )、
(Step Into )以及
(Step Out )。
另请参阅 教程:《Qt Widgets 应用程序》、《调试》和《调试器》。
Copyright © The Qt Company Ltd. and other contributors. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.