Search code examples
c++qtqlistview

QListView setModel problems calling via QMetaObject::invoke


Hi I have a QListView widget displayed correctly on my user interface.

I am registering a callback to a completely separate 3rd party library. This callback will be called on a completely separate thread to my user interface. I need this callback to interact with the QListView widget and set a new data model, so I believe I have to use

MyDataModel * model = new MyDataModel( ui->listViewWidget );
QMetaObject::invokeMethod( ui->listViewWidget, "setModel", Q_ARG( MyDataModel *, model ) );

However, It doesn't seem to work. i.e. no data is presented in the QListView widget. I've debugged the return value from QMetaObject::invokeMethod and it's returning false which suggests there's no method called "setModel" on the QListView. However, when I arrange for the callback to be called via the user interface thread, i.e. through a pushbutton on_clicked() event and make a call to

MyDataModel * model = new MyDataModel( ui->listViewWidget );
ui->listViewWidget->setModel( model );

This works perfectly, so there is a "setModel" method on the QListView..

Can someone please help me understand why QMetaObject::invokeMethod isn't working and maybe clear up wether I need to call invokeMethod in this way. i.e. are my thread assumptions correct about it needing to be ran on the event loop thread.

Yours, dazed and confused.. Mark.


Solution

  • The method QMetaObject::invokeMethod invokes only slot or signal on the object. Therefore your setModel must declared as slot. Also Q_ARG() takes a type name and a const reference of that type.