【问题标题】:QTextEdit not Setting TextQTextEdit 不设置文本
【发布时间】:2012-04-23 09:18:58
【问题描述】:

我确信对于我的问题有一个简单的解释,但我只是没有看到它。 我正在尝试将文本文件读入 QTextEdit,但显然我无法在此方法中更改 QTextEdit 文本,我不明白为什么。

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 时它工作正常,但是当我从 open 调用它时它不起作用。请帮忙

【问题讨论】:

  • 您确定文件已正确打开吗?你在你的文本编辑中看到"Prueba de texto2" 吗?如果你这样做了,那么你的文件路径或文件有问题。代替setText() 尝试setPlainText() 可以吗?
  • 我通过 QFileDialog 获取文件路径,所以应该没问题。 textEdit 不显示“Prueba De Texto2”,它停留在“Prueba de Texto1”中
  • 你确定Document::open()被调用了吗?
  • 是的,终端显示“Opening............”然后是“Opened”字符串
  • 在写入之前尝试清除'textarea->clear()'。

标签: c++ qt qt4


【解决方案1】:

您忘记在 QFile 对象上调用 open()

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

【讨论】:

    【解决方案2】:

    试试

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

    或者更好的是用

    替换整个流的东西
    QFile *file = new QFile(archivo);
    this->textArea->setPlainText(QString(file->readAll()));
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多