QTablewidget drop without creating new rows

2020-03-31 03:41发布

I have a QTableWidget and 1 column has only checkboxes, so for those items I have these flags:

/* create prototype for checkbox item */ 
checkItem = new QTableWidgetItem();
Qt::ItemFlags flags = checkItem->flags();
flags &= ~Qt::ItemIsEditable;
flags &= ~Qt::ItemIsDropEnabled;
flags &= ~Qt::ItemIsDragEnabled;
flags |= Qt::ItemIsUserCheckable;
checkItem->setFlags(flags);
/**/

Ok that works... almost. I can't drop anything in those items, that's good. But now there can be dropped in between 2 cells, so there is a new row created. How can I prevent that? In the other columns where the cells are drop-enabled, I can only drop in the cells and not in between and that is good. Why is this behavior changed when the item is not drop-enabled?

1条回答
劳资没心,怎么记你
2楼-- · 2020-03-31 04:05

A fast hack using an event filter (could need some tweaks):

What you do this is ignore any drop on the checkbox column. So it should be enough to disable row creation.

bool yourWidget::eventFilter(QObject *a_object, QEvent *a_event) 
  {
  bool result = false;
  if ((a_object == table->viewport()) && (a_event->type() == QEvent::Drop)) 
  {
     QDropEvent *p_drop_event = static_cast<QDropEvent *>(a_event);
     QPoint pos = p_drop_event->pos();
     QModelIndex new_index = table->indexAt(pos);
     if (new_index.column() == YOUR COLUMN HERE)
     {
       // Ignore drop event
       p_drop_event->setDropAction(Qt::IgnoreAction);
       p_drop_event->accept();
       return true;
     }
     else
     {
       // Allow drop
       return false;
     }

  }
return QObject::eventFilter(a_object, a_event);
}

Info about eventFilters:

Event Filters

查看更多
登录 后发表回答