I'm trying to keep some array data synchronized with the contents of a QTableWidget. I'd like to enable drag and drop reordering (moving items within the table, as opposed to copying), but it's not clear to me how, when the drop event is fired, I can find out what index the item was dragged FROM. Hence, I have no way of knowing what object to move within the list I'm synchronizing with. How can I get the original row index of the item being dragged?
问题:
回答1:
Encode the from index in QMimeData and store it in the QDrag object with setMimeData(). When the drop event occurs, extract the data from the QDropEvent with mimeData().
回答2:
Step 1. Override the QTableWidget::mimeData function. Call the base class implementation, then stuff your own custom MIME type into the QMimeData, and return it.
Step 2. Override the QTableWidget::dropEvent function. If your MIME data is in the QMimeData, accept the drop and extract your data. Use the QTableWidget::indexAt to find what row/column the drop went into.
回答3:
QDropEvent
has a source()
function that will give you the widget that started the drag drop event. Then do a qobject_cast<QTableWidget>
on the source
. Once you verify the pointer, call QTableWidget::findItems
to get the row of the item.
So something like this:
void dropEvent ( QDropEvent * event ) {
if (event) {
QTableWidget* table = qobject_cast<QTableWidget*>(event->source());
if (table) {
QString item = ""// Decode MIME data here.
Qt::MatchFlag someFlag = Qt::MatchExactly; // Check documentation for match type.
QList<QTableWidgetItem *> items = table->findItems(item, someFlag)
// If you don't have repeats, items[0] is what you want.
int initialRow = table->row(items[0]);
}
}
}
I tend to use model/view classes so this might be a little off, but it should work.