背景:笔者需要创建和删除多个pdd和多个pff文件(这些是自己创建的类型),一个个手动创建和删除很麻烦,就做了一款小软件解决此问题。
先看一下效果:
代码如下:
①、头文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMessageBox>
#include <QFile>
#include <QDir>
#include <QCompleter>
#include <QDirModel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButtonAdd_clicked();
void on_pushButtonDel_clicked();
private:
bool isFailAddFile();
bool createFile();
void fileFilter();
private:
Ui::MainWindow *ui;
QDir *m_tempDir;
QString m_dirString;
QCompleter *m_completer;
};
#endif // MAINWINDOW_H
②、源文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setFixedSize(485,90);
m_dirString = "CreatePddOrPff";
m_tempDir = new QDir;
m_tempDir->mkdir(m_dirString);
fileFilter();
}
MainWindow::~MainWindow()
{
delete ui;
delete m_tempDir;
}
void MainWindow::on_pushButtonAdd_clicked()
{
if(createFile()){
QMessageBox::information(this,"Success","File is creating.");
}
}
void MainWindow::on_pushButtonDel_clicked()
{
if(QFile::remove(QString(m_dirString).append("/").append(ui->lineEditDel->text()))){
QMessageBox::information(this,"Success","File is removing.");
ui->lineEditDel->setText("");
}
else{
QMessageBox::information(this,"Fail","File is not exists.");
}
}
bool MainWindow::isFailAddFile()
{
if(ui->lineEditAdd->text().isEmpty()){
QMessageBox::information(this,"Fail","File is Empty.");
}
return !ui->lineEditAdd->text().isEmpty();
}
bool MainWindow::createFile()
{
QFile file(QString(m_dirString).append("/").append(ui->lineEditAdd->text()).append(".").append(ui->comboBox->currentText()));
if(isFailAddFile()){
file.open(QIODevice::WriteOnly);
file.close();
fileFilter();
}
return file.exists();
}
void MainWindow::fileFilter()
{
QStringList filter;
QDir dir(m_dirString);
dir.setFilter(QDir::Files|QDir::Hidden|QDir::NoSymLinks);
filter << "*.p*";
m_tempDir->setNameFilters(filter);
QFileInfoList infoList = dir.entryInfoList();
for(int i = 0; i < infoList.count(); i++){
filter.append(infoList.at(i).fileName());
}
m_completer = new QCompleter(filter,this);
m_completer->setCaseSensitivity(Qt::CaseInsensitive);
ui->lineEditDel->setCompleter(m_completer);
}
③、ui文件:
标签:补全,Demo,QDir,ui,dirString,include,MainWindow,append,Qt From: https://blog.51cto.com/u_15854865/5811263