Signals and Slots

Signals and Slots are how events like the clicking of a button are connected to actions like a function you write to do something when the user clicks a button.

Simple QPushButton example

This example uses the QPushButton widget. You can download a working example here.

Start a new project called JustATest and add a push button and a line edit to the form, then save the form.

Here is the code for the JustATest.pm file.

package JustATest;
use Qt;
use JustATestGUI;
use Qt::isa "JustATestGUI";
use Qt::slots
    YouClickedMe => [];
 
sub NEW
{
    my $self = shift;
    $self->SUPER::NEW(@_);
    this->connect(this->pushButton1, SIGNAL('clicked()'), SLOT('YouClickedMe()'));        
}
 
sub YouClickedMe
{
    lineEdit1->setText("That is a great button!");
}
 
1;

Notice that the function called YouClickedMe is what we want to happen when the button is clicked.

The thing that connects the event of the button click to the action of the YouClickedMe function is a connect command.

this->connect(this->pushButton1, SIGNAL('clicked()'), SLOT('YouClickedMe()'));

The SIGNAL is the event and the SLOT is the action.

Also notice that near the top of the program is a definition line that tell the program there is going to be a SLOT that needs special attention.

use Qt::slots
    YouClickedMe => [];

This connect was for a QPushButton so it sends an event of clicked() for our SIGNAL but other objects use other signals and have different types of slots. The QPushButton is a simple widget object and the SLOT for a click event takes no arguments.

QComboBox a SLOT with arguments

The QComboBox is an example of a widget object where the SLOT takes an argument.

this->connect(this->{ConnectionCombo}, SIGNAL('activated(const QString&)'), SLOT('OnChange(const QString&)'));

You can download a QComboBox working example here.

package QComboBox;
use Qt;
use QComboBoxGUI;
use Qt::isa "QComboBoxGUI";
use Qt::slots
    OnSelect => [ 'const QString&' ];
 
sub NEW
{
    my $self = shift;
    $self->SUPER::NEW(@_);
 
    this->{comboBox1}->insertItem("Hat");
    this->{comboBox1}->insertItem("Coat");
    this->{comboBox1}->insertItem("Boots");
    this->{comboBox1}->insertItem("Car keys");
    this->connect(this->{comboBox1}, SIGNAL('activated(const QString&)'), SLOT('OnSelect(const QString&)'));
}
 
sub OnSelect
{
    # Grab the argument passed to this function as a constant QString variable
    $WhatYouSelected = shift; 
 
    lineEdit1->setText($WhatYouSelected);
}
 
1;

To download a working example project please see Download eamples.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License