I have a custom item model: MyModel : public QAbstractItemModel
that holds a std::vector<MyStruct> as internal data.
I try to load a lot of items in that vector asynchronously, by using a worker thread.
I have two solutions:
A. - use the worker thread to load a std::vector<MyStruct>
- pass the loaded data, though a custom event to the main thread
- let the main thread update the model with the data copied inside the event
B. - use the worker thread to load the std::vector<MyStruct>
- connect a thread signal with loaded data as argument to a slot in the main thread (queued connection)
- let the main thread, update the model with the data received as argument in the slot
Both these solutions work, but they are updating the model inside the main thread.
My question is: is there any way to update the model inside the worker thread? If yes, how?
Let's say my model has a function
void MyModel::setData(const std::vector<MyStruct> & data)
{
QMutexLocker locker
(&m_mutex
);
//protect shared state, accessed from multiple threads
beginResetModel(); //when will this be sent/received?
....update internal data
endResetModel(); //when will this be sent/received?
}
void MyModel::setData(const std::vector<MyStruct> & data)
{
QMutexLocker locker(&m_mutex); //protect shared state, accessed from multiple threads
beginResetModel(); //when will this be sent/received?
....update internal data
endResetModel(); //when will this be sent/received?
}
To copy to clipboard, switch view to plain text mode
and my worker thread does this:
void MyThread::run()
{
std::vector<MyStruct> myVector;
//load the data
model->setData(myVector); //tricky: when will resetModel signals be emitted/received?
}
void MyThread::run()
{
std::vector<MyStruct> myVector;
//load the data
model->setData(myVector); //tricky: when will resetModel signals be emitted/received?
}
To copy to clipboard, switch view to plain text mode
What will happen if I call
model->setData()
model->setData()
To copy to clipboard, switch view to plain text mode
from the worker thread? When will the
beginResetModel()
beginResetModel()
To copy to clipboard, switch view to plain text mode
and
endResetModel()
endResetModel()
To copy to clipboard, switch view to plain text mode
be handled?
I guess model will have to be mutexed, but I don't know if it will handle those beginResetModel() / endResetModel() properly.
I keep reading http://doc.qt.nokia.com/latest/threads-qobject.html
and I cannot figure this out.
I guess resetModel signals will be either ignored OR handled later, when main thread's event loop will receive them (e.g views observing model will be notified too late)
Thanks a lot,
Chris
Bookmarks