Example Slot Signal C++

Home > Articles > Programming > Python

In our example, we have a Receiver class that is implemented in C. This class defines a signal sendToQml and a slot receiveFromQml. Both have an integer parameter. The signal is sent to QML, and the slot is invoked from QML.

Every class can disconnect its slot or signal at any time when it is not interested in events anymore. If a class is destroyed, it automatically disconnects all of its signals and slots. If, in the above example, class Y is destroyed, it disconnects from Slot A in Class X and from Signal 1 in Class X and Z. Basic Features Creating a Slot. Each signal stores a list of slots. A slot defines what should be done when the signal is emitted. Typically an object emits the signal when it changes state. When a signal is emitted, the slots from the signal's slot list are executed, and sometimes a result is returned. Note that libsigc signals have absolutely nothing to do with POSIX signals. The C library function void (.signal(int sig, void (.func)(int)))(int) sets a function to handle signal i.e. A signal handler with signal number sig. (Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a. Signals and Events in Qt. But lets start with Qt. Qt offers two different systems for our needs, Qt signal/slot and QEvents. While Qt signal/slot is the moc driven signaling system of Qt (which you can connect to via QObject::connect), there is a second Event interface informing you about certain system-like events, such as QMouseEvent, QKeyEvent or QFocusEvent.

  1. Signals and Slots
< BackPage 4 of 6Next >
This chapter is from the book
Rapid GUI Programming with Python and Qt: The Definitive Guide to PyQt Programming

This chapter is from the book

This chapter is from the book

Rapid GUI Programming with Python and Qt: The Definitive Guide to PyQt Programming

Signals and Slots

Every GUI library provides the details of events that take place, such as mouse clicks and key presses. For example, if we have a button with the text Click Me, and the user clicks it, all kinds of information becomes available. The GUI library can tell us the coordinates of the mouse click relative to the button, relative to the button's parent widget, and relative to the screen; it can tell us the state of the Shift, Ctrl, Alt, and NumLock keys at the time of the click; and the precise time of the click and of the release; and so on. Similar information can be provided if the user 'clicked' the button without using the mouse. The user may have pressed the Tab key enough times to move the focus to the button and then pressed Spacebar, or maybe they pressed Alt+C. Although the outcome is the same in all these cases, each different means of clicking the button produces different events and different information.

The Qt library was the first to recognize that in almost every case, programmers don't need or even want all the low-level details: They don't care how the button was pressed, they just want to know that it was pressed so that they can respond appropriately. For this reason Qt, and therefore PyQt, provides two communication mechanisms: a low-level event-handling mechanism which is similar to those provided by all the other GUI libraries, and a high-level mechanism which Trolltech (makers of Qt) have called 'signals and slots'. We will look at the low-level mechanism in Chapter 10, and again in Chapter 11, but in this section we will focus on the high-level mechanism.

Every QObject—including all of PyQt's widgets since they derive from QWidget, a QObject subclass—supports the signals and slots mechanism. In particular, they are capable of announcing state changes, such as when a checkbox becomes checked or unchecked, and other important occurrences, for example when a button is clicked (by whatever means). All of PyQt's widgets have a set of predefined signals.

Whenever a signal is emitted, by default PyQt simply throws it away! To take notice of a signal we must connect it to a slot. In C++/Qt, slots are methods that must be declared with a special syntax; but in PyQt, they can be any callable we like (e.g., any function or method), and no special syntax is required when defining them.

Most widgets also have predefined slots, so in some cases we can connect a predefined signal to a predefined slot and not have to do anything else to get the behavior we want. PyQt is more versatile than C++/Qt in this regard, because we can connect not just to slots, but also to any callable, and from PyQt 4.2, it is possible to dynamically add 'predefined' signals and slots to QObjects. Let's see how signals and slots works in practice with the Signals and Slots program shown in Figure 4.6.

Both the QDial and QSpinBox widgets have valueChanged() signals that, when emitted, carry the new value. And they both have setValue() slots that take an integer value. We can therefore connect these two widgets to each other so that whichever one the user changes, will cause the other to be changed correspondingly:

Since the two widgets are connected in this way, if the user moves the dial—say to value 20—the dial will emit a valueChanged(20) signal which will, in turn, cause a call to the spinbox's setValue() slot with 20 as the argument. But then, since its value has now been changed, the spinbox will emit a valueChanged(20) signal which will in turn cause a call to the dial's setValue() slot with 20 as the argument. So it looks like we will get an infinite loop. But what happens is that the valueChanged() signal is not emitted if the value is not actually changed. This is because the standard approach to writing value-changing slots is to begin by comparing the new value with the existing one. If the values are the same, we do nothing and return; otherwise, we apply the change and emit a signal to announce the change of state. The connections are depicted in Figure 4.7.

Figure 4.7 The signals and slots connections

Now let's look at the general syntax for connections. We assume that the PyQt modules have been imported using the from ... import * syntax, and that s and w are QObjects, normally widgets, with s usually being self.

The signalSignature is the name of the signal and a (possibly empty) comma-separated list of parameter type names in parentheses. If the signal is a Qt signal, the type names must be the C++ type names, such as int and QString. C++ type names can be rather complex, with each type name possibly including one or more of const, *, and &. When we write them as signal (or slot) signatures we can drop any consts and &s, but must keep any *s. For example, almost every Qt signal that passes a QString uses a parameter type of const QString&, but in PyQt, just using QString alone is sufficient. On the other hand, the QListWidget has a signal with the signature itemActivated(QListWidgetItem*), and we must use this exactly as written.

PyQt signals are defined when they are actually emitted and can have any number of any type of parameters, as we will see shortly.

The slotSignature has the same form as a signalSignature except that the name is of a Qt slot. A slot may not have more arguments than the signal that is connected to it, but may have less; the additional parameters are then discarded. Corresponding signal and slot arguments must have the same types, so for example, we could not connect a QDial's valueChanged(int) signal to a QLineEdit's setText(QString) slot.

In our dial and spinbox example we used the instance.methodName syntax as we did with the example applications shown earlier in the chapter. But when the slot is actually a Qt slot rather than a Python method, it is more efficient to use the SLOT() syntax:

We have already seen that it is possible to connect multiple signals to the same slot. It is also possible to connect a single signal to multiple slots. Although rare, we can also connect a signal to another signal: In such cases, when the first signal is emitted, it will cause the signal it is connected to, to be emitted.

Connections are made using QObject.connect(); they can be broken using QObject.disconnect(). In practice, we rarely need to break connections ourselves since, for example, PyQt will automatically disconnect any connections involving an object that has been deleted.

So far we have seen how to connect to signals, and how to write slots—which are ordinary functions or methods. And we know that signals are emitted to signify state changes or other important occurrences. But what if we want to create a component that emits its own signals? This is easily achieved using QObject.emit(). For example, here is a complete QSpinBox subclass that emits its own custom atzero signal, and that also passes a number:

We connect to the spinbox's own valueChanged() signal and have it call our checkzero() slot. If the value happens to be 0, the checkzero() slot emits the atzero signal, along with a count of how many times it has been zero; passing additional data like this is optional. The lack of parentheses for the signal is important: It tells PyQt that this is a 'short-circuit' signal.

A signal with no arguments (and therefore no parentheses) is a short-circuit Python signal. When such a signal is emitted, any data can be passed as additional arguments to the emit() method, and they are passed as Python objects. This avoids the overhead of converting the arguments to and from C++ data types, and also means that arbitrary Python objects can be passed, even ones which cannot be converted to and from C++ data types. A signal with at least one argument is either a Qt signal or a non-short-circuit Python signal. In these cases, PyQt will check to see whether the signal is a Qt signal, and if it is not will assume that it is a Python signal. In either case, the arguments are converted to C++ data types.

Here is how we connect to the signal in the form's __init__() method:

Again, we must not use parentheses because it is a short-circuit signal. And for completeness, here is the slot it connects to in the form:

If we use the SIGNAL() function with an identifier but no parentheses, we are specifying a short-circuit signal as described earlier. We can use this syntax both to emit short-circuit signals, and to connect to them. Both uses are shown in the example.

If we use the SIGNAL() function with a signalSignature (a possibly empty parenthesized list of comma-separated PyQt types), we are specifying either a Python or a Qt signal. (A Python signal is one that is emitted in Python code; a Qt signal is one emitted from an underlying C++ object.) We can use this syntax both to emit Python and Qt signals, and to connect to them. These signals can be connected to any callable, that is, to any function or method, including Qt slots; they can also be connected using the SLOT() syntax, with a slotSignature. PyQt checks to see whether the signal is a Qt signal, and if it is not it assumes it is a Python signal. If we use parentheses, even for Python signals, the arguments must be convertible to C++ data types.

We will now look at another example, a tiny custom non-GUI class that has a signal and a slot and which shows that the mechanism is not limited to GUI classes—any QObject subclass can use signals and slots.

Both the rate() and the setRate() methods can be connected to, since any Python callable can be used as a slot. If the rate is changed, we update the private __rate value and emit a custom rateChanged signal, giving the new rate as a parameter. We have also used the faster short-circuit syntax. If we wanted to use the standard syntax, the only difference would be that the signal would be written as SIGNAL('rateChanged(float)'). If we connect the rateChanged signal to the setRate() slot, because of the if statement, no infinite loop will occur. Let us look at the class in use. First we will declare a function to be called when the rate changes:

And now we will try it out:

This will cause just one line to be output to the console: 'TaxRate changed to 8.50%'.

In earlier examples where we connected multiple signals to the same slot, we did not care who emitted the signal. But sometimes we want to connect two or more signals to the same slot, and have the slot behave differently depending on who called it. In this section's last example we will address this issue.

The Connections program shown in Figure 4.8, has five buttons and a label. When one of the buttons is clicked the signals and slots mechanism is used to update the label's text. Here is how the first button is created in the form's __init__() method:

All the other buttons are created in the same way, differing only in their variable name and the text that is passed to them.

We will start with the simplest connection, which is used by button1. Here is the __init__() method's connect() call:

We have used a dedicated method for this button:

Connecting a button's clicked() signal to a single method that responds appropriately is probably the most common connection scenario.

But what if most of the processing was the same, with just some parameterization depending on which particular button was pressed? In such cases, it is usually best to connect each button to the same slot. There are two approaches to doing this. One is to use partial function application to wrap a slot with a parameter so that when the slot is invoked it is parameterized with the button that called it. The other is to ask PyQt to tell us which button called the slot. We will show both approaches, starting with partial function application.

Back on page 65 we created a wrapper function which used Python 2.5's functools.partial() function or our own simple partial() function:

Using partial() we can now wrap a slot and a button name together. So we might be tempted to do this:

Unfortunately, this won't work for PyQt versions prior to 4.3. The wrapper function is created in the connect() call, but as soon as the connect() call completes, the wrapper goes out of scope and is garbage-collected. From PyQt 4.3, wrappers made with functools.partial() are treated specially when they are used for connections like this. This means that the function connected to will not be garbage-collected, so the code shown earlier will work correctly.

Example Slot Signal C++ Jammer

For PyQt 4.0, 4.1, and 4.2, we can still use partial(): We just need to keep a reference to the wrapper—we will not use the reference except for the connect() call, but the fact that it is an attribute of the form instance will ensure that the wrapper function will not go out of scope while the form exists, and will therefore work. So the connection is actually made like this:

When button2 is clicked, the anyButton() method will be called with a string parameter containing the text 'Two'. Here is what this method looks like:

Qt Signal Slot Example C++

We could have used this slot for all the buttons using the partial() function that we have just shown. And in fact, we could avoid using partial() at all and get the same results:

Here we've created a lambda function that is parameterized by the button's name. It works the same as the partial() technique, and calls the same anyButton() method, only with lambda being used to create the wrapper.

Both button2callback() and button3callback() call anyButton(); the only difference between them is that the first passes 'Two' as its parameter and the second passes 'Three'.

If we are using PyQt 4.1.1 or later, and we use lambda callbacks, we don't have to keep a reference to them ourselves. This is because PyQt treats lambda specially when used to create wrappers in a connection. (This is the same special treatment that is expected to be extended to functools.partial() in PyQt 4.3.) For this reason we can use lambda directly in connect() calls. For example:

The wrapping technique works perfectly well, but there is an alternative approach that is slightly more involved, but which may be useful in some cases, particularly when we don't want to wrap our calls. This other technique is used to respond to button4 and to button5. Here are their connections:

Notice that we do not wrap the clicked() method that they are both connected to, so at first sight it looks like there is no way to tell which button called the clicked() method.* However, the implementation makes clear that we can distinguish if we want to:

Inside a slot we can always call sender() to discover which QObject the invoking signal came from. (This could be None if the slot was called using a normal method call.) Although we know that we have connected only buttons to this slot, we still take care to check. We have used isinstance(), but we could have used hasattr(button, 'text') instead. If we had connected all the buttons to this slot, it would have worked correctly for them all.

Some programmers don't like using sender() because they feel that it isn't good object-oriented style, so they tend to use partial function application when needs like this arise.

There is actually one other technique that can be used to get the effect of wrapping a function and a parameter. It makes use of the QSignalMapper class, and an example of its use is shown in Chapter 9.

It is possible in some situations for a slot to be called as the result of a signal, and the processing performed in the slot, directly or indirectly, causes the signal that originally called the slot to be called again, leading to an infinite cycle. Such cycles are rare in practice. Two factors help reduce the possibility of cycles. First, some signals are emitted only if a real change takes place. For example, if the value of a QSpinBox is changed by the user, or programmatically by a setValue() call, it emits its valueChanged() signal only if the new value is different from the current value. Second, some signals are emitted only as the result of user actions. For example, QLineEdit emits its textEdited() signal only when the text is changed by the user, and not when it is changed in code by a setText() call.

If a signal–slot cycle does seem to have occurred, naturally, the first thing to check is that the code's logic is correct: Are we actually doing the processing we thought we were? If the logic is right, and we still have a cycle, we might be able to break the cycle by changing the signals that we connect to—for example, replacing signals that are emitted as a result of programmatic changes, with those that are emitted only as a result of user interaction. If the problem persists, we could stop signals being emitted at certain places in our code using QObject.blockSignals(), which is inherited by all QWidget classes and is passed a Boolean—True to stop the object emitting signals and False to resume signalling.

This completes our formal coverage of the signals and slots mechanism. We will see many more examples of signals and slots in practice in almost all the examples shown in the rest of the book. Most other GUI libraries have copied the mechanism in some form or other. This is because the signals and slots mechanism is very useful and powerful, and leaves programmers free to focus on the logic of their applications rather than having to concern themselves with the details of how the user invoked a particular operation.

Related Resources

  • Online Video $239.99
  • eBook (Watermarked) $31.99
  • Book $39.99

Written by Sarah Thompson - sarah@telergy.com

You can find the latest version of this documentation athttp://sigslot.sourceforge.net/

For downloads, mailing lists, bug reports, help and support, or anything similar, go tohttp://sourceforge.net/projects/sigslot

The author's personal web site is athttp://www.findatlantis.com/

Contents

Introduction

The C++ programming language is an amazingly capable beast. However, it is no panacea for all ills - it is just as possible to write spaghetti in this language as it is in any other (arguably easier than some).

C++ is usually described as an object-oriented language. Its claim to object orientation is generally appropriate, but unlike some other languages, C++ doesn't actually enforce good practice. Whether or not you think this is a good thing or a bad thing is up to you, I'm not interested in starting a religious war here, so I'll neatly sidestep the issue by changing the subject for a moment.

Flame me, flame me not

Before you lock & load your rocket launchers, folks, I'm using the MFC by way of example only. The signal/slot library is ISO C++ compliant (at least where possible) and will work on pretty much anything. All you need is a reasonable C++ compiler that supports templates. You don't need partial template specialisation support, so VC6 and VC.NET are both fine.

The Microsoft Foundation Classes (MFC) are a nightmarish mess. I'll say it again - the MFC is a programmer's nightmare. At one point it almost inspired me to give up programming and take up something less irritating, like becoming a professional 'nut the javelin' player or move to Outer Patagonia and become a cat wrangler. Nevertheless, the MFC is capable of supporting most things that you might want to do with the Windows platform, at the price of a little slice of one's sanity.

There are two reasons why the MFC is so painful. Firstly, it too-often seems to require an uphill struggle in order to get the simplest things to work. Secondly, it is very difficult and/or evilly messy trying to get disparate classes within an MFC application to talk to each other. The former problem is down to the design of the MFC itself - only deep experience using it can really get around this. The second problem is a consequence of the MFC being quite a thin wrapper around the underlying Windows SDK - getting one window to talk to another window often requires resorting to oldfashioned Windows 3.1 techniques like ::SendMessage() or ::PostMessage() with custom Windows messages. Yuck. That kind of code is difficult to write, difficult to debug, hard to maintain and generally speaking a Bad Idea.

Take a simple example. Imagine we want to create a dialog box, with a number displayed on it, and a couple of buttons which let you increment or decrement the number:

If you're going to program the MFC way, you'd slap in that dialog to the dialog editor in Visual Studio, then add message handlers for the 'Increment' and 'Decrement' buttons that use the MFC's DDX mechanism to update the number in the edit box. Easy enough you might think, but where's the reusability? I signed up to the card-carring object orientation movement on the basis that it was supposed to make it easier to reuse my code, or to use components written by other people with a minimum of pain. The MFC way of working might as well be Visual Basic, requiring cut-and-paste code reuse. Evil, nasty, bad.

What, in circumstances like this, I'd really like to be able to do is turn the numeric edit control and the increment/decrement buttons into genuinely reusable components in their own right. By component, I don't mean COM object or Active-X control, just a simple, lightwight, reusable C++ class.

The MFC way of doing this, reasonably enough, would be to inherit from the basic controls (CEdit and CButton in this example), then give those classes a common interface of some kind. You might, sensibly enough, add a couple of entry points to your numeric edit class, 'CMyEdit::Increment()' and 'CMyEdit::Decrement()', say, then in your CIncrementButton and CDecrementButton classes hold a pointer to a CMyEdit so that they can implement OnOK() handlers that call the relevant member functons in CMyEdit. This is fractionally better, but still not at all nice. What I'd like is to be able to create a general purpose button, that, er, well, 'clicks' when you click it, and an edit box that can be directed to do a variety of things remotely, such as increment, decrement, copy to clipboard, go back to zero, etc. The edit box shouldn't need to care what is calling it. Just as importantly, buttons shouldn't have to care what they are calling either, so the same, unmodified button class can be used to increment, decrement or clear the control this afternoon, and next week end up wired to my internet compliant remote garage door opener. Or whatever. But the important thing is that only the user of the classes should need to know (or care) how they are wired up - the classes themselves, to be genuinely reusable, should be above that kind of thing.

Speaking as an ex-hardware designer, I'd like software components to have pins around their edges, like ICs, so they can be 'wired up', but otherwise should be well behaved. To design a board with, say, an 8 bit microcontroller on it is made much easier by knowing that pin 34 is always Chip Enable (or something). I don't want to know how that pin is wired internally - I just want to know that it will work when I send a signal into it.

Credit where credit's due: Qt

The Qt library (see http://www.troll.no/ for further information) was the first attempt I personally ever saw at extending C++ by adding a 'signal-slot' metaphor to the language's existing repertoire of programming techniques.

Qt was a revelation to me when I started using it, which must be something like three years ago at the time of writing. For once, I could write code relatively quickly, with a reasonable chance of it actually working the way I intended it without the days of pushing water uphill with a fork that was usually required to breathe life into MFC applications. The thing that impressed me most about Qt was its signal/slot metaphor. Qt uses a preprocessor, moc, to preprocess an extended C++ syntax. Put briefly, any Qt class can possess one or more signals, and one or more slots. A slot is very much like an ordinary member function. Indeed, slots can be called directly as member functions, with the only syntactic difference being the need for the slotskeyword in the class header file. A signal in Qt is declared much like a member function, except that it has no local implementation - it just appears like a member function prototype in the header file. Signals can be connected, using the connect function, with any number of slots in any other C++ objects. When a signal is emitted, using the new keyword emit, all connected slots get called.

In principle, signals and slots are a bit like pointers, where a signal can be 'wired up' after the fact to the slots that need to be informed whenever it is emitted. Using pointers, be they function pointers, pointers to classes or pointers to class member functions, does have its own risks, of course. There are no guarantees, given such a pointer, that using it is safe - it is always necessary for the programmer to know, given the context of its use, that it is safe. Most programmers get this right nearly all of the time, of course. But when we get it wrong, our code goes horrendously bang, usually five minutes before a demo to the visiting CEO of your biggest client. I always tend to favour situations where the programming language picks up automatically on that kind of thing.

Signals and slots, in my opinion, have three major advantages over pointers:

Syntactically Neater. Signals & slots make for very readable code. You define your signals. You define your slots. You wire them up. That's it, and no surprises.

Inherently Robust. This is the neat part: when either end of a signal/slot connection is destroyed, the connection is automatically removed. It is therefore impossible to emit a signal and have it arrive at a class that has already been deleted. Best of all, you don't need to write any explicit cleanup code - if the caller goes out of scope, no problem. If the callee goes out of scope, no problem either.

Booster

Easier code reuse. Since the thing that has to type-agree is the signal and the slot, not the whole class interface, it is much easier to plug together disparate classes that had never initially been intended to work in that way. (Take it from me - I've done this in anger, and it really does make a difference)

I really like Qt. I think the people at TrollTech in Norway have done a brilliant job - their class library is far and away the best GUI library I've ever used (though the .NET framework actually comes remarkably close, but enough flame bait for one article).

More credit where more credit's due: Boost, GTK and James Slaughter

When I was working at Trayport in London, a coworker there, James Slaughter, got me interested in the Boost libraries, and was largely responsible for reawakening my interest in C++ as a programming language with real promise. Thank you James, if you're reading this. (As an aside, I was previously getting very interested in Objective CaML, but that's for another article at another time).

When I evangelised Qt within James' earshot, he opined that Qt was pretty good, but he wasn't keen on the moc preprocessor. Rightly enough, moc has a rather bad rep for mangling attempts to use templates in Qt-enabled classes, and it's always irritating to need to hack build scripts to preprocess code. James did mention that type safe signal/slot functionality was possible in C++. I'd kind of thought about it myself, but hadn't initially realised that it really was possible to do without something like moc.

I did a bit of a net search, and it seemed that a couple of people had put together C++ signal/slot libraries. One was in the pipeline for adoption by Boost (still is, at the time of writing). Another is due to the GTK bunch, as part of the GTK's C++ wrapper. Both were a little heavyweight for my needs (writing MFC code whilst staying at least a bit sane), and neither looked like good candidates for a straightforward Windows port.

I chose to write my own instead. The rest is history.

Downloading the sigslot library

You can download sigslot from the project downloads page.

Documentation

Detailed documentation for sigslot is currently in LaTeX format. I haven't yet decided whether to convert this to HTML and post it here, or to laboriously glomm it into the documentation system at SourceForge. For the moment, you can get the PDF version from the link below. If you want the LaTeX source, or are feeling kind and generous and would like to contribute by doing this conversion, please email me.

Reporting Bugs

Example slot signal c++ signal

Qt Signal Slot Example C

So far, sigslot has been tested on VC++ 6.0 on Win32, VC++ 7.0 (Unmanaged) on Win32, gcc under Cygwin and Intel C++ on Win32. It has also been used in some real code without problems. However, it is relatively new, so tread carefully and please make sure to report any bugs, fixes or feature requests to the project team. By preference, please do this through the bug tracking system at SourceForge.

License

Example Slot Signal C++ Booster

The sigslot library has been placed in the public domain. This means that you are free to use it however you like.

The author takes no responsibility or liability of any kind for any use that you may make of this library.

If you screw up, it's your fault.

If the library screws up, you got it for free, so you should have tested it better - it's still your responsibility.