2012-04-23 52 views
0

我確定對於我的問題,大部分都有一個簡單的解釋,但我只是沒有看到它。 我試圖將文本文件讀入QTextEdit,但顯然我無法更改此方法中的QTextEdit文本,我看不出原因。QTextEdit not設置文本

Document::Document(QWidget *parent) : QWidget(parent) 
{ 
    this->layout = new QGridLayout(this); 
    this->layout->setSpacing(2); 
    this->layout->setMargin(0); 
    this->setLayout(layout); 
    this->textArea = new QTextEdit(this); 
    this->textArea->setLineWrapMode(QTextEdit::NoWrap); 
    this->textArea->setAcceptDrops(true); 
    this->textArea->setAcceptRichText(true); 
    this->textArea->setUndoRedoEnabled(true); 
    this->textArea->setFont(QFont("Mono" , 11)); 
    this->layout->addWidget(textArea); 
    this->textArea->show(); 
    this->textArea->setFocus(); 
    this->textArea->setText("Prueba de texto1"); 
} 

void Document::open(QString archivo) 
{ 
    std::cout << "Opening..................." << std::endl; 
    this->textArea->setPlainText("Prueba de texto2"); 
    QFile file(archivo); 
    QTextStream stream(&file); 
    //this->textArea->append(stream.readAll()); 
    this->textArea->setText(stream.readAll()); 
    std::cout << "Opened" << std::endl; 

} 

我第一次它工作正常,但是當我把它從開放這是行不通的構造過程中使用的setText。請幫助

+0

你確定該文件打開是否正確?你在文本框中看到「Prueba de texto2」嗎?如果你這樣做,那麼你的文件路徑或文件有問題。而不是'setText()'嘗試'setPlainText()'這是否工作? – RedX 2012-04-23 09:22:06

+0

我通過QFileDialog獲取文件路徑,所以它應該沒問題。 textEdit不顯示「Prueba De Texto2」,它保留在「Prueba de Texto1」中 – Topo 2012-04-23 09:26:16

+0

您確定調用了「Document :: open()」嗎? – RedX 2012-04-23 09:29:25

回答

3

更換整個流的事情你忘了打電話給open()QFile對象

QFile file(archivo); 
    if (file.open(QFile::ReadOnly){ 
     QTextStream stream(&file); 
     ... 
    } else { 
     /// Oops, no pude abrir el archivo para leer :(
    } 
0

嘗試

this->textArea->setPlainText(QString(stream.readAll()); 

或更好,但與

QFile *file = new QFile(archivo); 
this->textArea->setPlainText(QString(file->readAll()));