Qt Slot Virtual Function

There are several online casino games with Qt Slot Virtual Function very good payback odds. For example, 'full pay' Video Poker games will have you playing at almost even with the house with perfect play. If i create a class from a base class with virtual slots, the slots never get called with the new connect-flavour. If i use the old connect-syntax, the slot gets called. What could be the problem? @ class BaseClass: public QObject public slots: virt. My GUI project in Qt has a lot of 'configuration pages' classes which all inherit directly from QWidget. Recently, I realized that all these classes share 2 commons slots (loadSettings and saveSettings).Regarding this, I have two questions: Does it make sense to write a intermediate base abstract class (lets name it BaseConfigurationPage) with these two slots as virtual pure methods?

Germain Garand

This document describes a set of Perl bindings for the Qt toolkit. Contactthe author at <germain@ebooksfrance.com>

PerlQt-3 is Ashley Winters' full featured object oriented interface toTrolltech's C++ Qt toolkit v3.0.

It is based on theSMOKElibrary, a language independent low-level wrapper generated from Qt headers byRichard Dale'skalyptusthanks to David Faure's module.

This document describes the principles of PerlQt programming.It assumes you have some basic Perl Object Oriented programming knowledge.

Some C++ knowledge is recommended but not required.It would mostly help you to find your way through Qt's excellent documentation which is ourultimate and only reference.If Qt is installed on your system, then you most probablyalso have its documentation. Try the $QTDIR/bin/assistant program.

Qt Slot Virtual Function

Requirements

To compile and use PerlQt, you'll need :

    a POSIX systemGNU tools : automake(>=1.5), autoconf (>=2.13), aclocal...Perl >= v5.6.0Qt >= v3.0SmokeQt 1.2.1The SMOKE library (Scripting Meta Object Kompiler) is part of KDE's kdebindings module.You may want to check if a precompiled version of this module exists for yoursystem.PerlQt is packaged with its own copy, so you don't need to check it out.

Perl and Qt's installation is out of the scope of this document. Please referto those projects' documentation.

Compilation

PerlQt uses GNU's Autoconf framework. However, the standard ./configure script is preferably drivenby the Makefile.PL wrapper. All options are forwarded to ./configure :

If SMOKE is missing, configure will generate its sources.Then :

This will install PerlQt, Puic and Smoke (if needed), as well as the pqtsh and pqtapi utilities.

The preferred install location for SMOKE and Puic is in the KDE3 file system.If you don't have KDE3 installed, specify a location with configure's--prefix option. e.g:

Troubleshooting and Configure Options

If Smoke's linking fails or your Qt library was built with very specificoptions, run Makefile.PL again with:

When building smoke, configure will check for OpenGL and try to compilesupport for it if it is properly installed and supported by Qt.

You may disable this checking with:

Also, default behaviour is to prefer the Mesa GL library over a proprietaryimplementation.If your system features a proprietary OpenGL library, and you'd like to useit, specify:

How to install PerlQt with user rights

To install PerlQt without super-user rights, simply follow this procedure:

    Perform a normal configuration, specifying as prefix a directory where you have write permissions :

    The above would install the Smoke library in ~/lib and the puic binary in ~/bin

    Reconfigure the Perl module so that it doesn't target the standard perl hierarchy:

    Beware : this is not the same Makefile.PL as above, but the one located in the ./PerlQtsubdirectory

    Compile and Install

    In order to use such an installation, you must tell to Perl where to find this extern hierarchy.This can be done either on the command line:

    or at the top of your program:

    ``5.x.x' should be changed to whatever Perl version your system is running.

Qt virtual slot

A typical Qt program using GUI components is based on an event loop.

This basically means that such a program is no more envisioned as a straightflow where you would need to handle yourself every single events (such as amouse click or a key press).

Instead, you just create an Application object, create the GUI components ituses,define what objects methods need to be called when an event occurs,and then start the main event loop.

That's all!Qt will handle all events and dispatch them to the correct subroutine.

Lets see how this process is implemented in a minimal PerlQt program.

Hello World


This program first loads the Qt interface [line 1] and creates the applicationobject, passing it a reference to the command line arguments array @ARGV[l.2].This application object is unique, and may later be accessed fromanywhere through the Qt::app() pointer.

At line 3, we create a PushButton, which has no parent (i.e : it won't becontained nor owned by another widget).Therefore, we pass to the constructor an undef value for the parent argument,which is PerlQt's way of passing a Null pointer.

After some layouting at [l.4], we tell the application object that our mainwidget is this PushButton [l.5]... that way, it will know that closing thewindow associated with this widget means : quit the application.

Now the last steps are to make this widget visible (as opposed tohidden, which is the default) by calling the show method on it [l.6] andto start the application loop [l.7].

Syntax elements summary :

Virtual Destructor

    All Qt classes are accessed through the prefix Qt::, which replaces the initial Q of Qt classes.When browsing the Qt documentation, you simply need to change thename of classes so that QFoo reads Qt::Foo.An object is created by calling the constructor of the class. It has the same name as the class itself.

    You don't need to say new Qt::Foo or Qt::Foo->new() as most Perlprogrammers would have expected.

    Instead, you just say :

    If you don't need to pass any argument to the constructor, simply say :

    Whenever you need to pass a Null pointer as an argument, use Perl's undef keyword. Do not pass zero. Beware: this is by far the most common error in PerlQt programs.

    Pointers are arguments preceded by an * character in Qt's documentation (e.g: ``QWidget * widget').

Inheritance and Objects

Before we can discuss how Perl subroutines can be called back from Qt, we needto introduce PerlQt's inheritance mechanism.

PerlQt was designed to couple as tightly as possible Qt's simplicity and Perl's power and flexibility.

In order to achieve that goal, the classical Object Oriented Perl paradigm had to be extended, much in the same way than Qt itselfhad to extend C++'s paradigm with metaobjects.

A Custom Widget

Lets rewrite the ``Hello World!' program, this time using a custom version of PushButton:

Here, we want to create our own version of the PushButton widget.Therefore, we create a new package for it [l.3] and import Qt [l.4].

We now want to declare our widget as subclassing PushButton.This is done through the use of the Qt::isa pragma [l.5], which accepts a list of one or more parent Qt classes.

It is now time to create a constructor for our new widget.This is done by creating a subroutine called NEW(note the capitalized form, which differentate it from the usual ``new' constructor. PerlQt's NEW constructor is called implicitly as can be seen on line 21).

Since we want our widget to call its parent's constructor first, we call the superclass's constructor (here: Qt::PushButton) on line 9, passing it all arguments we received.

At this time, a class instance has been created and stored into a special object holder named this (not $this but really just this).

Each time you invoke a method from within your package, you may now indifferently say method() or this->method();

Using Attributes

When building a new composite widget, you may just create its different parts inside my variables, since widgets are only deleted by their parents and not necessarily when their container goes out of scope.

In other words, PerlQt performs clever reference counting to prevent indesirable deletion of objects.

Now, you'll often want to keep an access to those parts from anywhere inside your package.For this purpose, you may use the this object's blessed hash, as is usual in Perl,but that isn't really convenient and you don't have any compile timechecking...

Here come Attributes. Attributes are data holders where you can store any kind of properties for your object.

Declaring new attributes is done through the use Qt::attributes pragma, as is demonstrated in the following package implementation :


Qt Public Slots

An attribute itsTime is declared at line 7, and loaded with a Qt::Time object at line 14.

Since we reimplement the virtual function ``resizeEvent' [l.19].each time the main widget is resized, this function will be triggered and our Button's text updated with values coming from the object [l.21] and from the attributes we defined [l.22].

Recapitulation

    In order to inherit a Qt class, a package must contain a use Qt::isa pragma.e.g:The object constructor is named NEW and is implicitly called.Thus you should not say :

    But say :

    Within a package, the current instance can be accessed through the this variable.

    When a member function is called, arguments are loaded as usual in the @_ array, but without the object pointer itself.

    Hence, you shouldn't say :

    Furthermore, if you want to call a base class method from a derived class,you'd use the specal attribute SUPER :

    Note that the :

    construct is also available, but will pass the object as first argument.

    Whenever you need to store a contained object in your package, you may define it as an Attribute :

    and then use it as a convenient accessor :

    To reimplement a virtual function, simply create a sub with the same name in your object.

    Existing virtual functions are marked as such in Qt's documentation(they are prefixed with the ``virtual' keyword).

    You can inspect what virtual function names are being called by Qt at runtime byputting a use Qt::debug qw( virtual ) statement at the top of your program.

Signals and Slots

We'll now learn how Qt objects can communicate with each other, allowing an event occuring, for instance, in a given widget to trigger the execution of one or several subroutines anywhere inside your program.

Most other toolkits use callbacks for that purpose, but Qt has a much more powerful and flexible mechanism called Signals and Slots.

Signals and slots are used for communication between objects.

This can be thought off as something similar to the wiring between several Hi-fI components : an amplificator, for instance, has a set of output signals, wich are emitted wether a listening device is connected to them or not. Also, a tape recorder deck can start to record when it receives a signal wired to it's input slot, and it doesn't need to know that this signal is also received by a CD recorder device, or listened through headphones.

A Qt component behaves just like that. It has several output Signals and several input Slots - and each signal can be connected to an unlimited number of listening slots of the same type, wether they are inside or outside the component.

The general syntax of this connection process is either :

Qt::Object::connect( sender, SIGNAL 'mysignal(arg_type)', receiver, SLOT 'myslot(arg_type)');

or

myObject->connect( sender, SIGNAL 'mysignal(arg_type)', SLOT 'myslot(arg_type)');

This mechanism can be extended at will by the declaration of custom Signals and Slots, through the use Qt::signals and use Qt::slots pragma(see also the other syntax, later on).

Each declared slot will call the corresponding subroutine in your object, each declared signal can be raised through the emit keyword.

As an example, lets rewrite again our Button package :

In this package, we define two extra slots and one extra signal.

We know from the Qt Documentation that a clicked PushButton emits a clicked() signal, so we connect it to our new slot at line 18.

We also connect our signal changeIt to our own change slot- which is quite stupid, but as an example.

Now, whenever our Button is clicked, the clicked() signal is raised and triggers the wasClicked() slot. wasClicked then proceeds to emit the changeIt(int,int) signal [l.27], hence triggering the change(int,int) slot with two arguments.

Finally, since PerlQt-3.008, an alternative syntax can be used to declare Signals and Slots:

and

This syntax is perfectly compatible with the traditionaluse Qt::signals and use Qt::slots declarations.

Eventually, it can prove good programming practice to mix both syntaxes, by first declaring Signals/Slots with use Qt::slots/signals, then repeat this declarationin the actual implementation with the second syntax.

Declarations will be checked for consistency at compile time, and any mismatchin arguments would trigger a warning.

Introduction

  • Note:
  • As of PerlQt-3.008, a separate PerlQt plugin for Qt Designer is available,bringing full integration, syntax highlighting, code completion and allowing to run/debug your PerlQt projectentirely from the Designer GUI. Nevertheless, the below is still accurate with regard to puic command line interaction and with regard to using Qt Designer without the specific plugin.

As efficient and intuitive as Qt can be, building a complete GUI from scratch is often a tedious task.

Hopefully, Qt comes with a very sophisticated GUI Builder named Qt Designer, which is close to a complete integrated development environment.It features Project management, drag'n drop GUI building, a complete object browser, graphical interconnection of signals and slots, and much much more.

Qt Designer's output is XML which can be parsed by several command line tools,among whose is puic (the PerlQt User Interface Compiler).

Assuming you have already built an interface file with the Designer, translating it to a PerlQt program is simply a matter of issuing one command :

This will generate the package defined in your ui file and a basic main package for testing purposes.

You may prefer :

This will only generate the package, which can then be used by a separate program.

Embedding Images

If you need to embed images or icons, it can be done in two ways:

  • Inline embedding
  • For this, you need to check the ``Edit->Form Settings->Pixmaps->Save inline' checkbox inside Qt Designer.Then : puic -x -o program.plprogram.ui
  • Image Collection
  • This option is more complex but also far more powerful and clean.

    puic -o Collection.pm -embed unique_identifierimage-1 ... image-n

    Then add a use Collection.pm statement to your program's main package.

    If you've created a project file in Qt Designer, and added all images you want to group (through ``Project->Image Collection'), you'll find all those images inside the directory where your project file (*.pro) is stored, under /images.You can then generate the corresponding image collection by issuing :

    puic -o Collection.pm -embed identifier ../images/*

    You can use as many image collections as you want in a program. Simply add a use statement for each collection.

Working With .ui Files

It will often happen that you need to regenerate your user interface -eitherbecause you changed your initial design, or you want to extend it.Thus writing your program's code straight in the auto-generated Perl file isquite a bad idea.You'd run constantly the risk of overwriting your handcrafted code, or endup doing lot of copy-paste.

Instead, you may :

  • Write slots implementation in the Designer
  • In Qt Designer, select the Source tab of the Object Explorer.There you can see a tree-like representation of your classes.Now if you double-click on the Slots/public entry,you are prompted with a dialog where you can create a new custom slot foryour module.Once this is done, the new slot appear inside the Object Explorer tree andclicking on it will bring you to a <Your Class>.ui.h file where you can writethe actual implementation of your slot.

    Keeping all the defaults, it should look like this :

    The slot declaration is actually C++ code, but simply ignore it and writeyour Perl code straight between the two braces, paying special attention toindent it at least by one space.

    All Perl code written this way will be saved to the ui.h file, and puic will take care ofplacing it back in the final program.

    Here, after running puic on the Form1.ui file, you'd have:

  • Subclassing your GUI
  • By using puic's -subimpl option, you may generate a derived moduleinheriting your original user interface.

    You'd typically generate the derived module once, and write any handcraftedcode in this child.Then, whenever you need to modify your GUI module, simply regenerate theparent module, and your child will inherit those changes.

    To generate the base module :

    (do this as often as needed, never edit by hand)

    To generate the child :

    or

    (do this once and work on the resulting file)

PerlQt comes bundled with two simple programs that can help you to find your way throughthe Qt API:

pqtapi

pqtapi is a commandline driven introspection tool.

Qt Signal And Slots

e.g:

pqtsh

pqtsh is a graphical shell that can be used to test the API interactively.It is fairly self explanatory and includes an interactive example (Help->Example)


Templated classes aren't available yet (classes derived from templated classes are).

PerlQt-3 is (c) 2002 Ashley Winters (and (c) 2003 Germain Garand)

Kalyptus and the Smoke generation engine are (c) David Faure and Richard Dale

Puic is (c) TrollTech AS., Phil Thompson and Germain Garand,

The mentioned software is released under the GNU Public Licence v.2 or later.

Whenever you want to use a class/method described in Qt'sdocumentation (see also the 'assistant' program bundled with Qt)from PerlQt, you need to follow some simple translation rules.

Classnames
    All classnames are changed from a Q prefix in Qt to a Qt:: prefixin Perl.e.g: QComboBox is named Qt::ComboBox within PerlQt.
Functions
    Functions referenced as static are accessed directly, and not throughan object. Thus the static function Foo in class QBar would be accessed fromPerlQt as

    The only notable exceptions are :

    Functions referenced as members or Signals are accessed through an objectwith the -> operator.e.g:

    There are no fundamental differences between methods and signals, however PerlQt provides the emit keyword as a convenient mnemonic, so that it is clear you are emitting a signal :

Arguments
  • By value
  • When an argument isn't preceded by the & or * character, it is passed by value. For all basic types such as int, char, float and double, PerlQt will automatically convert litteral and scalar values to the corresponding C++ type.

    Thus for a constructor prototype written as follow in the documentation :

    You'd say :

  • By reference
  • When an argument is preceded by the & character, it means a reference to an object or to a type is expected. You may either provide a variable name or a temporary object :

    If the argument isn't qualified as const (constant), it means the passedobject may be altered during the process - you must then provide a variable.

  • By pointer
  • When an argument is preceded by the * character, it means a pointer to an object or to a type is expected. You may provide a variable name or the Perl undef keyword for a Null pointer.

    Similarly, if the argument isn't const, the passed object may be altered bythe method call.

Enumerations
Enumerations are sort of named aliases for numeric values that would be hard toremember otherwise.

A C++ example would be :

where Strange is the generic enumeration name, and Apple, Orange,Lemon its possible values, which are only aliases for numbers (here 0, 1and 2).

Access to enumerations values in Perl Qt is very similar to a static functioncall. In fact, it is a static function call.

Therefore, since you probably want to avoid some readability problems, werecommend the use of the alternate function call syntax : &function.

Lets now go back to our Strange example.

If its definition was encountered in the class QFruits, you'd write fromPerlQt :

Operators
Within PerlQt, operators overloading works transparently.If a given operator is overloaded in a Qt class (which means using it triggers a custom method)it will behave identically in PerlQt.Beware though that due to limitations of the Smoke binding library, not all overloaded operators areavailable in PerlQt.You can check the availability of a given operator by using the pqtapi program.Also, due to outstanding differences between C++'s and Perl's object paradigm, the copy constructor operator (a.k.a '=')has been disabled.

e.g-1: '+=' overload

Qt Slot Virtual Function System

Constants
Qt doesn't use many constants, but there is at least one place where they are used : for setting Input/Output flags on files.In order to avoid the namespace pollution induced by global constants, PerlQt group them in the Qt::constants module.For instance, requesting the importation of all IO constants into the current namespace would be done with:

You may also import specific symbols:

Global Functions
Qt has also some utilitarian functions such as bitBlt, qCompress, etc.

Those were global scope functions and have been grouped in a common namespace:Qt::GlobalSpace.

Hence, you shall access this namespace either with a fully qualified call:

Or directly, after importation in the current namespace:

Of course, you may selectively import a few functions:

Note: GlobalSpace has also operators, such has the one performing an addition on twoQt::Point(). Those operators are called automatically.

e.g:

PerlQt handles internationalization by always converting QString back to utf8 in Perl.

Conversions from Perl strings to QStrings are made according to context :

  • If the Perl string is already utf8-encoded
  • then the string will be converted straight to QString.

    This is the most convenient and seemless way of internationalizing your application. Typically, one would just enablethe use of utf8 in source code with the use utf8 pragma and write its application with an utf8 aware editor.

  • If the string isn't tagged as utf8, and the use locale pragma is not set
  • then the string will be converted to QString's utf8 from ISO-Latin-1.
  • If the string isn't tagged as utf8 and the use locale pragma is set
  • then the string will be converted to QString's utf8 according to the currently set locale.

Once a string contains utf8, you can convert it back to any locale by setting up converters :

Or, with Perl >= 5.8.0, you may use Perl's Encode modules (see perldoc Encode).

disabling utf-8

Developers who don't want to use UTF-8 or want to temporarily disable UTF-8 marshallingfor handling legacy programs may use the use bytes pragma (and the corresponding no bytes).

Within the scope of this pragma, QStrings are marshalled back to ISO-Latin1 (default) or to your locale(if use locale has been set).

Qt Slot Virtual Function Cheat

Frivole use of this pragma is strongly discouraged as it ruins worldwide standardization efforts.

The Qt::debug module offers various debugging channels/features.

With the simple use Qt::debug statement, the verbose and ambiguous channels are activated.If you specify a list of channels within the use statement, then only the specified channels will be enabled.

Qt Slot Virtual Functions

Available channels :

  • ambiguous
  • Check if method and function calls are ambiguous, and tell which of the alternativeswas finally elected.
  • verbose
  • Enable more verbose debugging.

    Together with ambiguous, tell you the nearest matches in casea method or function call fails.e.g:

  • calls
  • For every call, tell what corresponding Qt method is called(detailing the arguments if verbose is on).
  • autoload
  • Track the intermediate code between a method invocation in Perland its resolution to either a Qt or Perl call.
  • gc
  • Give informations about garbage collectionwhenever a Qt object is deleted and/or a Perl object is destroyed
  • virtual
  • Report whenever a virtual function tries to access its Perlreimplementation (wether it exists or not).
  • all
  • Enable all channels

A marshaller is a piece of ``glue code' translating a given datatype to another.

Within PerlQt, most Qt objects keep their object nature, so that one may invoke methods on them.However, some classes and datatypes map so naturally to some Perl types that keeping their object nature wouldwould feel unnatural and clumsy.

For instance, instead of returning a Qt::StringList object, which would require an iterator to retrieve its content,PerlQt will translate it to an array reference containing all the object's strings.

In the other way, instead of providing a Qt::StringList object as an argument of a method, one would simplyprovide the reference to an array of Perl strings.

Here is the list of Marshallers as of PerlQt-3.008 :