How to not get changed-signals to be emitted when setting the current-index in QAbstactItemView?

423 views Asked by At

I'm programmatically changing the selected item with setCurrentIndex() of my Tree- and TableViews.

If the current item has changed, a multitude of signals are emitted (currentChanged(), currentColumnChanged, etc).

I'm listening to some of these signals in order to be informed when the user changes the selection.

Is there a way/a signal to distinguish between user-selected and programmatically selected events?

I tried using the activated()-signal on the views, but this seems to not behave the same way on different platforms (sometimes activated is triggered only if double-clicked).

3

There are 3 answers

4
MasterAler On BEST ANSWER

Maybe, you could just block all signals while making your change?
QSignalBlocker or QObject::blockSignals could help:

{
    const QSignalBlocker blocker(myWidget);
    myWidget->setCurrentIndex(someIndex);
}
3
mzimmers On

In your slot, you can use QObject::sender() to return the QObject to you. From there, there are a handful of ways you should be able to distinguish the source.

0
Patrick B. On

What I finally did, and it works in my case because I have a single-thread application, I created a custom variable programmatic-select, which I set to true before calling setCurrentIndex(). In the changeSelection()-slot I check this variable and do nothing if it is true.

Very important for this to work is to connect the slot to the signal with the connection-type DirectConnection. In this case the slot is executed synchronously when the signal is emitted and I'm sure the value of my variable is safe.