Qt: distinguish between drag from same or other window

678 views Asked by At

I am using a QTableView, on which I set my own custom model, inheriting from QAbstractTableModel, using a call to QTableView::setModel().

The table view supports drag and drop: my model class reimplements mimeData() and dropMimeData(). Items can be dragged and dropped, even between 2 instances of the application.

What I'd like to achieve is: dropMimeData() should detect whether the dropped element comes from the same window, or from another window of another running copy of the application. And it should behave differently in each case.

Using the argument Qt::DropAction action of dropMimeData() seemed the most natural thing, but that does not work: it is always Qt::CopyAction or Qt::MoveAction, irrespective of the originating window, and only depending on the defaultDropAction of the QTableView.

Is this possible?

2

There are 2 answers

0
user377486 On BEST ANSWER

I ended up subclassing QTableView, which can be done in QT Designer by right-clicking on the table in the form and choosing Promote to...- In the subclass I followed adlag's suggestion and used dropEvent->source() to detect whether the source was the same widget or another one.

0
adlag On

Suppose a QMainWindow instance MainWindow has two QTableView instances as childeren:
ui->tableView1 and ui->tableView2

If the function is not already declared, add the following to mainwindow.h:

protected:
bool eventFilter(QObject *target, QEvent *event);

add the following to the constructor in the implementation file

ui->tableView1->viewport()->installEventFilter(this); 
ui->tableView2->viewport()->installEventFilter(this); 

Add the following function in the implementation file mainwindow.cpp
(if the function already exists add extra if blocks)

bool MainWindow::eventFilter(QObject * target, QEvent *event)
{
    if (event->type() == QEvent::Drop) {
        QDropEvent *dropEvent = (QDropEvent*) event;
        // pointer target is the target and 
        // pointer dropEvent->source() is the source
        if (target == ui->tableView1->viewport()) {
            // ....
        } 
        if (target == ui->tableView2->viewport()) {
           // ...
        } 
    }
    return false; //leave further processing to widget
}

You can also intercept a QDragMoveEvent. By analyzing the pointers target and event->source() you can find out where it goes to and where it came from.