我试图使用QTableView来显示远程文件列表,我希望支持将文件拖到表视图中,但是我无法使它工作。
class MyTableView: public QTableView {
...
MyTableView(...) {
setDragEnabled(true);
setAcceptDrops(true);
setDragDropMode(DragDrop);
setDropIndicatorShown(true);
}
protected:
void dragEnterEvent(QDragEnterEvent *event) override {
// This function is called
const QMimeData* mimeData = event->mimeData();
QStringList test = mimeData->formats();
if (event->source() == nullptr) {
if (mimeData->hasUrls()) {
event->acceptProposedAction();
}
}
}
void dropEvent(QDropEvent *event) override {
// This function is not called.
}
....
}
class MyTableViewModel : public QAbstractTableModel {
...
Qt::ItemFlags flags(const QModelIndex& index) const {
if (!index.isValid())
return Qt::NoItemFlags;
Qt::ItemFlags flag = QAbstractItemModel::flags(index);
flag |= Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
return flag;
}
...
}
dragEnterEvent
被调用,但dropEvent
从未被调用过。
有人指出我需要重写dragMoveEvent
,但是我应该如何实现它呢?
还有一个人提到了QAbstractItemModel::canDropMimeData
,dropMimeData
,supportedDragActions
,我试图覆盖这些函数,只是返回true,但仍然不能工作。
或者是否有任何可用的工作演示/示例?或者怎样才是正确的方法?
我在谷歌上搜索了很多,但没有发现任何有用的东西。谢谢。
发布于 2022-09-15 13:31:33
最后,我能够使QTableView::dropEvent
像预期的那样工作。
官方医生来了:与项目视图一起使用拖放。这是一篇很长但很有用的文章。
关键代码:
// Enable drop/drag in the constructor of MyTableView
setDragEnabled(true);
setAcceptDrops(true);
setDragDropMode(DragDrop);
setDropIndicatorShown(true);
// viewport()->setAcceptDrops(true); // it's not required although the doc mentioned it
// MyTableViewModel
Qt::ItemFlags MyTableViewModel::flags(const QModelIndex &index) const {
Qt::ItemFlags flag = QAbstractItemModel::flags(index);
if (index.isValid()) {
return flag | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
} else {
return flag | Qt::ItemIsDropEnabled;
}
}
Qt::DropActions MyTableViewModel::supportedDropActions() const {
return Qt::CopyAction | Qt::MoveAction;
}
bool MyTableViewModel::canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int col, const QModelIndex& parent) const {
return true; // just for simplicity
}
https://stackoverflow.com/questions/73718181
复制相似问题