Qt Private Slot Example

Qt Private Slot Example Average ratng: 4,8/5 826 reviews

Similar to QPRIVATEPROPERTY, QPRIVATESLOT is used when you have a slot in a private class that you want to be considered part of the API of the corresponding public class, without affecting the interface (and hence binary compatibility) of that public class. We implement the zooming slots using the private scaleImage function. We set the scaling factors to 1.25 and 0.8, respectively. We set the scaling factors to 1.25 and 0.8, respectively. These factor values ensure that a Zoom In action and a Zoom Out action will cancel each other (since 1.25. 0.8 1), and in that way the normal image size.

Qt5 alpha has been released. One of the features which I have been working on is a new syntax for signals and slot.This blog entry will present it.

Here is how you would connect a signal to a slot:

What really happens behind the scenes is that the SIGNAL and SLOT macros will convert their argument to a string. Then QObject::connect() will compare those strings with the introspection data collected by the moc tool.

What's the problem with this syntax?

While working fine in general, we can identify some issues:

  • No compile time check: All the checks are done at run-time by parsing the strings. That means if you do a typo in the name of the signal or the slot, it will compile but the connection will not be made, and you will only notice a warning in the standard output.
  • Since it operates on the strings, the type names of the slot must match exactly the ones of the signal. And they also need to be the same in the header and in the connect statement. This means it won't work nicely if you want to use typedef or namespaces

In the upcoming Qt5, an alternative syntax exist. The former syntax will still work. But you can now also use this new way of connecting your signals to your slots:

Which one is the more beautiful is a matter of taste. One can quickly get used to the new syntax.

So apart from the aesthetic point of view, let us go over some of the things that it brings us:

Compile-time checking

You will get a compiler error if you misspelled the signal or slot name, or if the arguments of your slot do not match those from the signal.
This might save you some time while you are doing some re-factoring and change the name or arguments of signals or slots.

An effort has been made, using static_assert to get nice compile errors if the arguments do not match or of you miss a Q_OBJECT

Arguments automatic type conversion

Not only you can now use typedef or namespaces properly, but you can also connect signalsto slots that take arguments of different types if an implicit conversion is possible

In the following example, we connect a signal that has a QString as a parameter to a slot that takes a QVariant. It works because QVariant has an implicit constructor that takes a QString

Connecting to any function

As you might have seen in the previous example, the slot was just declared as publicand not as slot. Qt will indeed call directly the function pointer of the slot, andwill not need moc introspection anymore. (It still needs it for the signal)

Qt Private Slot Examples

But what we can also do is connecting to any function or functor:

This can become very powerful when you associate that with boost or tr1::bind.

Qt Private Slot Example For Real

C++11 lambda expressions

Everything documented here works with the plain old C++98. But if you use compiler that supportsC++11, I really recommend you to use some of the language's new features.Lambda expressions are supportedby at least MSVC 2010, GCC 4.5, clang 3.1. For the last two, you need to pass -std=c++0x asa flag.

You can then write code like:

This allows you to write asynchronous code very easily.

Update: Also have a look what other C++11 features Qt5 offers.

It is time to try it out. Check out the alpha and start playing. Don't hesistate to report bugs.

Home All Classes Main Classes Annotated Grouped Classes Functions

In this example we introduce a timer to implement animated shooting.

  • t11/lcdrange.h contains the LCDRangeclass definition.
  • t11/lcdrange.cpp contains the LCDRangeimplementation.
  • t11/cannon.h contains the CannonField classdefinition.
  • t11/cannon.cpp contains the CannonFieldimplementation.
  • t11/main.cpp contains MyWidget and main.

Line-by-line Walkthrough

t11/cannon.h

The CannonField now has shooting capabilities.

Calling this slot will make the cannon shoot if a shot is not in the air.

This private slot is used to move the shot while it is in the air,using a QTimer.

This private function paints the shot.

This private function returns the shot's enclosing rectangle ifone is in the air; otherwise the returned rectangle is undefined.

Qt Private Slot Example Software

These private variables contain information that describes the shot. ThetimerCount keeps track of the time passed since the shot was fired.The shoot_ang is the cannon angle and shoot_f is the cannon forcewhen the shot was fired.

t11/cannon.cpp

Qt Private Slot Example Value

We include the math library because we need the sin() and cos() functions.

We initialize our new private variables and connect the QTimer::timeout() signal to our moveShot() slot. We'll move theshot every time the timer times out.

This function shoots a shot unless a shot is in the air. The timerCountis reset to zero. The shoot_ang and shoot_f are set to the currentcannon angle and force. Finally, we start the timer.

moveShot() is the slot that moves the shot, called every 50milliseconds when the QTimer fires.

Its tasks are to compute the new position, repaint the screen with theshot in the new position, and if necessary, stop the timer.

First we make a QRegion that holds the old shotRect(). A QRegionis capable of holding any sort of region, and we'll use it here tosimplify the painting. ShotRect() returns the rectangle where theshot is now - it is explained in detail later.

Qt private slot example software

Then we increment the timerCount, which has the effect of moving theshot one step along its trajectory.

Next we fetch the new shot rectangle.

If the shot has moved beyond the right or bottom edge of the widget, westop the timer or we add the new shotRect() to the QRegion.

Finally, we repaint the QRegion. This will send a single paint eventfor just the one or two rectangles that need updating.

The paint event function has been split in two since the previouschapter. Now we fetch the bounding rectangle of the region thatneeds painting, check whether it intersects either the cannon and/orthe shot, and if necessary, call paintCannon() and/or paintShot().

This private function paints the shot by drawing a black filled rectangle.

We leave out the implementation of paintCannon(); it is the same asthe paintEvent() from the previous chapter.

This private function calculates the center point of the shot and returnsthe enclosing rectangle of the shot. It uses the initial cannon force andangle in addition to timerCount, which increases as time passes.

The formula used is the classical Newtonian formula for frictionlessmovement in a gravity field. For simplicity, we've chosen todisregard any Einsteinian effects.

We calculate the center point in a coordinate system where ycoordinates increase upward. After we have calculated the centerpoint, we construct a QRect with size 6x6 and move its center point tothe point calculated above. In the same operation we convert thepoint into the widget's coordinate system (see TheCoordinate System).

The qRound() function is an inline function defined in qglobal.h (includedby all other Qt header files). qRound() rounds a double to the closestinteger.

t11/main.cpp

The only addition is the Shoot button.

In the constructor we create and set up the Shoot button exactly like wedid with the Quit button. Note that the first argument to the constructoris the button text, and the third is the widget's name.

Slot

Connects the clicked() signal of the Shoot button to the shoot() slotof the CannonField.

Behavior

Example

The cannon can shoot, but there's nothing to shoot at.

(See Compiling for how to create amakefile and build the application.)

Exercises

Make the shot a filled circle. Hint: QPainter::drawEllipse() mayhelp.

Change the color of the cannon when a shot is in the air.

You're now ready for Chapter 12.

[Previous tutorial][Next tutorial][Main tutorial page]