Qt Slots Keyword

 
Qt Slots Keyword Average ratng: 9,9/10 4279 reviews
  1. Qt Slots Keywords
  2. Qt Slots Keyword

Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. Signals and slots are made possible by Qt's meta-object system .

In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in. Asynchronous slots are marked by the keyword QNOREPLY in the method signature, before the void return type and the slot name. The quit slot in the D-Bus. This section describes the new style of connecting signals and slots introduced in PyQt4 v4.5. One of the key features of Qt is its use of signals and slots to communicate between objects. Their use encourages the development of reusable components. A signal is emitted when something of potential interest happens.

Introduction

In GUI programming, when we change one widget, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. For example, if a user clicks a Close button, we probably want the window's close() function to be called.

Other toolkits achieve this kind of communication using callbacks. A callback is a pointer to a function, so if you want a processing function to notify you about some event you pass a pointer to another function (the callback) to the processing function. The processing function then calls the callback when appropriate. While successful frameworks using this method do exist, callbacks can be unintuitive and may suffer from problems in ensuring the type-correctness of callback arguments.

Signals and Slots

In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal. Qt's widgets have many pre-defined slots, but it is common practice to subclass widgets and add your own slots so that you can handle the signals that you are interested in.

Signals and slots in Qt

The signals and slots mechanism is type safe: The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.) Since the signatures are compatible, the compiler can help us detect type mismatches when using the function pointer-based syntax. The string-based SIGNAL and SLOT syntax will detect type mismatches at runtime. Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. Qt's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time. Signals and slots can take any number of arguments of any type. They are completely type safe.

All classes that inherit from QObject or one of its subclasses (e.g., QWidget ) can contain signals and slots. Signals are emitted by objects when they change their state in a way that may be interesting to other objects. This is all the object does to communicate. It does not know or care whether anything is receiving the signals it emits. This is true information encapsulation, and ensures that the object can be used as a software component.

Slots can be used for receiving signals, but they are also normal member functions. Just as an object does not know if anything receives its signals, a slot does not know if it has any signals connected to it. This ensures that truly independent components can be created with Qt.

You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)

Together, signals and slots make up a powerful component programming mechanism.

Signals

Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses.

When a signal is emitted, the slots connected to it are usually executed immediately, just like a normal function call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop. Execution of the code following the emit statement will occur once all slots have returned. The situation is slightly different when using queued connections ; in such a case, the code following the emit keyword will continue immediately, and the slots will be executed later.

If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.

Signals are automatically generated by the moc and must not be implemented in the .cpp file. They can never have return types (i.e. use void ).

A note about arguments: Our experience shows that signals and slots are more reusable if they do not use special types. If QScrollBar::valueChanged () were to use a special type such as the hypothetical QScrollBar::Range, it could only be connected to slots designed specifically for QScrollBar . Connecting different input widgets together would be impossible.

Slots

A slot is called when a signal connected to it is emitted. Slots are normal C++ functions and can be called normally; their only special feature is that signals can be connected to them.

Since slots are normal member functions, they follow the normal C++ rules when called directly. However, as slots, they can be invoked by any component, regardless of its access level, via a signal-slot connection. This means that a signal emitted from an instance of an arbitrary class can cause a private slot to be invoked in an instance of an unrelated class.

You can also define slots to be virtual, which we have found quite useful in practice.

Compared to callbacks, signals and slots are slightly slower because of the increased flexibility they provide, although the difference for real applications is insignificant. In general, emitting a signal that is connected to some slots, is approximately ten times slower than calling the receivers directly, with non-virtual function calls. This is the overhead required to locate the connection object, to safely iterate over all connections (i.e. checking that subsequent receivers have not been destroyed during the emission), and to marshall any parameters in a generic fashion. While ten non-virtual function calls may sound like a lot, it's much less overhead than any new or delete operation, for example. As soon as you perform a string, vector or list operation that behind the scene requires new or delete , the signals and slots overhead is only responsible for a very small proportion of the complete function call costs. The same is true whenever you do a system call in a slot; or indirectly call more than ten functions. The simplicity and flexibility of the signals and slots mechanism is well worth the overhead, which your users won't even notice.

Note that other libraries that define variables called signals or slots may cause compiler warnings and errors when compiled alongside a Qt-based application. To solve this problem, #undef the offending preprocessor symbol.

Connecting the signal to the slot

Prior to the fifth version of Qt to connect the signal to the slot through the recorded macros, whereas in the fifth version of the recording has been applied, based on the signs.

Writing with macros:

Writing on the basis of indicators:

The advantage of the second option is that it is possible to determine the mismatch of signatures and the wrong slot or signal name of another project compilation stage, not in the process of testing applications.

An example of using signals and slots

For example, the use of signals and slots project was created, which in the main window contains three buttons, each of which is connected to the slot and these slots already transmit a signal in a single slot with the pressed button number.

Project Structure

Project Structure

According to the tradition of conducting lessons enclosing structure of the project, which is absolutely trivial and defaulted to the disgrace that will not even describe members of her classes and files.

mainwindow.h

Thus, the following three buttons - three slots, one signal at all three buttons, which is fed into the slot button and transmits the number buttons into a single slot that displays a message with the number buttons.

mainwindow.cpp

A file in this logic is configured as described in the preceding paragraphs. Just check the code and go to the video page, there is shown in detail the whole process, demonstrated the application, and also shows what happens if we make coding a variety of errors.

Video

Navigation:Up, Table of Contents, Bibliography, Index, Title Page
Laurent Rineau and Radu Ursu

Qt is a GUI toolkit1 forcross-platform application development.

16.1 Introduction

This chapter describes the Qt_widget package which providesan interface between CGAL and the GUI toolkit Qt .The Qt_widget package allows to build Qt applications showing two dimensional CGAL objects and algorithms.

The atom of the Qt user interface is called a widget.A widget receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Widgets are rectangular, and the different widgetsof an application are sorted in a Z-order. Widgetscan have a parent widget and children.A widget is clipped by its parent and by the widgets in front of it.

The most important class in the packageis the class Qt_widget which implements a widgetproviding a drawing area and output stream operators for CGAL two dimensional objects. Qt_widget also provideszooming and panning functionalities.

The Qt_widget allows to attach layers. Layers usuallydraw on the drawing area of the widget. Layers can be activated anddeactivated, and what you see in the drawing area is the overlay ofall attached activated layers. Layers can also be used for enteringinput, and CGAL provides input layers for the two-dimensionalCGAL objects.

The package includes also the class Qt_widget_standard_toolbar providing a standard toolbar for controlling the basic functionalityof the Qt_widget.

The following sections describe the main class as well as the helper classesin more detail and give examples that can be taken as starting points fornew applications.

Remark: The Qt_widget is distributed underthe QPL, which is Trolltech's open source license. For more detailson the QPL see http://www.trolltech.com/developer/licensing/qpl.html.

16.2 Qt_widget

The class Qt_widget is derived from the class QWidget which is the base class of all Qt user interface objects.

The Qt_widget provides output operators for two dimensional CGAL objects. There are operators defined for output of: points, segments, lines, rays, circles, triangles, rectangles, polygons, conics, and all type oftriangulations. Also some operators are defined to setQt_widget's properties, like background and fill color, aswell as line width and point size.

As the following examples show, simple applications can be writtenwithout the layers.

16.2.1 Example: Hello Segment

The first example draws a red segment on an orange background.

We follow the Qt naming conventions for material properties, forexample, the CGAL::BackgroundColor above.

All the drawing code should be put between Qt_Widget's lock() andunlock() functions. See the manual reference pages ofQt_widget. Doing like this, the window will be updated onlyonce, when Qt_widget finds the last unlock(). This way youcan avoid the window flickering.

This example has a severe drawback: when you resize the window it isempty, as nothing is redrawn. This style of programs makesonly sense, if you quickly want to validate output of a geometriccomputation. As in any event driven GUI application, Qt provides a callback mecanism sothat the window system can update the drawingwhenever necessary. This is the topic of the next example.

16.2.2 Example: Signals and Slots

This example is slightly more involved and uses thesignal/slots mecanism of Qt .

The main widget shows aDelaunay triangulation. Every time the mouse button is pressed over the widget, a point is input and inserted in the Delaunaytriangulation. The result of this insertion appears immediately.Furthermore, the drawing is updated every time the window is resized.

Qt applications are event driven and respond to user interaction.For example, when a user clicks on a menu item or on a toolbar button,the application executes some codes. The programmer of anapplication has to be able to relate events to the relevant code.Qt provide for that the signals/slots mecanism:

  • Signals.Each Qt widget declares a set of signals which, using thekeyword emit can be emitted by member functions under some circumstances. Signals are declared by using the keyword signals: just like anaccess specifier in your class declaration.
  • Slots.A slot is just a member function declared under a public (or private)slots section.
  • Connect.Signals and slots can be connected together using the method connect. This method needs to know four things: the objectthat sends out the signal, the signal, the object to which belong the connected slotand the slot connected to the signal.For instance, the statement:

    connects the signal redraw_on_back() of the widget widgetto the slot redraw_win() of the QMainWindowhis.Signals and slots can have any type of arguments, but a signal and aslot connected together must have the same arguments types.

    Every class that defines at least a signal or a slot must be derivedfrom the class QObject and must use the macro Q_OBJECTinside the private section of its declaration. You also need to runmoc, the Meta Object Compiler supplied with Qt on thefile that contains the class declaration.

    moc is a pre-compiler that produces the meta object codeof each class that uses the macro Q_OBJECT. This meta object code is needed by the signal/slot mecanism. There areseveral methods to compile the outputs of moc. In CGAL, we havechosen to include the outputs of moc in a source files. See theQt documentation on moc for other possibilities.

    The line //moc_source_file : tutorial2.C is for users that usemakefiles. This line tells to the CGAL makefile generator thattutorial2.C should be the file that moc should be run on.

    Let us come back to the control flow in the above example.The main widget of the application is the widget wof class My_window. The creator of My_window triggers the creation of a Qt_widgetaccessible through the pointer widget.When the mouse button is pressed in its drawing area,the Qt_widget emits the signal s_mousePressEvent(QMouseEvent*)connected to the slot mousePressEvent(QMouseEvent*) of My_window.This slot inserts the point in the Delaunay triangulationand calls the method redraw() of Qt_widget.The redraw() method of Qt_widgetemits the signal redraw_on_back(). This signal isconnected to the slot redraw_win()of My_window which actually draws the triangulation.Note that the Qt_widget emits the same signalredraw_on_back() when the window is resized. Thus,the signals/slots connection ensures that thetriangulation is redrawn each time the redrawing is needed.


    advanced
    There are several ways to draw something with Qt_widget. One wayis to use the signals redraw_on_back(), redraw_on_front().This way you can bring your drawings before all or after all theother drawings. An other option is to use the QPainter instance of Qt_widget that you can get calling get_painter()method. The most recommended way is to use layers, that are describedin the next section.
    advanced

    Note that in that example, the My_window constructor callsnew to allocate a new Qt_widget object but delete isnever called to deallocate it. This does not mean that there is amemory leak. It is in Qt's responsability to free widgets that have aparent. In that example the My_window object is the parent ofwidget and will deallocate it automatically at its destruction.

    16.3 Layers

    16.3.1 Using Layers to Draw

    In the examples from the previous section the code for drawing on thewidget was in the redraw_win() function. As soon as theapplications are more involved it leads to a more modular design ifone delegates the drawing task to layers. For example, if theapplication displays a Delaunay triangulation, the correspondingVoronoi diagram, and at the same time highlights the nearest vertex tothe mouse coordinates, it makes sense to have three independentlayers. Besides better code, layers have the advantage that they canbe activated and deactivated at runtime. Finally, more modularitymeans a higher potential for reuse.

    A layer can be attached to a Qt_widget. The redraw()member function of the Qt_widget callsthe method Qt_widget_layer::draw() of all attached layers, in theorder that they were attached. It is a very simple rule: the last layerattached will be drawn on top.

    Also a layer can be activated and deactivated. Only activelayers are drawn, and by default a layer is activated when it getsattached. Note that deactivating and activating do not influence theorder of layers. You can change the order only by attaching anddetaching it.

    CGAL provides a base class so that users can write their ownlayers. All the layers have to derive from this base classQt_widget_layer to have the functionality described.

    16.3.2 Example: Using a Layer to Draw

    Example

    This example defines a class derived fromQt_widget_layer. In the member function draw()is the code for drawing the triangulation. In My_Windowclass you need an instance of My_Layer and you will have to attach it, if you want to see what the layer draws on thescreen.

    As you see, this example is very similar to the previous one, butthe code for drawing the triangulation is no longer in theredraw_win() function, but in a layer.

    16.3.3 Using Layers to Build New Objects

    The main purpose of layers is to have more modular code for drawing onthe widget. Things are similar for handling input. In the previousexamples, input went through the Qt_widget::mousePressedEvent()callback, which interpreted the input. In applications where you havedifferent kinds of input, e.g., segments and polygons in anarrangement demo, this quickly leads to unreadable, difficult to maintaincode, especially as typically more than one event callback isinvolved. The proper way of decomposition, is delegationof the event handling to a layer.

    A layer for Qt_widget receives all the events fromQt_widget if it is active and can provide some functionalitylike input objects for Qt_widget. Notice that the layersreceive events in the order they have been attached. Layers can haveinternal state, because for entering complex objects it needs severalevents. Therefore layers must have functions to initialize state whenthey are activated and to clean up when they are deactivated.

    CGAL provides some predefined input layers. You can have a lot oflayers attached that could be active in the same time. You have totake care how you manage the events if you do not want to haveconflicts. A conflict is when two attached layers that are active need both the same event and getting and using it might not have such agood effect in your application. For example the predefined layers that builds a new line and a new circle produce bad visual effects when are both active.

    You can resolve conflicts by using layers exclusive. If you have several layers that can not be active at the same time without creatingconflicts, you can resolve that by letting the user not activatemore than one of those at a time.


    advanced
    In all the CGAL demos that are provided, the layers are used with atoolbar and buttons. To activate and deactivate a layer you have toclick one of the toolbar buttons. There are layers that need exclusive use. This is accomplished by grouping the buttons in one group, andmaking that group exclusive. The group class is QButtonGroup thatcomes with Qt .
    advanced

    We first show how to use layers and then how they work.

    16.3.4 Example: How to Use a Layer

    In the previous section, you could insert new points in thetriangulation by clicking on the widget. This example shows howthe same can be achieved with the help of a layer.

    We attach the predefined layer Qt_widget_get_point to the widget,and connect the signal emitted by the widget to the function thathandles the input. When the user clicks with the left mouse button,the layer creates a point and passes it to the widget. The widget thenemits a signal that gets passed to the connected slotMy_Window::get_new_object(CGAL::Object).

    The Qt_widget forwards all events that it receives to theattached and active layers. If a layer is attached but not active, itdoes not get the events. It is put in a passive state. Activating anddeactivating the layer does not mean that the object is destructed.

    Qt Slots Keyword

    16.3.5 Example: How Layers Work

    The following is an example of a layer that creates CGAL points whenthe user clicks the left mouse button over the widget.

    The Qt_widget forwards mouse and keyboard events to the attached layer.In the above example only the mousePressEvent member function is overloaded.

    Tools that create new CGAL objects, must call the member function Qt_widget::new_object(CGAL::Object). TheQt_widget then emits the signalnew_cgal_object(CGAL::Object). This signal can be routed toany slot of other object accepting a CGAL::Object, with thefollowing connect statement:

    The first argument must be a pointer to an instance of Qt_widget.In the example we connect it to MyWindow::get_new_object(CGAL::Object).

    16.4 The Standard Toolbar

    The Qt_widget allows to zoom and pan. This functionality is accessible through the class Qt_widget_standard_toolbar. The example further down shows how to use it in your application.

    The functionality of the toolbar is as follows from the left to right:

    History back:
    Go back into the transformation history
    History forth:
    Go forth into the transformation history
    Zoom In:
    The scaling factor is multiplied by two,keeping the same center.
    Zoom Out:
    The scaling factor is divided by two, keepingthe same center.
    Point tool:
    Deactivate the layers corresponding to thethree following buttons which form an exclusive group
    Focus on Point:
    Lets you choose the center of theregion where you want to focus.
    Focus on the Region:
    The area in the rectangle that you selected will be magnified to best fit in the window.
    Hand Tool:
    Used for translate. Click to select thefirst point of translation and drag to select the second point.
    Mouse Coordinates Layer:
    Mouse coordinates aredisplayed on the status bar of your window. You can deactivate thislayer if you click on it. To activate it again just click one more time.

    Example

    This example generates 100 points and inserts them in a Delaunaytriangulation. Using the standard toolbar you can zoom in, zoom out,translate.

    16.5 The Help Window

    We provide a class in the Qt_widget library that was taken froman example of Qt and adapted to our needs. This class has thefunctionality of a rich text browser with hypertext navigation. Youcan also PRINT, GO BACK, GO FORWARD or GO HOME. This class is calledQt_help_window and you can use it to display hypertext supportin your application. It is used in a lot of demos provided in thedistribution.

    Example

    16.6 Some Predefined Icons

    CGAL provides some icons defined in some header files. The icons arepixmaps, having the extension .xpm. Their location is /include/CGAL/IO/pixmaps.

    To use a pixmap in your code you have to include the right file, andto know the names of the pixmaps. The names of the pixmaps arecomposed of two parts, the name of the file and the tag xpm. So forexample the arrow pixmap has the name arrow_xpm, the linepixmap has the name line_xpm, and so on. There are also pixmaps files that contain small icons. The name of the smaller pixmaps contain a small at the middle of it like point_small_xpm.In the tutorials and demos, almost all the pixmaps are used for the toolbar buttons, like this:

    Example

    Qt Slots Keywords

    16.7 What Shall I Use?

    The previous sections presented different ways of writing Qt based applications. We recommend to use layers for the drawing task and forinput handling, even if you write tiny applications, because in generalthey grow over time. Layers are a little bit more overhead, but it pays off in the long run, as you then do not have to completelyreorganize your code, to add layers.

    Qt Slots Keyword

    Footnotes

    1http://www.trolltech.com
    Next chapter: Qt_widget
    Navigation:Table of Contents, Bibliography, Index, Title Page