我创建了一个自定义 QLineEdit 小部件来处理文件的拖放。该部分的一切都很好,但是一旦我添加了一个 Class 变量,应用程序就会在类的构造或销毁时崩溃:
- 当我的变量是 QString 时,它在构造时崩溃
- 当我的变量是 QString* 时,它在销毁时崩溃
我尝试在析构函数中删除变量(QString *),同样的问题......
有任何想法吗?
标题:
#ifndef DROPLINEEDIT_H
#define DROPLINEEDIT_H
#include <QLineEdit>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QFileInfo>
#include <QString>
#include <QDebug>
class DropLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit DropLineEdit(QWidget *parent = 0);
~DropLineEdit();
protected:
virtual void dragEnterEvent(QDragEnterEvent *event);
virtual void dropEvent(QDropEvent *event);
virtual void dragLeaveEvent(QDragLeaveEvent *event);
signals:
public slots:
private:
QString * mFileName;
};
#endif // DROPLINEEDIT_H
资源:
#include "droplineedit.h"
DropLineEdit::DropLineEdit(QWidget *parent) :
QLineEdit(parent)
{
setAcceptDrops(true);
this->setReadOnly(true);
this->setStyleSheet("QLineEdit { border: 2px solid gray ; border-radius: 8px ; padding: 0 6px }");
}
DropLineEdit::~DropLineEdit()
{
if(!mFileName){
delete mFileName;
}
}
// **************************************** PROTECTED METHODS **************************************** //
void DropLineEdit::dragEnterEvent(QDragEnterEvent *event){
this->setStyleSheet("QLineEdit { border: 3px solid black ; border-radius: 8px ; padding: 0 6px }");
event->accept();
}
void DropLineEdit::dragLeaveEvent(QDragLeaveEvent *event){
this->setStyleSheet("QLineEdit { border: 2px solid gray ; border-radius: 8px ; padding: 0 6px }");
event->accept();
}
void DropLineEdit::dropEvent(QDropEvent *event){
// Get the data. If multiple files are dropped, take only the first one and fetch save its info
QList<QUrl> list = event->mimeData()->urls();
QFileInfo * fileInfo = new QFileInfo(list.at(0).toLocalFile());
qDebug() << fileInfo->absoluteFilePath();
mFileName = new QString(fileInfo->absoluteFilePath());
this->setText(fileInfo->fileName());
this->setStyleSheet("QLineEdit { border: 2px solid gray ; border-radius: 8px ; padding: 0 6px }");
event->accept();
}