When dragging a row in a QTableWidget, how can I find out what row index it was dragged FROM and TO?

被刻印的时光 ゝ 提交于 2019-12-12 18:18:55

问题


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.



来源:https://stackoverflow.com/questions/1776712/when-dragging-a-row-in-a-qtablewidget-how-can-i-find-out-what-row-index-it-was

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!