qt – emit a signal

When you trying to link the slots and signals together you need to have a QObject::connect and also a emitting, I have created a basic demonstration of this with a QPushButton (link to qt signal and slots, and a QT link for the signal and slots)

The basics of slot(s) and signal(s) with emit(ting) is that a slot is where the emit(ed) signal goes to, when a signal is emit(ed) via a class. For example if you want to link a value changed event then you would emit a signal from within the class and then use that signal with the QObject::connect to link to a slot within class as well.

I have created a class called EmitterTest that has a function within it called

        void setValueAndEmit(int v);

this function will set the value and emit the signal for any QObject::connect to link to a slot. To emit the signal you just

        emit valueChanged(v);

where the valueChanged is the signal within the class definition (you do not define that function because it is kinder like a virtual function).

To allow for these slots and signals to be defined within the class you need to call the macro Q_OBJECT at the top of the class (within a private area) so that all of the necessary attachments to the class can be created (within the moc file associated with the class when you run the qmake later on).

To define a signal and slot there is keywords within the “new” class structure available because of the Q_OBJECT and you can just use them like public and private declarations

    public slots :
        void setValue(int v);
 
    signals:
        void valueChanged(int newV);

signals are always public in there access rights.

What the code below does is to create a slot and signal with a function that will emit a signal when called (the function that is) so the signal is “fired” off to what ever is listening to it, to connect a signal to a slot you use the QObject::connect as below

    EmitterTest em1, em2;
 
    QObject::connect(&em1, SIGNAL(valueChanged(int)),
                     &em2, SLOT(setValue(int)));

where the EmitterTest is the class that I am creating, and the object em1 signal valueChanged is linked to the same class type but different instance of it, em2 slot setValue.

Here is the code below for the full EmitterTest, here is the header file for the emitting test class, if you save as emitting.h

#ifndef EMITTING_H
#define EMITTING_H
 
#include <QObject>
 
class EmitterTest : public QObject
{
    Q_OBJECT
 
    public:
        EmitterTest() { mem_value = 0;}
 
        int getValue() const { return mem_value;}
        void setValueAndEmit(int v);
 
    // these pick up the emitted signal
    public slots :
        void setValue(int v);
 
    // these are what are sent out over emitted signals
    // you do not implement the signals since they are just virtual functions
    // as such that you call with emit then the value within the parameter(s)
    // is passed to the slot.
    signals:
        void valueChanged(int newV);
 
    private:
        int mem_value;
};
 
#endif // EMITTING_H

and here is the emitting.cpp file, that holds the main runtime main function.

#include <QObject>
#include <QString>
#include <stdio.h>
#include "emitting.h"
 
void EmitterTest::setValue(int v)
{
    // if the value has changed
    printf("The new value for %d\n", v);
    mem_value = v;
}
 
void EmitterTest::setValueAndEmit(int v)
{
    // if the value has changed
    if (v != mem_value)
    {
        mem_value = v;
        emit valueChanged(v);
    }
}
 
int main()
{
    EmitterTest em1, em2;
 
    QObject::connect(&em1, SIGNAL(valueChanged(int)),
                     &em2, SLOT(setValue(int)));
 
    em1.setValueAndEmit(10);
    printf("The connection from the object connection em1 %d should equal em2 %d \n", em1.getValue(), em2.getValue());
    em2.setValueAndEmit(15);
    printf("The connection from the object connection em1 %d should NOT equal em2 %d \n", em1.getValue(), em2.getValue());
    // the values are not the same because I have not connected them even though I have called the emit within the
    // setValueAndEmit
    return 0;
}

if you save them into a directory and then to compile you need to have the qmake and also make (nmake for windows) to make the relevant files to build a qt project. The qmake project creates the necessary .pro file to build the project, the qmake will build the necessary files (moc files) for the make (or nmake) to build the project into a executable file

qmake -project
qmake
make

and then there will be a executable file within that directory and the output will be once you have run it

The new value for 10
The connection from the object connection em1 10 should equal em2 10
The connection from the object connection em1 10 should NOT equal em2 15

as you notice since I only connected em1 signal to em2, if you change em2 mem_value then em1 does not change as well because the em2 signal is not linked back to the em1 slot.

If you get this error when you are trying out any emit test

undefined reference to `vtable for --- your class name

, it is because for some reason if you use the Q_OBJECT you need to define the class within a .h (header file) and then it will compile instead if you try and use the same .cpp for the main source code then you will get this error message.

hover over to show a hidden element

Sometimes you may not have the luxury of having javascript to do some of the great things that it can do, like showing hidden content on the screen when you hover over a HTML element (like a A HTML tag for example). In CSS you can achieve a similar result with using some of the overflow and styling elements of un/ordered lists to accomplish a similar result.

If you save this code as codingfriends_showhide.html and then open it up in Firefox or your browser of choice (not sure if it will work in IE6 shall have to check it !). and then just hover over the block and it will display the hidden message 🙂

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>CSS - show/hide on hover</title>
<style type="text/css">
/* the main ul block, there is no list style at all e.g. all together */
#showhideblock {
	list-style:none;
	margin:0;
	padding:0;
}
/* the main ul block elements push to the left and make there display inline e.g. no breaks */
#showhideblock li {
	float:left;
	width:200px;
	height:55px;
	display:inline;
	border:1px solid black; 
}
 
/* the basic showing element of the list */
#showhideblock li .show{
	display:block;
	width:200px;
	height:55px;
}
/* hide the hiding element of the list with the height of 0 and overflow set to hidden */
/* but once shown display in black */
#showhideblock li .hide {
	color : black;
	height: 0; /* hide the .hide element */
	overflow: hidden;
	background:black;
}
/* when you hover over the shown element, set the hidden element sizes */
#showhideblock li:hover .hide, #showhideblock li.over .hide {
	height: 55px;
	width:  200px;
}
/* when you hover over the shown element set the shown element height and overflow values */
#showhideblock li:hover .show, #showhideblock li.over .show {
	height: 0;
	overflow: hidden;
}
 
/* set the show a href links to colour of black (on the white background of the shown element */
/* and the textual size to be bigger than normal */
#showhideblock li a {
	color:black;
	font-size:1.5em;
}
/* since changing the background colour of the hidden element to black, change the on hover */
/* to have a textual colour of white */
#showhideblock li a:hover {
	color:white;
}
</style>
</head>
 
<body>
<ul id="showhideblock">
    <li>
      <a class="show" href="#"  title="The image to show">Hover over me, what has been hidden ?</a>
      <div class="hide">
	<a href="#" title="the hidden link">Codingfriends - I was hidden here all along</a>
      </div>
    </li>
</ul>
</body>
</html>

In essence the main parts of the code are as follows, you need to set the unordered list to have a list style of none with the list elements (li) having a display of being inline (which means that there is no breaks between the elements).

#showhideblock {
	list-style:none;
...
#showhideblock li {
	display:inline;

with this in place you can use the size of show and hide elements with also the overflow set to hidden (when you hover over the block you need to set the shown element overflow to hidden and set the size of the hidden element so that it shows)

#showhideblock li .hide {
	color : black;
	height: 0; /* hide the .hide element */
	overflow: hidden;

And once you have saved the above file and opened up in your browser of choice when you now hover over the “Hover over me” text you will see the hidden text instead.

kernel – hello world

To compile up this module you will need to have the linux header files, which should be installed but if not you just need to either use apt-get, rpm, pacman etc to install the linux header files.

With kubuntu I use the aptitude command to install applications and updates etc, but to get the linux-headers I used

aptitude install linux-headers

that is normally linked to the latest version of the linux kernel that you are using.

The main part of the program is outputting a potential parameter being passed (passing parameters to a nvidia kernel module here) and also saying hello world, kinder two for the price of one as such tutorial.

As in c language there is the printf, but in the kernel there is a printk which is the same similar thing but more for outputting errors/messages to the user.

So for example

printk(KERN_INFO "hi there\n");

the KERN_INFO is a kernel information marco that sends the details to a information level of output, e.g. /var/log/messages or you could use dmesg

here is the code on how to pull in parameters from a kernel module being loaded, the parameter_int is my parameter to be checked against and the S_IRUSR is the access rights (IR = read permission, IW = write permission, USR = user, GRP = group, OTH = others)

The module_param takes 3 parameters, the first is the variable to place the value into, second is the variable type and the third is the access rights, with the MODULE_PARM_DESC is the description of the parameter to pass, in this case it is just a integer value.

static int parameter_int = 0;
module_param(parameter_int, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(parameter_int, "An integer value");

Within a normal c/c++ program there is a main function where the program is run from, but in the kernel space since the main program is already running you can define what functions to call when the module is inserted and also removed,

module_init(hello_init);
module_exit(hello_exit);

the module_init parameter is the function to call when the module is loaded and the module_exit parameter is the function to call when module is removed from the kernel space.

Here is the full code, if you save this as helloworld_parameter.c

/* hello world with passing some parameters in the kernel module */
 
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/stat.h>
 
MODULE_LICENSE("GPL");
MODULE_AUTHOR("genux");
 
/* need to setup a setup a static variable to hold the parameter value and
   set it to a default value is none is passed */
static int parameter_int = 0;
 
/* the linux/stat.h has the S_IRUSR definitions etc.. */
/* S_IRUSR = read permission, owner
   S_IWUSR = write permission, owner
   S_IRGRP = read permission, group
   S_IROTH = read permission, others
   */
 
module_param(parameter_int, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(parameter_int, "An integer value");
 
static int __init hello_init(void)
{
	printk(KERN_INFO "Hello world\n\n");
	printk(KERN_INFO "my parameter int value is : %d\n", parameter_int);
	return 0;
}
 
static void __exit hello_exit(void)
{
	printk(KERN_INFO "Goodbye from hello world parameter\n");
}
 
module_init(hello_init);
module_exit(hello_exit);

since we are compiling a kernel module we need to link to the loaded kernel modules, here is a Makefile to compile up the program, so save this as “Makefile”

obj-m += helloworld_parameter.o
 
all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
 
clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

the first is the obj-m += which means compile a object module and you could have more than one file to compile up so use the += to add more files to it, the -C means change directory for the build environment for the kernel space, the M is a parameter passed to the build environment to use this current directory for where the source files are, and the modules means to create kernel modules e.g. filename.ko.

once you have run the

make

there should be a file called helloworld_parameter.ko, to find out details about your new module you can use the modinfo

modinfo helloworld_parameter.ko
filename:       helloworld_parameter.ko
author:         genux
license:        GPL
srcversion:     A81F18D40DA3C5FAB1C71FF
depends:
vermagic:       2.6.31-17-generic SMP mod_unload modversions
parm:           parameter_int:An interger value (int)

and the parm: is the important part here, it is what the parameter is called to pass a value to for example to watch the module being inserted if you open up two consoles and on one put

tail -f /var/log/messages

in the second console do

insmod helloworld_parameter.ko
rmmod helloworld_parameter.ko
insmod helloworld_parameter.ko parameter_int=3
rmmod helloworld_parameter.ko

and the output should be in the first console

Hello world
 
my parameter int value is : 0
Goodbye from hello world parameter
 
Hello world
 
my parameter int value is : 3
Goodbye from hello world parameter

hope that helps with kernel modules, I am planning on doing a kernel module for a custom built USB device.

kernel – passing module parameters

With normal programs that allow you pass parameters on there command line, for example

printoutmyname genux

where the program is called printoutmyname and the first parameter is genux (it is normal that the first parameter [0] is actually the program name and the second parameter [1] is the parameter that is passed)

Well in Linux kernel (where here is a example on how to compile the kernel for a ubuntu based setup) you can pass parameters to the modules that are getting loaded. One module would be your graphics card, in my case a nvidia graphics card.

To find out what parameters can be passed to the graphics card you will have to find the kernel module file (filename.ko, where the ko is the kernel object file), so to search for the nvidia.ko in my case I did

locate nvidia.ko

and then changed to that directory and did a module information on it

cd /lib/modules/2.6.31-17-generic/updates/dkms/
ls
nvidia.ko  vboxdrv.ko  vboxnetadp.ko  vboxnetflt.ko

and doing a module information on it you call the modinfo on the kernel object file as

modinfo nvidia.ko
</pre
 
my output was
 
<pre lang="bash">
filename:       nvidia.ko
license:        NVIDIA
alias:          char-major-195-*
alias:          pci:v000010DEd*sv*sd*bc03sc02i00*
alias:          pci:v000010DEd*sv*sd*bc03sc00i00*
depends:
vermagic:       2.6.31-17-generic SMP mod_unload modversions
parm:           NVreg_EnableVia4x:int
parm:           NVreg_EnableALiAGP:int
parm:           NVreg_ReqAGPRate:int
parm:           NVreg_EnableAGPSBA:int
parm:           NVreg_EnableAGPFW:int
parm:           NVreg_Mobile:int
parm:           NVreg_ResmanDebugLevel:int
parm:           NVreg_RmLogonRC:int
parm:           NVreg_ModifyDeviceFiles:int
parm:           NVreg_DeviceFileUID:int
parm:           NVreg_DeviceFileGID:int
parm:           NVreg_DeviceFileMode:int
parm:           NVreg_RemapLimit:int
parm:           NVreg_UpdateMemoryTypes:int
parm:           NVreg_UseVBios:int
parm:           NVreg_RMEdgeIntrCheck:int
parm:           NVreg_UsePageAttributeTable:int
parm:           NVreg_EnableMSI:int
parm:           NVreg_MapRegistersEarly:int
parm:           NVreg_RmNvclkIdleGraphics:int
parm:           NVreg_RegistryDwords:charp
parm:           NVreg_NvAGP:int

where the parm: is a parameter to pass to the module on load (insmod, or loaded via the kernel at boot time which you can force to load via the /etc/modules file and the parameters can be placed in the /etc/modprobe.d directory).

for example to load the nvidia module with a parameter NVreg_NvAGP you would do something like

insmod nvidia.ko NVreg_NvAGP=1

and the passing value is 1 to the NVreg_NvAGP parameter

operator – comparisons

Comparisons between classes are different compared to local variables e.g. int(eger), float, doubles.. because the comparisons aspects of the standard variables have already been done e.g.

int a=2;
int b =3;
if (a==b)....

the comparison being the “==”, within your own classes if you want to test against a another object that is of the same class you will have to write a comparison function that will either return true or false, of course there are other comparisons <,>, <=, >= etc and also +,- which can be implemented if you wanted to.

The basics of the comparison operator is

bool operator == (const yourclassname &tester)

where yourclassname is what you have called your class, of course you can run comparisons with other classes and also standard variables like floats, but you will need to write a separate one for each. The operator is the keyword, and it returns a bool(ean) result which is either true/false, so once you have done a comparison within this function you just return either true or false and the code below will still compile

classA a;
classA b;
if (a==b) ..

below is code that you can compile to demonstrate operator keyword abit more.

#include <iostream>
 
using namespace std;
 
class classA
{
  public : 
    int x;
 
  // of course you cannot alter the testing class so const 
  // the tester is the right hand side of the boolean test e.g.
  // if (A == B ) . A = this class and B = tester
  bool operator == (const classA &tester)
  {
      if (x == tester.x) 
	return true; 
      else 
	return false;
  };
};
 
int main()
{
    classA a;
    classA b;
    a.x = 0;
    b.x = 0;
 
    if (a==b)
      cout << "the same" << endl;
    else
      cout << "not the same" << endl;
 
    b.x = 1;
 
    if (a==b)
      cout << "the same" << endl;
    else
      cout << "not the same" << endl;
 
    return 0;
}

and the output would be

the same
not the same

QT – hello world – signals and slots

QT framework is a great application stack that allows for cross development (between different OS’s) without having to re-do the code for e.g.Linux/Windows different setups. It is similar to Java and C Sharp (C#) in that way, but the difference with them is that they compile into a native object which can then run within a virtual machine where as the QT framework is more designed to be compiled within each setup, which should make it quicker as well because it will be in the native code and not running in a virtual machine.

The nice thing about QT is that it has its own SIGNAL and SLOTS, similar to C Sharp (C#) events process where you can link something happening to when something else has just happened (e.g. moved a value on a slider bar and a integer value alters as well).

I shall go into more detail with SIGNAL’s and SLOT’s in the next tutorial for QT development, but in essence they are defined within the class of the object itself and then you link them with a “connect” syntax. e.g.

    object::connect(object_to_send_signal, SIGNAL(signal_of_the_object_that_will_be_emit),
                        object_to_pick_up_signal, SLOT(function_to_call_once_signal_has_been_emitted));

so you will link/connect a objects that sends a signal to a slot that receives the signal.

Here is a basic GUI for a QT application that will have a button that says “QUIT” and also a signal that is emitted once that button class clicked() has happened, that links to the application (QApplication object) that has a “quit” function that stops the program from executing.

To start with we first include the basic header files and then create a QApplication (the gui as such) and then a QPushButton object with the default text being “Quit”.

    QApplication app(argc, argv);
    QPushButton *button = new QPushButton("Quit");

once this has happened we then create the connection between the clicking of the button to the application “quit”ing function.

    QObject::connect(button, SIGNAL(clicked()),
                        &app, SLOT(quit()));

we have only created the button but not placed it on the screen, so we use the show method within the button class and then run the application execution function to actually run the GUI program

    button->show();
    return app.exec();

if you save this file within a directory called quit and call this file quit.cpp

#include <QApplication>
#include <QPushButton>
 
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QPushButton *button = new QPushButton("Quit");
    QObject::connect(button, SIGNAL(clicked()),
                        &app, SLOT(quit()));
    button->show();
    return app.exec();
}

then change to that directory within your console/command line and then we need to build up the QT compiling project files.

qmake -project

this will make the quit.pro file within that same directory (it uses the same name as the directory name), and within that file is

######################################################################
# Automatically generated by qmake (2.01a) Wed Feb 24 11:49:39 2010
######################################################################
 
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
 
# Input
SOURCES += quit.cpp

which basically means that the application uses the source files of quit.cpp, you then need to create the Makefile (which is the actual compiling c++ file that g++ uses to create the application)

qmake

so the directory will be something similar to

Makefile  
quit.cpp
quit.pro

within Linux you can just now run the make command which will make the application “quit” but without windows you would need to have the nmake command instead, so run either make or nmake and within the directory now will be a quit application that you can run and the output would be a simple GUI with a button on it that says “Quit” and once you click that button the application will quit.

Equals – why ? and why not ==

Object oriented programming allows for objects to be created on the fly with the keyword “new”. The new will create a new object on the heap memory space and then give that memory location to the variable name, for example.

class NewClass 
{
   private int x;
} ....
 
NewClass a = new NewClass();
NewClass b = new NewClass();

What is happening in memory is something like below, the a variable has a small space and so does b, because they are just “pointers” to the actual memory locations of the class that was created.

Variable Value
a 0x0102
b 0x0110

where as the memory on the heap space would actually hold the NewClass details for example.

Memory location Value
0x0102 NewClass – overhead details
0x0104 NewClass – x value
…. ….
0x0110 NewClass – overhead details
0x0112 NewClass – x value

So the actual value of a and b are just values within memory, this could give reason why the “==” (equals) does not work e.g.

if (a==b)

even if both of them have the same internal values of the NewClass x value, they are still actual pointing to different locations (which makes sense otherwise you are comparing the same object which would be silly). There is a few functions to do the comparsions of objects, Equals, Compare for example and if you implement these functions within your class you can then “compare” the two objects instead of the memory locations that are held within the variables (a 0x0102 and b 0x0110)

To implement a Equal function it would be something similar to

	public boolean Equals(Object obj)
	{
		if (x == ((ClassA)obj).xValue())
			return true;
                return false;
	}

where the obj (Object) passed is the same type as the Class e.g. NewClass and return true if they are same (after casting the object obj value to a ClassA structure).

Here is a bigger example with code for two java files, if you save this class as normal for java to have it the same as the class name e.g. ClassA.java

public class ClassA {
	private int x;
 
	public ClassA() { x =0;}
	public ClassA(int value) { x = value;}
 
	public int xValue() { return x; }
	public void setX (int value) { x = value;}
 
	public boolean Equals(Object obj)
	{
		if (x == ((ClassA)obj).xValue())
			return true;
		return false;
	}
 
	public int Compare(Object obj)
	{
		ClassA objA = (ClassA)obj;
		if (x > objA.xValue())
			return 1;
		else if (x < objA.xValue())
			return -1;
		else
			return 0;
	}
}

this file also includes the Compare function method, so the returns have to be normal to java comparison e.g. 1 means > (greater than) , 0 = same, -1 < (less than), it is up to you to implement to make sure that this kinder of comparison adhears to how you want the class is greater than another class, could be a X value as above, or could that you call the first class number 1 and the second of that type of class 2.. it is up to you. and then save this as Test.java

public class Test {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClassA a = new ClassA();
		a.setX(10);
		ClassA a2 = new ClassA();
		a2.setX(10);
		if (a==a2)
			System.out.println("Yep the same");
		else
			System.out.println("nope not the same");
 
		if (a.Equals(a2))
			System.out.println("Yep the same");
		else
			System.out.println("nope not the same");
		a2.setX(11);
		int comparsion = a.Compare(a2);
		if (comparsion == 0)
			System.out.println("Same");
		else if (comparsion == 1)
			System.out.println("greater");
		else	// only -1 left.
			System.out.println("less than");
 
	}
 
}

compile them you just need to javac Test.java and that will compile the ClassA.java file as well, then to run

java Test
 
nope not the same
Yep the same
less than