2012-07-31 54 views
0

我有一個問題:我的項目是一個非常簡單的一個QTextEdit和QSyntaxHighlighter,我試圖加載一個.cpp文件,並突出顯示該文件的第八行,但如果我要求它突出顯示該行,QTextEdit無法加載整個文件。Qt QTextEdit加載只是一半的文本文件

下圖顯示了這個問題:

enter image description here

應用程序的相關代碼如下:

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文件測試項目(在目錄中) ectory FileToOpen \ diagramwidget.cpp),這裏的

http://idsg01.altervista.org/QTextEditProblem.zip

我一直在試圖解決這個問題了大量的時間,我開始懷疑這是不是一個錯誤或東西完整的源代碼類似

回答

0

看來,控制的QTextEdit需要時間每次加載後,設置setPlainText()解決了問題後QApplication:processEvents();雖然它不是一個完美的解決方案。

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); 
    } 
+0

,但如果我評論了「突出」行了,該的QTextEdit可以處理這一切沒有問題 – 2012-07-31 16:52:26

+1

@JohnnyPauling,很難說爲什麼會這樣...但你可以在一個週期內將數據分割到塊,它應該永遠是好的。 – SingerOfTheFall 2012-07-31 16:54:02

+0

看看我的帖子,感謝Qt論壇,我解決了它,無論如何,我將你的答案標記爲有用,因爲你浪費了你的時間來幫助我。謝謝! – 2012-07-31 17:09:06