教程: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.