Qt5.8 读写txt文件

关键代码

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
 
  
    QObject::connect(ui->writeButton,SIGNAL(clicked(bool)),this,SLOT(writeButtonSlot()));
    QObject::connect(ui->readButton ,SIGNAL(clicked(bool)),this,SLOT( readButtonSlot()));
}
 
  
void Widget::readButtonSlot()
{
    QString fileName = QFileDialog::getOpenFileName(
                     this,
                     tr("Open File"),
                     "E:/QtControlFiles/Read",
                     tr("*.txt"));
    QFile file( fileName );
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug()<<"no read";
        return;
    }
    qDebug()<<"Yes read";
    QTextStream in(&file);
    //QString line = in.readLine();//读取一个回车结束
    QString line = in.readAll();//读取所有
    ui->textEdit->setText(line);
}
 
  
void Widget::writeButtonSlot()
{
     QString writeData = ui->textEdit->toPlainText();
     QFile data("E:/QtControlFiles/Write/Txt_Demo.txt");
     if (data.open( QIODevice::Text | QFile::WriteOnly  ))
     {
         qDebug()<<"yes write";
         QTextStream out(&data);
         out << writeData ;
         return;
     }
     qDebug()<<"no write";
}

源程序链接下载:http://download.csdn.net/detail/m_986883511/9849938


你可能感兴趣的:(Qt)