首页 > 解决方案 > 在特殊情况下,如何防止来自 QFileSystemModel 的 rowsInserted 信号?

问题描述

我正在编写文件资源管理器,并且使用 QFileSysteModel 作为基础。我注意到方法QFileSystemModel::index()QFileSystemModel::fetchMore导致模型发出信号rowsInserted

我已将rowsInserted信号连接到一个插槽,该插槽发送有关新插入行的数据。问题是来自QFileSystemModel::index()并且QFileSystemModel::fetchMore不是真正新的行,而是由 QFileSystemModel 本身添加到模型中的行,这在我的程序中造成了麻烦。

我在使用之前尝试过设置标志QFileSystemModel::index()QFileSystemModel::fetchMore但它并不可靠,尤其是QFileSystemModel::fetchMore.

喜欢:

m_blockRowInsert = true; // <-- blocks rowInserted for m_fileSysModel->index
auto index = m_fileSysModel->index(pathNew); // calls immediately rowsInserted
if(index.isValid())
{
    if(m_fileSysModel->canFetchMore(index))
    {
         m_blockRowInsert = true;// <-- does not work reliable because rowsInserted can be called more than once by fetchmore
         m_fileSysModel->fetchMore(index); // <-- calls rowsInserted after completing the function
    }
}

我试图像这样重置标志:

void onRowsInserted(const QModelIndex &parent, int first, int last)
{
    if(m_blockRowInsert)
    {
        m_blockRowInsert = false;
        return;
    }
}

标签: c++qtqfilesystemmodelqmodelindex

解决方案


您可以使用blockSignals功能。这样,您可以在之前阻止信号fetchMore并在之后启用信号。

...
if(m_fileSysModel->canFetchMore(index))
{
     this->blockSignals(true);
     m_fileSysModel->fetchMore(index);
     this->blockSignals(false);
}
...

我假设那thisrowInserted信号的发送者。


推荐阅读