日照网站建设哪家好拉新推广平台有哪些
1. 说明
QSaveFile和QFile两个类都是用来操作文件的,区别在于QSaveFile在对文件进行写入时有一种保护机制,再写入出错时,不会对源文件中的内容进行操作。该类在执行写操作时,会先将内容写入到一个临时文件中,如果没有错误发生,调用其成员函数commit()将临时文件中的内容移到目标文件中。
2. 简单使用案例
本案例中使用QSaveFile类进行文件写入操作,使用QFile类进行文件的读取操作,类QSaveFile在使用说明上显示也可以进行读操作,但在实际使用时发现会出问题。
包含两个界面:mainwindow.ui是主窗口,inputwindow.ui是信息输入弹窗,输入要写入文件的内容
mainwindow.ui:
inputwindow.ui:
mainwindow.h代码:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QSaveFile>
#include <QFile>
#include <QDir>
#include <QListWidgetItem>
#include <QDebug>#include "inputwindow.h"QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_btnWrite_clicked();void on_btnRead_clicked();void getInputText(QString mstr);private:Ui::MainWindow *ui;//引入第二界面弹窗对象InputWindow *inputWin;QSaveFile *mFile=nullptr;
};
#endif // MAINWINDOW_H
mainwindow.cpp代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);//如果指定路径下不存在该文件,则会在该路径下新建此文件mFile = new QSaveFile("/home/chin/Desktop/Python/savefile2.py");mFile->open(QFile::WriteOnly|QFile::Truncate|QFile::Text);}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_btnWrite_clicked()
{inputWin = new InputWindow(this);//调整位置和尺寸inputWin->setGeometry((this->width()- inputWin->width())/1.5,(this->height()-inputWin->height())/2,150,80);inputWin->show();//绑定信号,注意信号中如果带有参数,不能写参数的名字,给出参数类型即可,否则出错connect(inputWin,SIGNAL(sendInputStr(QString)),this,SLOT(getInputText(QString)));
}void MainWindow::on_btnRead_clicked()
{QFile file("/home/chin/Desktop/Python/savefile2.py");
// qDebug()<<file.fileName().split('/')[file.fileName().split('/').length()-1].split('.')[0];QString str;if(file.open(QFile::ReadOnly)){str = file.readAll();}ui->fileContentList->addItem(str);
}void MainWindow::getInputText(QString mstr)
{if(mFile->isOpen()){mFile->write(mstr.toUtf8());qDebug()<<mstr;mFile->commit();}
}
不同界面之间的参数传递使用信号槽的方式实现,但是注意当信号中包含参数时,只需要写出参数的类型即可,不能写形参的名字,否则信号槽连接会出问题。
inputwindow.h代码:
#ifndef INPUTWINDOW_H
#define INPUTWINDOW_H#include <QWidget>
#include <QDebug>namespace Ui {
class InputWindow;
}class InputWindow : public QWidget
{Q_OBJECTpublic:explicit InputWindow(QWidget *parent = nullptr);~InputWindow();private slots:void on_btnYes_clicked();void on_btnCancel_clicked();signals://自定义信号void sendInputStr(QString str);private:Ui::InputWindow *ui;
};#endif // INPUTWINDOW_H
inputwindow.cpp代码:
#include "inputwindow.h"
#include "ui_inputwindow.h"InputWindow::InputWindow(QWidget *parent) :QWidget(parent),ui(new Ui::InputWindow)
{ui->setupUi(this);}InputWindow::~InputWindow()
{delete ui;
}void InputWindow::on_btnYes_clicked()
{QString str = ui->inputText->toPlainText();//发射信号emit sendInputStr(str);qDebug()<<str;delete this;
}void InputWindow::on_btnCancel_clicked()
{delete this;
}