Showing posts with label Qt4. Show all posts
Showing posts with label Qt4. Show all posts

Saturday, November 19, 2011

Drawing Charts with Python & Qt4

Back again with some graphics stuff that can be useful in monitoring applications.
As you can immagine, this charts are 100% QPainter. The source code is available on blog-code@github.

Pie Chart
table = DataTable()
table.addColumn('Lang')
table.addColumn('Rating')
table.addRow(['Java', 17.874])
table.addRow(['C', 17.322])
table.addRow(['C++', 8.084])
table.addRow(['C#', 7.319])
table.addRow(['PHP', 6.096])

chart = PieChart(table)
chart.save('pie.png', QSize(240, 240), legend_width=100)

The usage is really simple, you have to create your table with columns and data, create a chart object using the table that you've created and you can call the draw() or save() method to show/save the chart somewhere.

Scattered Chart
chart = ScatterChart(table)
chart.haxis_title = 'Proc input'
chart.haxis_vmin = 0
chart.haxis_vmax = 16
chart.haxis_step = 2
chart.vaxis_title = 'Quality'
chart.vaxis_vmin = 90
chart.vaxis_vmax = 104
chart.vaxis_step = 1


You can customize the min/max value and the step of horizontal and vertical axis, ore you can use the default calculated on your data. You can also set the Reference column with setHorizontalAxisColumn() or setVerticalAxisColumn().

Area Chart

table = DataTable()
table.addColumn('Time')
table.addColumn('Site 1')
table.addColumn('Site 2')
table.addRow([ 4.00, 120,   500])
table.addRow([ 6.00, 270,   460])
table.addRow([ 8.30, 1260, 1120])
table.addRow([10.15, 2030,  540])
table.addRow([12.00,  520,  890])
table.addRow([18.20, 1862, 1500])

chart = AreaChart(table)
chart.setHorizontalAxisColumn(0)
chart.haxis_title = 'Time'
chart.haxis_vmin = 0.0
chart.haxis_vmax = 20.0
chart.haxis_step = 5

chart.save('area.png', QSize(400, 240), legend_width=100)


Line Chart


chart = LineChart(table)
chart.setHorizontalAxisColumn(0)
chart.haxis_title = 'Time'
chart.haxis_vmin = 0.0
chart.haxis_vmax = 20.0
chart.haxis_step = 2



Once again, the code is available on github at blog-code/qt4-charts/chart.py.

Don't miss the Florence Qt Day 2012

The conference will take place on 27/28 January 2012, AC Hotel Firenze Porta al Prato (Florence, Italy). And it is Free!

  • The Qt Project
  • Qt 5.0
  • Qt Quick
  • Qt WebKit
  • Performance & Profiling
  • Qt in Use
  • ...And many more


Take a look at http://www.qtday.it for more information.

Sunday, August 15, 2010

Qt4 Http Request Parser

Qt 4.4 introduces QNetworkRequest and QNetworkAccessManager to help you with your HTTP client request. But if you want parse an HTTP Request, because you're writing an HTTP server, it seems that there's nothing already done (comment here, if I've missed it).

So, this morning I've written a little class that help you with HTTP Request parse:

  • static HttpRequest fromData (const QByteArray& data);
  • static HttpRequest fromStream (QIODevice *buffer);

There's a couple of method that you can use to parse your request data, and some others method to retrieve headers, method type, url and body data.

Qt is used only for QHash, QByteArray and QIODevice classes, you've to implement all the "socket" logic, to handle your client request and response.

The Source code is available here: Qt4 Http Request Parser Source Code.

Saturday, July 24, 2010

iPhone/Qt: UDP Voice using AudioQueue/QAudioOutput

Qt 4.6 Introduces QtMultimedia with support for raw audio input/output, while Mac OS X and iPhone OS has well known CoreAudio/AudioQueue from a long time.

This example show how to implement a really rudimentary VOIP between an iOS (iPhone/iPod Touch/iPad) and a Desktop (using Qt). To simplify the example is just unidirectional iOS to Qt, because doing Qt to iOS part is just the specular code.

The idea is very simple, Fetch the sample data from the microphone, and send over UDP. No compression no packet number just send raw data in simple way as possible.

On iOS we've AudioQueueNewInput() that creates a new recording audio queue object, and AudioQueueNewOutput() that creates a new playback audio queue object.

The specular Qt 4.6+ classes are QAudioInput class that provides an interface for receiving audio data from an audio input device, and QAudioOutput class that provides an interface for sending audio data to an audio output device. To handle audio samples we can easily wrap QIODevice read() and write() calls.

The source code is really easy. iOS code contains AudioRecorder.h/AudioRecorder.m that is a C code that wrap AudioQueue Input to record a stream, with a callback handler to intercept packet data. The Qt4 Source code contains just  a QIODevice Wrapper that read from UDP and prepare for QAudioOutputStream. It's really really simple, but gives you an idea.

The Source code is available here, and contains both Qt 4.6+ and iOS sources: iPhone/Qt UDP Voice Source Code.

Note: Due to a QTBUG-8878 we cannot use 8, 16, 24 KHz Frequency. Will be fixed in Qt 4.6.4.

Thursday, July 8, 2010

PyQt4: Electronic Oscillator

An electronic oscillator is an electronic circuit that produces a repetitive electronic signal: sine wave, square wave and any other repetitive mathematical function.

So, why an Oscillator? Because, I'm currently looking at Audio, and Audio Effects (Distortion, Chorus, Delay, Flange, Reverb, ...) and the sound is basically a wave with a certain frequency.

How can you visualize your effect function? I've created this one above using Python and PyQt4. Less than 200 lines of code. Including the Oscillator class with 5 types of wave (ok, not so difficult).

You can find the source code here: PyQt4 Electronic Oscillator Source Code.

Sunday, April 18, 2010

Qt Animation Framework Example

Today I've finally written my first example with the Qt Animation Framework (Qt 4.6).

The animation framework aims to provide an easy way for creating animated and smooth GUI's. By animating Qt properties, the framework provides great freedom for animating widgets and other QObjects.

The examples is really simple, few lines of code. And the Qt Animation Framework does all the magic under the hood. Just assign the Start and the End Value for the specified property and the interpolator does the rest.

YouTube video is available here: Qt Animation Example Video and you can find the Source Code here: Example Source Code.

Saturday, January 30, 2010

PyQt4 Schema Script

I've received a couple of emails asking me what I use to draw various graphs and schema that I post on this blog. And the obviously answer is QPainter! I've a small PyQt script that does the easy things but the more difficult one is coded every time...


The script is really simple, it take an xml input and just draw the few items that can recognize. You can use RGBA colors and you can draw linee-paths, like in the image above. The XML looks like this one:



<!-- Green Rect -->
<item type='rectangle'
x='130' y='140' width='140' height='60' 
border='1/0x98b954' 
color='0xf4ffe4/0xdbfdab' />

<text x='130' y='140' width='140' height='60'
color='0x000000' font='Arial'
size='12' bold='false' italic='true'>
I'm just a Test!
</text>        

<!-- Links Line -->
<line path='70,120;70,170;130,170' />



I know that it's a stupid thing and making xml seems to be a long job, but this is what I need at the moment, maybe in the future this script will get a WYSIWYG ui but at this time is just a simple script that generate an image :)

The source code with the above example is available here: PyQt4 Schema Script.

Saturday, January 16, 2010

Qt4 Image Crop Item

Just a quick break from Math, File-System and Data Structure (I'm overly busy). The example below is a simple QGraphicsItem, that allow the user to select an area on the screen, like the "crop tool" that you can see in every Image Editor. The source code is very simple, just paint() and moveEvent() handlers.


The source code is available here: Qt4 Image Crop Item Source Code.

Sunday, December 13, 2009

Qt4/OpenGL: Pose Editor

Last week I've published an automated "Puppet Animation" to show how Skeletal Animation and OpenGL works. Today, I've made something more to help you in the Animation Design Process.

The Qt code is really simple, it was just an UI with some slider connected to the Model Bones Matrix to performs Rotations and Translations and a QGLWidget that displays the OpenGL that you've already seen in the last post. I've also added a Useful ListWidget to display textures that are loaded by the model.

To get some cool models you can start by checking Blender's Open Projects that allows you to download models from Elephants Dream (see the screenshot above), Big Buck Bunny or Yo Frankie!. I'm still working on a better way to export Bones from Blender, If you've already tried and want to share some information, give me a mail! (thanks).

For this example, I've made a Big Package that contains the OpenGL engine that allows you to load and drows models and the Qt4 Pose Editor Tool that you can easily find in tools/ folder. The Source code is available here: Qt4/OpenGL Pose Editor Source Code.

Sunday, November 22, 2009

Nokia Certified Qt Developer!

Friday, I've received the congratulations mail to have successfully passed the Qt Essential exam, with the nice logo that you can see below... so, this post is just to place this sticker somewhere. I still prefer the Qt T-Shirt and the QtCentre paper of the Qt Centre Programming Contest.


Thanks to Giovanni Bajo and Develer, for the opportunity.

Friday, July 31, 2009

Qt4 Imap API

Pushed in my GitHub repo the first draft of the Qt4 Imap (RFC 3501 Interne Message Access Protocol) Library.
I've implemented a sync communication because it's much easier to use, so if you want to use it in async way you need to implement a thread class that wrap the Imap class and throws the events that you need.


Imap imap;
if (!imap.connectToHost(IMAP_HOST, IMAP_PORT, IMAP_USE_SSL))
IMAP_MAIN_ABORT("connectToHost()", imap.errorString());

if (!imap.login(IMAP_USERNAME, IMAP_PASSWORD, IMAP_LOGIN_TYPE))
IMAP_MAIN_ABORT("login()", imap.errorString());

ImapMailbox *mailbox = imap.select("INBOX");
qDebug() << "INBOX";
qDebug() << " - Exists:" << mailbox->exists();
qDebug() << " - Unseen:" << mailbox->unseen();

QList<int> messageList = imap.searchRecentUnseen();
imap.fetch(mailbox, messageList);
foreach (int msgId, messageList) {
ImapMessage *message = mailbox->findById(msgId);
if (message == NULL) continue;

imap.fetchBodyStructure(message);

qDebug() << "FROM" << message->fromAddress().toString();
foreach (ImapAddress address, message->toAddresses())
qDebug() << " - TO" << address.toString();
qDebug() << "SUBJECT" << message->subject();

for (int i = 0; i < message->bodyPartCount(); ++i) {
ImapMessageBodyPart *bodyPart = message->bodyPartAt(i);
imap.fetchBodyPart(message, i);

qDebug() << bodyPart->isAttachment() << bodyPart->contentType();
qDebug() << bodyPart->data();
}
}

delete mailbox;

imap.logout();
imap.disconnectFromHost();

Thursday, July 23, 2009

Qt4 Google Contacts APIs

Just pushed at GitHub the first draft of the Qt4 Google Contacts Service...

Contacts APIs allows client applications to view and update Contacts content in the form of Google Data API feeds. Your client application can request a list of a user's contacts, edit or delete content in an existing contact.


// Setup Contact
THGoogleContact *contact = new THGoogleContact;
contact->setFullName("John Doe");

THGoogleIm *im = new THGoogleIm;
im->setRel(THGoogleIm::relWork());
im->setAddress("john.doe@aim.com");
im->setProtocol(THGoogleIm::protocolAim());
contact->addImAddress(im);

THGoogleEmail *email = new THGoogleEmail;
email->setAddress("john.doe@mail.com");
email->setRel(THGoogleEmail::relWork());
contact->addEmailAddress(email);

// Insert Contact
THGoogleContactsService *gContacts = new THGoogleContactsService;
gContacts->setAuthToken(...);
gContacts->insertContact(contact);


Take a look at contacttest.cpp for a more complete usage example.

Sunday, June 28, 2009

Qt4 Canvas Plugins

Today, during my Sunday morning bike trip I've had an Idea on how to simply implement a Canvas Plugins in Qt Applications, to give you an idea of How browser external plugins like flash or others works. The Code is really simple there's a class CanvasPlugin with a couple of Abstract Methods Init, UnInit, Resize, MouseEvent and a signal that says "Hey, Paint this Image!". To give you an Idea of the result below you can see a Window with two Widgets, a CanvasPluginViewer and a Label. Canvas Plugin Viewer load an external Library (.so) passed to the command line as first argument.


You can interact with the canvas like a normal widget (the red square moves along the window and you can stop and resume its animation). But you can extend the sample sending and receiving information from a server, or you can do other crazy external things. (See flash usage for more ideas).

That's all folks, it's lunch time. If you've any question send me a mail or write a comment, and remember that this is just a couple of minutes coded example, so don't use in your highly stable app. :)

The Source Code is Available Here: Qt4 Canvas Plugins Source Code.

Saturday, June 13, 2009

Qt4 iPhone Like Cut/Copy/Paste Widget

I'm watching the WWDC Keynote podcast, Just finished the Bertrand Serlet Talk, about Snow Leopard. Now before watching Scott Forstall with the new iPhone 3GS, a little break with an example of Cut, Copy and Paste like Widget. (In the Snow Leopard dock demo, I've seen "the same" widget used to do expose)

It's a really simple example but it can be useful to someone to understand how to add actions to a custom shape.

The Source Code is available Here: Qt4 iPhone Like Cut, Copy Paste Source Code.

Thursday, June 11, 2009

Qt4 Geo IP Location

In a time of Google Maps, Geo Location and other services like this... Here an example of Geo IP Location Service (http://www.hostip.info/) is really far from perfect, but it's just an example.

The sample uses QNetworkAccessManager to get the Geo Location of the IP, and Webkit to display the address on the Google Map.

The Source Code is available Here: Qt4 Geo IP Location Source Code.

Friday, May 29, 2009

Tool: IP Packet Sniffer

Today I've implemented a simple IP Packet Sniffer.

Sometimes is useful to know what're the IP packages that transit on your network, for Analyze network problems, Monitor network usage, Debug client/server communications or Debug network protocol implementations.

The tool is very simple, but I think that can be useful to learn something more about IP and TCP packets and Protocols implementation.

Maybe you can extend this Tool to support other Transport Layer Protocol.

Note: You need to run it as Root.

You can find the Source Code Here: IP Packet Sniffer Source Code.

Saturday, May 16, 2009

Qt4 Jump Away Animation

When I've started working on Mac OS X with Core Animation, I was impressed by an Example (I don't remember the link, if someone knows it, post it in the comments! thanks)... Very few lines of code for a great effect.

After a year, or probably more.. this example was came back to my mind, so I've decided to clone using Qt. And below you can see a short Demonstration Video. Your desktop jump away.. full screen is fantastic :)



The Source Code is Available Here: Qt4 Jump Away Animation Source Code.

Friday, May 15, 2009

PyQt4: PyCon3 Photos on Flickr

PyCon3 was finished, Only one week is passed and I already miss it. Guido van Rossum, Alex Martelli, Ariya Hidayat, Raymond Hettinger, David Boddie, Fredrik Lundh... C/C++ and Python Developer not .NET "coders" (I hate even more my boring .NET job).

Following the PyCon week, here a simple example of PyQt4 that allows you to see up to 500 photos tagged PyCon3 on Flickr.

As always the source code is available here: PyQt4 PyCon3 Flickr Source Code.

Wednesday, May 6, 2009

Qt4 Touch and Rotate

Alan has asked my How I've implemented the Touch and Rotate feature of the Moko. The answer is very simple, It's all Magic! There're very few lines of code to do it, because all the magic is made by atan2.

Atan2 is a variation of the arctangent function. For any real arguments x and y not both equal to zero, atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the coordinates (x, y) on it.

The Source Code is available here: Qt4 Touch and Rotate Source Code.
OT: PyCon3 (Italia) starts Tomorrow!

Saturday, May 2, 2009

Qt4 JSON Stream Reader

JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects).

One way to use JSON with Qt4 is using the QScriptEngine (engine.Evaluate(jsonSource)), But I like Reinventing the wheel, so I've written a simple JSON Stream Reader that works "almost" like the QXmlStreamReader.

You've a readNext() method that read the next token and returns its type, and two properties name() and values() that Returns the name of the Property, Object or Array and the Value of the Property in a QVariant that can be Bool, Int, Double or String.

Below there's an Example of How to use the JSON Stream Reader. Maybe you can use it to create an automatic Object Mapper like the Xml Object Mapper that I've posted a couple of weeks ago.


QFile file("test.json");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString();
return(1);
}

THJsonStreamReader reader(&file);
while (!reader.atEnd()) {
switch (reader.readNext()) {
case THJsonStreamReader::PropertyNumerical:
qDebug() << " - Property Numerical" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyString:
qDebug() << " - Property String" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyFalse:
qDebug() << " - Property False" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyTrue:
qDebug() << " - Property True" << reader.name() << reader.value();
break;
case THJsonStreamReader::PropertyNull:
qDebug() << " - Property Null" << reader.name();
break;
case THJsonStreamReader::Object:
qDebug() << "Object" << reader.name();
break;
case THJsonStreamReader::ObjectEnd:
qDebug() << "Object End";
break;
case THJsonStreamReader::Array:
qDebug() << "Array" << reader.name();
break;
case THJsonStreamReader::ArrayEnd:
qDebug() << "Array End";
break;
}
}

file.close();



The Source Code is Available Here: Qt4 JSON Stream Reader Source Code.