教程:C++ 调试

本教程以TextFinder示例说明如何在“Debug ”模式下调试 Qt C++ 应用程序。

TextFinder 将文本文件读入QString ,然后通过QTextEdit 进行显示。要查看 TextFinder 类并查看其中存储的数据:

  1. 在“textfinder.cpp ”中,点击行号与窗口边框之间的区域(即我们更改光标位置的那一行),以设置断点。

    在编辑器中设置断点

  2. 转到“Debug ”>“Start Debugging ”>“Start Debugging of Startup Project ”,或按F5 键。
  3. 要查看断点信息,请转到“Breakpoints ”视图。

    在“断点”视图中查看断点详细信息

  4. 要删除断点,请右键单击该断点,然后选择“Delete Breakpoint ”。
  5. 要查看 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.