[英]Qt - Drag and Drop File into ListView
I am trying to write a simple program (nothing special) which has a QListView
and some Buttons.我正在尝试编写一个简单的程序(没什么特别的),它有一个
QListView
和一些按钮。
My question is: How do I specifically tell the QListView
to accept Drag and Drop from the filesystem?我的问题是:我如何明确告诉
QListView
接受来自文件系统的拖放?
I currently have我目前有
setAcceptDrops(true)
Which is OK, but the drag and drop works on the whole (Main)Window.没关系,但拖放适用于整个(主)窗口。 I just want it to work when the file is dragged into the
QListView
.我只是希望它在文件被拖入
QListView
。
Why doesn't this work?:为什么这不起作用?:
ui->listView->setAcceptDrops(true);
The whole code:整个代码:
#include "player.h"
#include "ui_player.h"
#include <QListView>
Player::Player(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Player)
{
ui->setupUi(this);
setAcceptDrops(true);
//This doesnt work:
//ui->listView->setAcceptDrops(true);
}
Player::~Player()
{
delete ui;
}
void Player::dropEvent(QDropEvent *ev)
{
QList<QUrl> urls = ev -> mimeData() -> urls();
foreach(QUrl url, urls)
{
qDebug() << url.toString();
}
ev->acceptProposedAction();
}
void Player::dragEnterEvent(QDragEnterEvent *ev)
{
ev->acceptProposedAction();
}
You should override these event functions for QListView
, not QMainWindow
.您应该为
QListView
而不是QMainWindow
覆盖这些事件函数。 When you do ui->listView->setAcceptDrops(true);
当你做
ui->listView->setAcceptDrops(true);
, QListView
is now the widget that reacts to the drop events, by calling its virtual
dropEvent
and dragEnterEvent
functions. ,
QListView
现在是通过调用其virtual
dropEvent
和dragEnterEvent
函数对放置事件做出反应的小部件。
Make your own class that inherits QListView
and define dropEvent
and dragEnterEvent
in there:创建您自己的继承
QListView
的类并在其中定义dropEvent
和dragEnterEvent
:
class MyListView
{
public:
MyListView(QWidget *parent); // implement
protected:
void dropEvent(QDropEvent *ev) override; // implement
void dragEnterEvent(QDragEnterEvent *ev) override; // implement
};
You might also want to override dragMoveEvent
as the reference says.您可能还想像参考文献所说的那样覆盖
dragMoveEvent
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.