Wednesday, 20 January 2010

Resizing a QGraphicsPixmapItem

I've just finished some code where I wanted to resize some QGraphicsPixmapItems. I was able to scale them but this didn't allow me to resize to specific pixels. After a short while I noticed that if I create a pixmap object first I can resize that, then create a QGraphicsPixmapItem using the pixmap object:

//first create a pixmap object
QPixmap pixmapObject(":Images/myimage.png");

//now create a QGraphicsPixmapItem
QGraphicsPixmapItem * myImagePixmapItem
= new QGraphicsPixmapItem();

//add the resized QGraphicsPixmapItem to the pixmap

The scaledToHeight function in the last line could be either scaled, scaledToWidth or scaledToHeight. scaled allows you to set both the width and height of the object where as the other 2 will scale the other side automatically so that the aspect ratio of the pixmap is preserved.

Monday, 18 January 2010

Remove trailing newline character from asctime output

When converting a tm structure to a string using the asctime function in c++ you are left with a cstring ending with a newline character (\n). This is often a pain if you want to insert the date into another string to use later.

By looking at the contents of the cstring you can see that the last two characters are \n and \0. Therefore we just need to change the second to last character in the string from \n to \0:

struct tm * timeinfo;
char * time = asctime(timeinfo);
time(strlen(time)-1) = '\0';
cout << "The time is: " << time;
If you’re not sure what’s going on here the end of a cstring is terminated when the character \0 (A null terminator) is reached. If we look at what the cstring looks like before we use the above code it would look like this:
Sat May 20 15:21:51 2000\n\0
After the code is run it will look like this:
Sat May 20 15:21:51 2000\0\0