在特殊情况下如何防止来自 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;
    }
}

解决方法

您可以使用 blockSignals 函数。通过这种方式,您可以在 fetchMore 之前阻止信号并在之后启用信号。

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

我假设 thisrowInserted 信号的发送者。