anselmolsm.org

A few words about 2012

| Comments

Sunset in Montevideo, Uruguay. May 2012
Sunset in Montevideo, Uruguay. May 2012

2012 is almost over, but there is time for one more post, just the third this year.

After the Qt Contributors Summit 2012, our team at INdT received a new task: continue the development of ‘The Incredible Circus’. I had worked a little on Circus before, members of the current team worked on the level editor, so maintaining and creating new features for the Qt (Symbian, N9) version was fine.

Then we also received a more challenging task: extend and maintain the WP7 version, only after making this version behavior like the Qt version - and the level editor, as a consequence. A bunch of new stuff to learn and, in some cases, get along: C#, XNA, WP7 and Windows itself :-P

Part of the result of this work was released in version 1.2, an update for the game already published on Nokia Store and WP Marketplace. This version added a new set of levels and some bugfixes; there are more things to come, we are looking forward the new releases.

In parallel, we also worked in a consultancy about a project using Qt, at a client’s office in São Paulo. It was interesting to have contact with other developers working in a different way and inside a different organization.

Then the end of the year was time to study HTML5, Javascript. I must admit I underestimated HTML5 too much, but I still not sharing the faith about HTML5 solving all the the things, however for some use cases it’s becoming a good alternative.

And a remarkable event in the end 2012 was the release of Qt 5.0! Congratulations to all who contributed with code and also those who helped in many other ways!

Let’s see what 2013 brings. Happy new year =)

Qt 5 UiHelpers

| Comments

In my previous post I mentioned one of the experiments we are currently working on. Now it is time to introduce the Qt 5 playground project called UiHelpers - Fortunately, this name will change ;) Those who follow the Qt development mailing list already read about it, the idea about this post is to reach more people from the community in general.

Context

If you are already familiar with the structure of Qt 5 code, feel free to jump to the next section.

In Qt 4, the whole source code is in the same git repository. The traditional widgets derived from QWidget are part of the QtGui module and represent a central piece for the GUI application development.

In Qt 5, things changed. Qt code were splitted in many repositories which group Qt libraries depending on their functionalities. Examples of repositories are qtbase, qtdeclarative, qtjsbackend, qtxmlpatterns, qtsvg, qttools, etc. As you may know, QtQuick 2 became a first class citizen in Qt 5, which means qtdeclarative is one of the main repositories, house of QtQuick and QtQml classes.

But, there are classes that provide the base for QtQuick 2 work properly - they are part of the qtbase repo. There you find QtCore, QtGui, QtNetwork, QtOpenGL, QtPlatformSupport, QtXml, QtWidgets, etc.

Wait: What’s the difference between QtGui and QtWidgets?

As part of the changes of Qt 5, QtGui is now focused in the basic infrastructure for GUI work on different platforms. For example, it is the place for the platform abstraction layer, window management, image handling, etc.

QtWidgets, as you can conclude based on its name, contains the children of QWidget: QPushButton, QSpinBox, QMainWindow, etc. Also, there are non-widgets classes in QtWidgets, some of them because they are internally too coupled to QWidget classes.

Origins

In this thread it was mentioned the case of QUndoStack, QUndoCommand that are in QtWidgets but can be useful in other contexts where developers do not want to link against QtWidgets just because of this kind of helper classes. Later, in the change 15857 (with the help of ogoffart), we discussed about moving QUndo* out of QtWidgets. First, we moved these classes to QtGui what as not considered correct given the new motivation of this lib. Then, another idea was to move the classes to a new lib, inside qtbase. It was not considered ideal and the decision was to create a separated repo for these classes, leaving QtWidgets untouched (since the Qt community do not want to introduce new bugs in this lib).

Current status

We set a wiki page where it is possible to check the classes made available out of QtWidgets. Also, there are instructions about where to download the source code, build, test and contact us.

Besides moving classes out of QtWidgets, some prototypes of convenience APIs were created for QtQuick 2 developers and we are very interested in receiving feedback about them. It’s worth mentioning the QML API for UndoStack and the CompletionModel which is based on the internals of QCompleter and was made available in a QML friendly way.

The following example shows a possible use case for the CompletionModel. Improving the models supported by sourceModel is part of the ToDo list. The ListView is going to show the updated list that currently satisfies what is written in the TextInput.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
TextInput {
    id: input
}

CompletionModel {
    id: completionModel
    sourceModel: ["Ascension Island", "Andorra", "Afghanistan"]
    completionPrefix: input.text
    caseSensitivity: Qt.CaseInsensitive
}

ListView {
    model: completionModel
    delegate: Text { text: modelData }
}

The two examples bellow show the UndoStack and two items that represent commands. The idea of UndoPropertyCommand is to enable track the changes of some properties. In the example, we are going to track x and y when myRect is moved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
UndoStack {
    id: stack
    undoLimit: 5
}

UndoPropertyCommand {
    id: moveCommand
    properties: ["x", "y"]
}

Rectangle {
    id: myRect

    (...)
    
    MouseArea {
        (...)
        drag.target: parent
        onPressed: stack.push(moveCommand, myRect);
    }
}

UndoCommand is another element used to represent commands. The difference here is that it allows the customization of the actions onUndo and onRedo the command.

1
2
3
4
5
6
7
8
9
10
UndoCommand {
    id: aCommand
    
    onUndo: doAThing(target);
    onRedo: undoAThing(target);
}

Button {
    onClicked: stack.push(aCommand, target);
}

Future

Maybe one day this playground project gets promoted and become a Qt Add-on, but there is no expectation it will happen before 5.0. In the meanwhile, there is a ToDo list with some topics we consider important to handle, like better examples, more tests, docs, etc.

We are looking forward receiving more opinions about this work and, as always, contributors are welcome!

Working in the open again

| Comments

Long time since my last post (it’s sad to realize how often I start posts writing this). Since last year’s Qt Contributors’ Summit, our team at INdT worked on a closed source project - the main reason of the low activity here. At least, I could write some posts for the Qt Labs Blog Brazil, most of them introducing basic concepts about Qt programming and the Qt ecosystem (buzzword++). The good part is: This project we were working on was developed using Qt and QML for a desktop application. Besides promoting Qt among Brazilian developers and companies, this project helped us to think about improvements for future releases of QtQuick aiming desktop applications. I am looking forward to see a release of this product soon! (However, when it is going to happen is a client decision).

Then, after the end of this project, I finally managed to contribute to Qt5! :-)

Also, in the end of the last year some coworkers started a kind of pet project: It’s called Iceberg, a fork of the Icecream Monitor.

“Why a fork?” Here we use (http://en.opensuse.org/Icecream)[icecream] for distributed compilation, many colleagues used to complain about icemon depending on kdelibs. In fact, the code did not use the additional features compared to the equivalent Qt classes. Then, after hugopl started the project, we fixed some issues and added new stuff. The code is here.

I am writing another post to introduce one of our current research projects, which is also part of the proposal I sent to Akademy 2012.

Qt Platform Abstraction, Lighthouse para os íntimos

| Comments

Originalmente publicado em http://blog.qtlabs.org.br/2012/03/16/qt-platform-abstraction-lighthouse-para-os-intimos/

É do conhecimento de muitos que Qt é oficialmente suportado em várias plataformas. Recentemente, graças aos esforços da comunidade, novas plataformas passaram a ser suportadas - ainda de forma não oficial - com destaque para Android e iOS. No post de hoje, faremos uma breve introdução à nova estrutura que tem como objetivo simplificar novos ports de Qt, o QPA - Qt Platform Abstraction, codename Lighthouse.

Começo

Em meados de 2009 alguns dos desenvolvedores baseados em Oslo resolveram refatorar o código existente no chamado Qt for Embedded, que é, resumidamente, focada em dispositivos embarcados sem Xorg (no caso do Qt for Embedded Linux), usando framebuffer para a saída gráfica. Nele, existe o QWS - Q Windowing System - que faz as vezes de sistema de janelas simples. A idéia de refatorar tal código era justamente para reduzir a dependência do QWS, porém foram anos de “contaminação” de código e essa tarefa demonstrou-se maior do que o esperado. Foi então que surgiu uma ideia:

Quão difícil seria remover todo o código específico de plataformas e ter um novo port compilável?

Parte do plano era aproveitar que Qt já contava com a Raster Engine e os Alien Widgets já haviam invadido e fixado residência no Qt 4.4. Uma semana mais tarde, já existia um código para QtGui independente de plataforma e compilado com sucesso.

Raster Engine? Alien widgets?

Ambos são potenciais temas para novos posts, segue uma rápida (e, digamos, superficial) explicação para que possamos seguir com nosso assunto:

  • Raster Engine é um sistema gráfico implementado totalmente em software, ou seja, de forma independente do hardware onde está sendo executado. Foi introduzido no Qt 4.0 após repetidas tentativas de utilizar GDI e GDI+ (APIs nativas do Microsoft Windows) para backend gráfico de Qt no MicrosoftWindows.
  • Alien Widgets é o nome dado à uma forma como os widgets são criados na tela. Para nossa rápida explicação de hoje, usaremos terminologia do Xorg. Tradicionalmente, cada widget era na verdade uma “janela do X”. Assim, uma tela com o que costumamos chamar de janela, contendo um botão e um checkbox teria, em termos de estruturas do X, 3 janelas, sendo que 2 delas aninhadas em uma maior. Essa combinação toda era grande responsável por efeitos visuais indesejáveis quando redimensionávamos aplicações, pois o Xserver precisava coordenar a movimentação e redimensionamento desses componentes, o que não acabava bem. Com os Alien Widgets acontece diferente: O Xserver conhece apenas a janela top level, os widgets dentro dela ficam por conta da maquinaria interna do Qt.

Voltando ao assunto

O próximo passo seria conseguir criar um processo único com uma janela full-screen utlizando framebuffer, aproveitando-se dessa infra-estrutura. Com o sucesso desse experimento, o projeto tomou forma e recebeu o nome de Lighthouse, tendo como objetivo: “Como tornar mais fácil Qt suportar diferentes hardwares gráficos”. Com Lighthouse, um port passa a precisar de um plugin que implemente a representação de janelas (window surfaces) para dado cliente (ex: x11 client) e funcionalidades para envio e recebimento de mensagens para o servidor do sistema de janelas (window system server). Um primeiro port teste feito, utilizando QImage como display device, precisou deapenas 147 linhas de código. Prefere uma comparação de uma classe real? qwidget_x11.cpp: 2424 linhas, qwidget_qpa.cpp: 671 linhas. O código correspondente à essa reengenharia já encontra-se integrado no branch 4.8, com o nome Qt Platform Abstraction. Portanto, aqueles que tiverem o repositório clonado podem observar em src/gui/kernel a existência de arquivos com o sufixo _qpa.h:

  • qplatformclipboard_qpa.h
  • qplatformcursor_qpa.h
  • qplatformeventloopintegration_qpa.h
  • qplatformglcontext_qpa.h
  • qplatformintegrationplugin_qpa.h
  • qplatformintegration_qpa.h
  • qplatformnativeinterface_qpa.h
  • qplatformscreen_qpa.h
  • qplatformwindowformat_qpa.h
  • qplatformwindow_qpa.h

Analisando os nomes desses arquivos (e das classes contidas neles) notamos os componentes que devem ser implementados em um novo port de Qt. Além dos já mencionados ports para Android (Necessitas) e iOS, são outros exemplos que aproveitaram do Lighthouse:

libCaca: convertendo widgets para modo texto. Útil? Não sei, mas vale para exemplificar como ficou mais fácil portar Qt =)

Qt on NaCl:

A tarefa de suportar o Wayland também foi beneficiada por essa nova estrutura, que também está tendo um importante papel no desenvovimento do futuro Qt5. Para referência, os artigos no Qt Labs a respeito desse assunto estão dentro da categoria lighthouse.

Até a próxima =)

Alguns erros comuns ao herdar de QObject

| Comments

Originalmente publicado em http://blog.qtlabs.org.br/2011/07/11/alguns-erros-comuns-ao-herdar-de-qobject

Com o passar do tempo, os erros de uma determinada ferramenta tornam-se familiares de tal forma que solucioná-los passa a ser automático. Entretanto, muitos destes erros não são triviais entre iniciantes, que vez ou outra acabam gastando tempo para contorná-los. Pois vamos tratar de dois que ultimamente tem sido a causa frequente de vários tópicos criados na Qt Devnet. Portanto, se você ainda está se familiarizando com Qt, o texto de hoje é para você. Se você já tem alguma experiência com Qt, vai se lembrar da primeira vez que passou por isso ;)

Consideremos a seguinte declaração de classe:

1
2
3
4
5
6
7
8
9
10
11
class MyClass:public QObject
{
    public:
    MyClass(QObject * parent=0);

signals:
    void aSignal();

public slots:
    void aSlot();
};

Pois bem, você declarou uma classe herdando de QObject e criou um novo sinal e um novo slot. Após conectar este sinal e/ou este slot, você partiu feliz para testar sua aplicação porém nada funciona e você recebe o seguinte alerta:

1
No such signal QObject::aSignal()

E por alguns instantes a pergunta que fica é:

Mas afinal, o que terá acontecido?

Aí que entra um detalhe que passa muitas vezes despercebido entre aqueles que partem estusiasmados para o código: Você esqueceu-se da macro Q_OBJECT na declaração de sua classe. Com alguma prática, alguns resolverão a questão rapidamente e serão felizes. No entanto, outros adicionarão a macro citada e acabarão agora “ouvindo” as seguintes palavras do compilador:

1
main.cpp:(.text+0x54): undefined reference to `vtable for MyClass'

(ok, ok, senhor purista, é um erro do linker, não do compilador)

Afinal, por que eu disse que alguns resolverão este problema e serão felizes e outros enfrentarão este erro? O que eles fizeram de diferente?

Bem, caro leitor, a diferença é que o primeiro lembrou-se de executar qmake depois de adicionar a macro Q_OBJECT, enquanto o segundo partiu ansioso para apenas compilar o projeto.

qmake? Q_OBJECT?

Bem, vamos entender o que aconteceu.

Conforme está escrito na documentação, quando uma classe herda QObject, seja direta ou indiretamente, e declara novas propriedades Q_PROPERTY e/ou novos sinais e/ou slots (vale também para reimplementações), torna-se necessária a adição da macro Q_OBJECT em sua declaração. De forma resumida, esta macro serve como indicador de que o Qt Meta-Object Compiler - mas pode chamar de moc - deve processar esta classe e gerar o arquivo .moc correspondete.

Assim, na primeira situação descrita no início deste texto, o código de fato herda de QObject e declara um novo sinal e um novo slot, porém não apresenta a macro Q_OBJECT. A classe é compilada normalmente, entretanto, não acontece a resolução das informações adicionadas pelo sistema de meta objetos do Qt (no exemplo, o sinal aSignal() não é encontrado). Na sequência, quando segundo usuário adiciona Q_OBJECT e parte direto para o make, acontece um erro de ligação pois falta o arquivo .moc correspondente, onde estariam os símbolos faltantes. Este arquivo .moc não foi gerado pois, ao não executar qmake, não houve a verificação da necessidade do moc entrar em ação.

Portanto, a declaração correta da classe MyClass é:

1
2
3
4
5
6
7
8
9
10
11
12
class MyClass:public QObject
{
    Q_OBJECT
public:
    MyClass(QObject * parent=0);

signals:
    void aSignal();

public slots:
    void aSlot();
};

Existe ainda um outro caso recorrente cuja solução apresenta uma particularidade. Consideremos a nossa class MyClass,  agora declarada no mesmo arquivo que a função main (digamos, num arquivo chamado main.cpp):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MyClass:public QObject
{
    Q_OBJECT
public:
    MyClass(QObject * parent=0)
        : QObject(parent)
    {
    }
signals:
    void aSignal();

public slots:
    void aSlot()
    {
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MyClass myClass;

    return app.exec();
}

O que há de diferente? - Pergunta você.

A princípio nada demais. Porém, atente ao fato da classe MyClass agora estar no mesmo arquivo que a função main. Ao tentar compilar esta versão do nosso exemplo, mais uma vez aparecerá um erro parecido com:

1
undefined reference to `vtable for MyClass'

Ao observar a saída da compilação, você nota que o moc nem é executado. Assim, a classe que necessita ser tratada por ele passa em branco. Para contornar este caso, insira a linha:

1
#include "main.moc"

após a declaração da classe e execute qmake. Isso forçará a execução do moc para criar este arquivo main.moc onde estarão os símbolos referentes aos sinais e slots. (Sim, existe automake, mas não estou tratando de ferramentas adicionais aqui, ok?).

Hoje ficamos concentrados na solução de erros comuns envolvendo moc e a macro Q_OBJECT. Futuramente voltaremos a abordar o tema, entrando em mais detalhes quanto ao papel exercido pelo moc e o conteúdo dos arquivos por ele gerados.

Tem mais algum caso comum de erro que seria interessante abordarmos, para auxiliar os iniciantes? Envie suas sugestões ;)

Qt Contributors’ Summit

| Comments

I'm going to the Qt Contributors' Summit
I’m going to the Qt Contributors’ Summit

We are in Berlin, attending the Qt Contributor’s Summit. 265 people are discussing very important (and interesting) topics for Qt 5 and the open governance. You can follow what’s happening here using the hash code #qtcs on several social networks. And of course, you can check the wiki page of the event.

Personally, I am attending sessions related with QML, Qt-Components, DevNet and open governance.

And yesterday was Thursday, also known as the “Yellow Day”:

Ok, Ademar was not wearing yellow t-shirt. Well, imagine him as the goalkeeper of the team ;)
Ok, Ademar was not wearing yellow t-shirt. Well, imagine him as the goalkeeper of the team ;)

Meego Conf 2011 - San Francisco

| Comments

I am in San Francisco again! =), this time for the MeeGo Conference 2011.

The event is about to begin with the keynote “The Future of MeeGo Starts Now” presented by the president of Linux Foundation, Jim Zemlin.

This time, I’m going to present a talk too! The talk is today and the topic is “Writing applications for multiple MeeGo devices”.

There are other talks by openBossa/INdT guys, check the schedule!

MeeGo Conference and the Mobile Sprint

| Comments

Then November became a very busy month.

After the Qt Dev Days San Francisco, I went quickly to Natal to present a talk about Qt and KDE on mobile devices. It’s time to say thank you for the ENSL organizers - As always, I am late with my posts…

So, last week we went to Dublin, for the MeeGo Conference 2010. As more people already posted, it was a really nice event. The good surprise was the limit of the number of Intel and Nokia people, leaving space for the growing community meet - more than a thousand people attended, very well accommodated in the place chosen (the conference rooms at the Aviva Stadium) with a good work of the organization which managed to keep things working nicely.

Although the short time of the presentations, it was good to have a whole idea of how the project is being conduced, and it looks promising. Unfortunately I left Dublin on Wednesday morning, so I lost the last day which was reserved for the ’unconference’ sections and the football match, but I managed to go to the Guinness Storehouse on Tuesday night, a really good choice for the conference after hours.

With the Lenovo ideapad received from the MeeGo Conference guys (thanks! :-)) in my backpack, I traveled to Berlin for the KDE Mobile Sprint, kindly hosted by KDAB.

I must say, we had fun with the new devices. :-) During the sprint, interesting discussions about MeeGo, new opportunities, QML and Qt-components. Some of the guys dedicated their time to KDE packaging for MeeGo while in parallel other ones worked in QML based widgets for plasma, tested how some applications work on the ideapad’s touchscreen, and tested plasma-mobile and plasma-tablet shells on it. The results of this sprint are being listed in this wiki page.

The first steps :-)
The first steps :-)

Check the videos in Marco’s and Artur’s posts about the sprint. Also, Till Adam showing Kontact Mobile on MeeGo.

Of course there is more work to do, but considering how things worked without special attention to this device (and for MeeGo), we can expect good news in the future.

And here a screenshot of the gallery to test the Plasma QML widgets, with a FlashingLabel, some BusyWidgets and a PushButton. It’s just the beginning.

I know, the gallery is, let's say, weird... :-P
I know, the gallery is, let’s say, weird… :-P

If you’re going to San Francisco…

| Comments

“…You’re gonna meet some gentle people there”

This part of the Scott Mackenzie’s famous song is definitely true. I’m in San Francisco since last Friday and I’m enjoying the city.

The real reason for this trip is the Qt Developer Days, which started yesterday with the training sections and the demo area, where I could see different kind of applications, products and ideas using Qt or created to ease the development with Qt.

It’s just a short post, in a few minutes there will be the first keynote and I have to go downstairs. :-)

This is my first DevDays, special thanks to the Qt Developer Network guys who decided to bring some of the contributors!

The Golden Gate Bridge
The Golden Gate Bridge

Updates

| Comments

Looooong time since my last post. Before writing about new things, an overview of what happened since June:

  • In August, I went to the Belo Horizonte Free Software Festival (in Betim =), where I presented an introductory talk about F/OSS and KDE. It was a nice opportunity to explain some basic concepts to a beginner but very interested public. Thanks KDE e.V. for the support and to the FSLBH organizers!
  • I moved to another apartment (second time this year).
  • I did not go to Akademy =(
  • Our interns developed a simple, but nice, comics-reader as part of their studies to learn Qt. The source code is here and there is a Maemo 5 package here.
  • Two of our cute demos from the last year grew up and became applications. The updated sources are available here and here. Kudos to the guys who made it possible!
  • I’ve been working in the development of kdepim-mobile and, in parallel, I’m following the development of Qt-Components. It is interesting because kdepim-mobile is trying to to use QML as much as possible for the UI, what provides interesting feedback to Qt-Components.
  • Patches for the widgets explorer. Since I started using a vertical panel on the right, I found some bugs and things to improve.
  • I’m enjoying the Qt Developer Network - More about it in a future post :-)
  • Some airport and flight minutes were dedicated to do a first translation of Enzyme and Commit-digest to pt_BR. As I am not a translator, it’s time to request help for the pt_BR translation team =)

Someone said a few weeks ago that a good post must have a picture. Here is a picture of the Municipal Park and the  ”Hippie Fair”, in Belo Horizonte:

Belo Horizonte
Belo Horizonte