【问题标题】:Read text file in textedit Qt C++在 textedit Qt C++ 中读取文本文件
【发布时间】:2013-11-14 09:48:32
【问题描述】:

我有这个文本文件:

Name 1      Email 1
Name 2      Email 2
Name 3      Email 3
Name 4      Email 4
Name 5      Email 5

这是一份员工名单及其电子邮件。我想在一个对话窗口中列出一个列表,并在那里显示他们的名字。我认为这是在对话窗口上打印文本文件的好方法,但它不起作用。

employees_dialog.cpp

#include "employees_dialog.h"
#include "ui_employees_dialog.h"
#include <QtCore/QFile>
#include <QtCore/QTextStream>


employees_dialog::employees_dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::employees_dialog)
{
    ui->setupUi(this);
    getTextFile();
}

employees_dialog::~employees_dialog()
{
    delete ui;
}

void employees_dialog::getTextFile()
{
    QFile myFile(":/employees.txt");
    myFile.open(QIODevice::ReadOnly);
    QTextStream textStream(&myFile);
    QString line = textStream.readAll();
    myFile.close();
    ui->textEdit->setPlainText(line);
}

这是头文件。

#ifndef EMPLOYEES_DIALOG_H
#define EMPLOYEES_DIALOG_H

#include <QDialog>

namespace Ui {
    class employees_dialog;
}

class employees_dialog : public QDialog
{
    Q_OBJECT

public:
    explicit employees_dialog(QWidget *parent = 0);
    ~employees_dialog();

private slots:

private:
    Ui::employees_dialog *ui;
    void getTextFile();
};

#endif // EMPLOYEES_DIALOG_H

所以 UI 中的 textEdit 应该显示文本文件。但它只是空白的白色。我在 Qt 资源文件中有该文件。调试器没有给出任何错误,应用程序本身工作正常,但文本不会出现在 textEdit 中。

顺便说一句,我是 Qt 新手。

【问题讨论】:

  • 测试文件打开错误
  • 我会使用调试器。在 getTextFile() 上设置断点并检查 line 的内容。我怀疑 QFile 没有打开是因为 qrc 文件有问题。
  • if(QFile::exists(true)) { qDebug("文件不存在或无法打开"); }
  • 这不起作用它说 'F:\Scripts\Berichtencentrumemployees_dialog.cpp:30: error: C2665: 'QFile::exists' : 2 个重载都不能转换所有参数类型 c:\ qt\qt5.1.1\5.1.1\msvc2012_64\include\qtcore\qfile.h(108): 可能是 'bool QFile::exists(const QString &)' 同时尝试匹配参数列表 '(bool)''
  • @SvenWeerdenburg 只是 myFile.exists() 而不是 QFile::exists(true)

标签: c++ qt dialog


【解决方案1】:

使用这个:

QFile file( "myfile.txt" );

if ( !file.exists() )
{
    qDebug()<<"doesn't exist the file";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多