简体   繁体   English

在 QAbstactItemView 中设置当前索引时如何不发出更改信号?

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

I'm programmatically changing the selected item with setCurrentIndex() of my Tree- and TableViews.我正在使用 Tree- 和 TableView 的setCurrentIndex()以编程方式更改所选项目。

If the current item has changed, a multitude of signals are emitted ( currentChanged() , currentColumnChanged , etc).如果当前项已更改,则会发出大量信号( currentChanged()currentColumnChanged等)。

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).我尝试在视图上使用activated() - 信号,但这似乎在不同平台上的行为方式不同(有时激活仅在双击时触发)。

Maybe, you could just block all signals while making your change?也许,您可以在进行更改时阻止所有信号?
QSignalBlocker or QObject::blockSignals could help: QSignalBlockerQObject::blockSignals可以帮助:

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

In your slot, you can use QObject::sender() to return the QObject to you.在您的插槽中,您可以使用 QObject::sender() 将 QObject 返回给您。 From there, there are a handful of ways you should be able to distinguish the source.从那里,您应该可以通过几种方法来区分来源。

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() .我最终做了什么,它在我的情况下有效,因为我有一个单线程应用程序,我创建了一个自定义变量programmatic-select ,我在调用setCurrentIndex()之前将其设置为 true 。 In the changeSelection() -slot I check this variable and do nothing if it is true.changeSelection() -slot 中,我检查这个变量,如果它是真的,什么也不做。

Very important for this to work is to connect the slot to the signal with the connection-type DirectConnection .要实现这一点非常重要的是使用连接类型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.在这种情况下,槽会在信号发出时同步执行,我确信我的变量值是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM