1

I'm sure there most be a simple explanation for my problem but I just don't see it. I'm trying to read a text file into a QTextEdit but apparently i'm unable to change the QTextEdit text in this method and I can't see why.

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;

}

The first time I use SetText during the constructor it works fine but when I call it from open it doesn't work. Help please

4

2 回答 2

3

你忘了open()调用QFile对象

    QFile file(archivo); 
    if (file.open(QFile::ReadOnly){
         QTextStream stream(&file);
         ...
    } else {
        /// Oops, no pude abrir el archivo para leer :(
    }
于 2012-04-23T18:38:54.460 回答
0

尝试

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

或者更好的是用

QFile *file = new QFile(archivo);
this->textArea->setPlainText(QString(file->readAll()));
于 2012-04-23T16:03:15.627 回答