正如标题所说,当我从QTableWidget拖动一个项目时,它向ui-> table-> children中添加了一个子项,然后将ChildAdded事件启动到我的eventFilter中,问题是如果我删除了被拖动的项放到不接受删除的区域中,则不会从ui-> table-> children中删除该子项,而在已启用删除的区域中释放被拖动的项将会这样做,并启动ChildRemoved事件。
这是我的初始化代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
m_ui(new Ui::MainWindow)
{
m_ui->setupUi(this);
m_ui->left_table->installEventFilter(this);
m_ui->right_table->installEventFilter(this);
m_ui->left_table->setColumnCount(1);
m_ui->left_table->setRowCount(25);
m_ui->left_table->setHorizontalHeaderLabels({"Source"});
m_ui->left_table->horizontalHeader()->setStretchLastSection(true);
m_ui->left_table->setAcceptDrops(false);
m_ui->left_table->setDragEnabled(true);
m_ui->right_table->setColumnCount(1);
m_ui->right_table->setHorizontalHeaderLabels({"Receiver"});
m_ui->right_table->horizontalHeader()->setStretchLastSection(true);
m_ui->right_table->setAcceptDrops(true);
for (int i = 0; i < 25; ++i) {
m_ui->left_table->setItem(i, 0, new QTableWidgetItem(QString::number(i)));
}
qDebug() << "Left childs: " << m_ui->left_table->children().size();
}
和事件过滤器:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::ChildAdded || event->type() == QEvent::ChildRemoved) {
qDebug() << "Object: " << watched->objectName()
<< " Event: " << event->type()
<< "Childs: " << m_ui->left_table->children().size();
}
return false;
}
放置在无效区域上的示例,这不会删除之前添加的子项:
放置有效区域的示例,这将删除子项并调用ChildRemoved事件: