- 在维护同事的一个程序时,发现一个小bug。具体情形是这样:有一个对话框,用户可选中QListWidget中的某一项进行打开删除操作;在进行删除操作时,没有去判断item是否被选中进执行删除操作,会引起程序崩溃问题。于是就有了这篇小文。直接上代码:
.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_open_clicked();
void on_pushButton_delete_clicked();
void setPushButtonEnable();
private:
Ui::Widget *ui;
void initFileList();
};
#endif // WIDGET_H
.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QDebug>
#include <QDir>
#include <QMessageBox>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
initFileList();
ui->pushButton_delete->setEnabled(false);//初始化删除按钮不可点击,当有文件选中时才可点击
connect(ui->listWidget,SIGNAL(itemSelectionChanged()),SLOT(setPushButtonEnable()));//重要的槽连接,检测是否有item改变
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_open_clicked()
{
if(ui->listWidget->count() != 0)
{
qDebug() << "open the" << ui->listWidget->currentItem()->text();
}
}
void Widget::on_pushButton_delete_clicked()
{
QString runPath = QCoreApplication::applicationDirPath();
if(QMessageBox::warning(this, "Warning", "Delete this file?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
if(ui->listWidget->count() != 0)
{
QFile::remove(runPath + "/File/" + ui->listWidget->currentItem()->text());
initFileList();
}
else
{
QMessageBox::warning(this, "Warning", "No file is selected!", QMessageBox::Yes);
}
}
else
{
return;
}
}
void Widget::setPushButtonEnable()
{
ui->pushButton_delete->setEnabled(true);
}
void Widget::initFileList()
{
QString runPath = QCoreApplication::applicationDirPath();
QDir *dir = new QDir(runPath + "/File");
QStringList filter;
qDebug() <<"path:" << runPath + "/File";
filter << "*.txt";
dir->setNameFilters(filter);
QList<QFileInfo> *fileInfo = new QList<QFileInfo>(dir->entryInfoList(filter));
ui->listWidget->clear();
for(int i = 0; i < fileInfo->count();i++)
{
ui->listWidget->addItem(fileInfo->at(i).fileName());
}
}
其中要在程序执行目录下创建File文件夹,才能正常操作。