Qt disconnect не работает

Qt 5 Disconnect lambda

В документации на Qt 5 по сигналам и слотам https://wiki.qt.io/New_Signal_Slot_Syntax написано следующее:

Disconnecting in Qt5

Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card) In particular, does not work with static function, functors or lambda functions.

Я использовал лямбда выражение:

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Сконструировать \lambda-вызов и вычислить его значение Lambda
Задание Для выражения из таблицы согласно номеру варианта сконструировать \lambda — вызов и.

Проблема с Disconnect
Здравствуйте. Подскажите пожалуйста. Написал прогу работает через Telnet, соединение проходит.

Disconnect в NetworkBehaviour
Подскажите, а как сделать отключение от сервера в NetworkBehaviour? Я кажется совсем одичал 😀 .

Использование disconnect
Допустим, есть какой-то коннект: connect(flag, SIGNAL(toggled(bool)), this.

Решение

kavashige, QObject::connect возвращает handle соединения. Его можно потом передать в функцию QObject::disconnect, чтобы разорвать соединение.

Добавлено через 1 минуту
Там же прямо в следующей строчке написано как поступать с лямбдами и прочим!

disconnect Коннекта!
Привет. Обязательно ли делать disconnect в сигнально\слотовой связи? сейчас при отладке сделал.

Disconnect и его использования
Доброго времени суток, к примеру, я создаю окно MyWindow *my = new MyWindow(this); connect(my.

Disconnect слота по ссылке не работает
Привет всем, мне нужно было отключить выделения при нажатии на заголовок таблицы, нашел вот такой.

Network.Disconnect является устаревшим
Здравствуйте, мне нужно сделать так, чтобы если у игрока оставалось 0 хп , его отключало от.

Источник

Qt disconnect не работает

I have a number of different signals connected to one slot. Is there any disconnect function that can be used to disconnect everything connected to a specific slot?

@QObject::connect(object1, SIGNAL(a()), receiver, SLOT(slot()));
QObject::connect(object2, SIGNAL(b()), receiver, SLOT(slot()));
QObject::connect(object3, SIGNAL(c()), receiver, SLOT(slot()));@

Now I want a function to disconnect all the signals from receiver’s slot(). There is an option:

but this connects only the signals in the current object. I want to disconnect ALL signals, without knowing the objects that are connected to the slot.

If you deleted receiver (the parent class), then all of the signals/slots associated with that object will be deleted as well on cleanup. or delete the children classes. that’s the only way I can think of doing it.

I’ve looked for a method that does what you want (including tricks with the Qt Meta-Object system) for quite a while and haven’t found one.

Ahhh. Something like this is quite common in the system I writing. And dvez43, I can’t delete anything since I have to use the objects later on.

May this help
@QObject::connect(object1, SIGNAL(a()), receiver, SIGNAL(LocalProxySignal()));
QObject::connect(object2, SIGNAL(b()), receiver, SIGNAL(LocalProxySignal()));
QObject::connect(object3, SIGNAL(c()), receiver, SIGNAL(LocalProxySignal()));

QObject::connect(receiver, SIGNAL(LocalProxySignal()), receiver, SLOT(slot()));@

. and disconnect
@QObject::disconnect(receiver, SLOT(slot()));@

Interesting. Yes this might work, but it’s a small overhead; so not a very “clean” solution. But thanks, this will do for now. Is there a reason why there isn’t a function like this? Should this maybe be reported as a “new feature”?

Источник

Qt/C++ — Урок 078. Не мешайте старый синтаксис сигналов на макросах SIGNAL SLOT и слотов с новым синтаксисом на указателях

Все мы знаем, что в Qt существует два синтаксиса сигналов и слотов:

Но также, как не стоит мешать пиво с водкой, с таким же успехом не стоит смешивать два синтаксиса в рамках одного проекта.

Конечно, существуют проекты, в которых написано достаточно много кода и сделать полный рефакторинг по смене всего синтаксиса является довольно накладной работой, но если вы, постепенно дополняя проект, переходите на новый синтаксис, постарайтесь в рамках одного сигнала слотового соединения обновить все места кода с данным соединением на новый синтаксис.

Дело в том, что для обоих случаев ( SINGAL SLOT макросы и синтаксис на указателях ) формируется иное содержание moc файлов , что приводит к тому, что смешанное использование методов connect и disconnect не работает так, как ожидалось бы. А если быть точным, то метод disconnect не будет работать в том случае, если connect был вызван с использованием макросов, а disconnect был вызван с использованием указателей.

Пример

Создадим пробный проект, в котором будет окно и одна кнопка. Добавим в окне слот. И в конструкторе класса окна проверим четыре комбинации подключения сигнала кнопки к слоту окна:

  1. connect SIGNAL SLOT — disconnect SIGNAL SLOT
  2. connect SIGNAL SLOT — disconnect синтаксис на указателях
  3. connect на указателях — disconnect на указателях
  4. connect на указателях — disconnect SIGNAL SLOT

widget.h

widget.cpp

Вывод

Таким образом получается, что пара connect SINGAL SLOT — disconnect на указателях даёт не тот результат, который ожидался. И по факту слот остаётся подключённым.

Поэтому новичкам рекомендую внимательно относится к этому нюансу работы с сигналами и слотами в Qt.

Рекомендуем хостинг TIMEWEB

Рекомендуемые статьи по этой тематике

Источник

How to disconnect a signal with a slot temporarily in Qt?

I connect a slot with a signal. But now I want to disconnect them temporarily.

Here is part of my class declaration:

In the constructor of frmMain , I connect myReadTimer with a slot so that ReadMyCom will be called every 5 seconds:

But, in slot on_btnDownload_clicked . I don’t want myReadTimer to emit any signal in on_btnDownload_clicked ‘s scope. So I want to disconnect them at the beginning of on_btnDownload_clicked and reconnect them in the end. Like this:

I searched in Stackoverflow and got some answer like call the QObject destructor. But I don’t know how to use it.

I also tried to use disconnect , like:

But it still not work. So could any one help me how to do this?

2 Answers 2

There is a very nice function in QObject that comes in handy every now and again: QObject::blockSignals()

Here’s a very simple fire-and-forget class that will do what you want. I take no credit for it’s design, I found it on the internet somewhere a long time ago. Be careful though, it will block all signals to all objects. If this is not what you want, you can modify the class to suit your needs.

Usage, in your case, becomes trivial

UPDATE:

I see that from Qt 5.3, a very similar class has been offically added to the API. It does a similar job as the one above with a slightly bigger feature-set. I suggest you use the official QSignalBlocker class instead in order to keep your codebase up-to-date with any API changes.

Usage, however, remains exactly the same.

Disconnect/reconnect syntax

There are many ways to call disconnect, depending on exactly what you want disconnected. See the QObject documentation page for an explanation of how they work.

Here’s an example using 0 to mean «disconnect all slots.»

Or you can specify the exact signal-slot pair to disconnect by copying your ‘connect’ syntax, like this:

Stopping the timer

Since you’re working with a timer, this may be simpler:

Differences from your original approach:

  • Since you’re stopping and restarting the timer, the next time it fires will be interval after your slot function finishes.

Do you need to do anything special at all?

In a single-threaded Qt application, if you’re already handling a signal, another signal won’t «jump in the middle» of that code. Instead it’ll be queued up as an even to handle immediately after the current slot returns.

So perhaps you don’t need to stop or disconnect your timer at all.

Differences from your original approach:

  • If on_btnDownload_clicked takes a while to execute, you might have multiple ReadMyCom events queued up after on_btnDownload_clicked completes. (Note that at this point you’d have an operation that basically «locks up» your GUI for a while anyway; it may make more sense to refactor the function or give it its own thread.)

Источник

How to disconnect all signals while function is running in Qt?

I have been searching for tow days, but nothing that could help me. I want to disconnect all signals while functions are running. The main trick is the class that emits signal and the class that receives it are both different classes. I have a QPushButton in class that emits signals, and my custom class Screen which receives signals, they are both connected.

The class that manages events (class sender)

I was trying to use disconnect , and nothing. Was trying to use QObject::blockSignals() the same story.

Please any help would be great!!

UPDATE

2 Answers 2

Update

I’ve taken the more recent code you’ve posted and made some changes to it.

Summary

Let’s start with your comment:

i can’t reach «GO» button from the screen.cpp unless it is global. And i do not want to use any globals.

You’re on the right track in trying to avoid globals. However, I don’t think your Screen class really needs to know about your GO button. Instead, you could do what I suggested in our discussion, which is that, instead of connect ing your GO button directly to your Screen ‘s generate() slot, you should instead connect the button to a separate on_button_clicked event handler in your Game class that will:

  1. disable or disconnect the GO button,
  2. call your screen ‘s generate() method, and
  3. re-enable or re-connect the button after generate() returns.

This would also imply that generate() may no longer need to be a slot, but that’s up to you.

Your Code — With My Suggested Updates

I’ve made the following changes:

In game.h , I added a slot to the Game class:

In game.cpp , I added the implementation as follows:

And also replaced your constructor’s QObject::connect call with the one below:

Now, you can keep your Screen class unaware of the existence of your GO button, which means less coupling and complexity, but still get to prevent the user from using your button in the meantime, which is what you want.

Original Response

Basically, you need to use QObject::disconnect as follows:

You can do this in the slot after the event gets handled.

Disconnecting the signals/slots between the objects of interest is a better approach than trying to disconnect all signals globally for the whole application for several reasons, including unintended side-effects that may lead to bugs or other unexpected behavior.

In your particular example, you have:

So to disconnect, you may only need to write this when you start processing:

And then re-connect after you’re done processing.

Or, as @Matt said in a comment, you could simply disable the button widget in the user interface and not mess around with the signals. If the user cannot click the button, then the signal cannot be emitted by the user.

This is probably a simpler and more reliable solution.

Signal-Blocking Update

If you still want to connect/disconnect and you’re using Qt 5.3+, then you should use QSignalBlocker , which also takes care of preserving and restoring things back to their previous state. Quoting from their docs:

Working Sample Code

A short example app consisting of a window with a QPushButton and a QListWidget in a QMainWindow follows below.

mainwindow.cpp

mainwindow.h

main.cpp

mainwindow.ui

You can copy-paste the contents of the .ui file to reproduce the simple layout if needed. It’s below:

Источник

Читайте также:  Как можно отремонтировать монитор
Оцените статью