我有一个问题:我的项目非常简单,有一个QTextEdit和一个QSyntaxHighlighter,我正在尝试加载.cpp文件并突出显示该文件的第八行,但QTextEdit无法加载整个文件,如果我要求它突出显示该行。
下图显示了问题:
该申请的相关代码如下:
void MainWindow::openFile(const QString &path)
{
QString fileName = path;
if (fileName.isNull())
fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), "", "C++ Files (*.cpp *.h)");
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QFile::ReadOnly | QFile::Text))
editor->setPlainText(file.readAll());
QVector<quint32> test;
test.append(8); // I want the eighth line to be highlighted
editor->highlightLines(test);
}
}
和
#include "texteditwidget.h"
TextEditWidget::TextEditWidget(QWidget *parent) :
QTextEdit(parent)
{
setAcceptRichText(false);
setLineWrapMode(QTextEdit::NoWrap);
}
// Called to highlight lines of code
void TextEditWidget::highlightLines(QVector<quint32> linesNumbers)
{
// Highlight just the first element
this->setFocus();
QTextCursor cursor = this->textCursor();
cursor.setPosition(0);
cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, linesNumbers[0]);
this->setTextCursor(cursor);
QTextBlock block = document()->findBlockByNumber(linesNumbers[0]);
QTextBlockFormat blkfmt = block.blockFormat();
// Select it
blkfmt.setBackground(Qt::yellow);
this->textCursor().mergeBlockFormat(blkfmt);
}
但是如果你想用我使用的cpp文件测试项目(在目录FileToOpen \ diagramwidget.cpp中),这里是完整的源代码
http://idsg01.altervista.org/QTextEditProblem.zip
我一直在努力解决这个问题很多时间,我开始怀疑这不是一个错误或类似的东西
答案 0 :(得分:1)
QTextEdit
无法接受如此大量的文字。拆分它,例如:
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QFile::ReadOnly | QFile::Text))
{
QByteArray a = file.readAll();
QString s = a.mid(0, 3000);//note that I split the array into pieces of 3000 symbols.
//you will need to split the whole text like this.
QString s1 = a.mid(3000,3000);
editor->setPlainText(s);
editor->append(s1);
}
答案 1 :(得分:0)
似乎QTextEdit控件在每次加载后都需要时间,在QApplication:processEvents();
解决问题后设置setPlainText()
,虽然这不是一个优雅的解决方案。