I have been a lazy programmer. In fact, I haven’t been a programmer at all. This has led to the suspension of my grand project to relearn gui programming, and thus also putting the most interesting blog-series online on hold.

”Don’t attribute to inspiration when boredom will suffice!”
But then something changed in my life. I became bored. Very bored. I idly started to look through my computer for entertainment, and stumbled across my programming folder (the Mecca of unfinished projects). At first
I just chose not to see it, but after I got even more bored I dove in. As some of you might know: there is this limit to how much time you can waste in front of a computer before actually doing something productive.

Since I am studying German I began by writing my own vocabulary training program (there are tons of these out there, but none of them were easy enough (i.e. console based)). After a while I thought that a vocabulary-training GUI would be swell, so I started writing one. I immediately stumbled into trouble.

I had mostly forgotten everything I learned the previous time, so I ended up doing the same errors over again (stupid python2 not using unicode. I can’t wait to use pyqt with python 3).

So, headfirst into the problems(and solutions):
At first I thought about making a table-based UI, with every word in a two-column table. The left side in the table would be the swedish words (un-editable of cource),
and the right side would be empty for me to fill in the German translations. This ended up sucking major balls since it overly complex and boring.

But, good thing for another project of mine, I learned how to create a table using Qt’s Model-View-Controller-stuff. The trick: cheating. Qt provides fantastic comfort-classes for creating this. The display widget (the table) i used was QTreeView. Nothing magic there. The data model (like the ”database” (bad choice of word) where QTreeView gets the data do be displayed) I used was QStandardItemModel. That is where the magic happen. I sat a couple of hours trying to implent a decent model, but I am way too stupid.

This makes it really simple. Just check the following example code:

# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *

import sys

class Win(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # creates a model with 0 rows and 2 columns
        model = QStandardItemModel(0,2)
        model.setHeaderData(0, Qt.Horizontal, QVariant('Horizontal Header 1'))
        model.setHeaderData(1, Qt.Horizontal, QVariant('Horizontal Header 2'))

        model.insertRow(0) # 0 = at the top
        model.setData(model.index(0,0), QVariant("Columnt 1"))
        model.setData(model.index(0,1), QVariant("Columnt 2"))

        treeview = QTreeView(self)
        treeview.setRootIsDecorated(False) #removes the "branches" from the treeview
        treeview.setModel(model)

        self.setCentralWidget(treeview)

app = QApplication(sys.argv)
window = Win()
window.show()
sys.exit(app.exec_())

 

resulting in the STUNNIG, ORGASMIC and FANTASTIC (but still not very useful) window:

example_list

Neat, huh? (except for maybe my copypasted ”columnt”)

Now, as I said, this was a bit too boring when it comes to a vocabulary training program. You sorta see all the words you have to type in, and instead of becoming a fun ”what is to come next” experience, it just becomes a dreadful process of typing words. It also wasn’t nicely integrated with my plans on how the program should work, so i ditched that design.

Instead I went for a more traditional QLabel/QLineEdit design. On the top there is a QLabel that shows you the greeting, but also the result from the last word you typed in. It is green if you are correct, and red if you are not (more on this later). Below the green_red_widget I have another QLabel to display the word-to-translate. Below that one there is a simple QLineEdit to input the German translation of the word displayed.

Here is what it looks like (I am sorry it is fucking ugly, ok?):

Reinventing the Linux GUI

Yay! A visual basic GUI from the early nineties! Anyways. The only extremely cool thing here is of course the puke-green background of the uppermost widget. That one is actually easier than it looks. Example code of a window that changes the background color to green when you click it:

# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *

import sys
import time

class Win(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self)
        self.setAutoFillBackground(True)
        self.pal = self.palette()

    def mousePressEvent(self, event):
        self.pal.setColor(self.backgroundRole(), Qt.green)
        self.setPalette(self.pal)

app = QApplication(sys.argv)
window = Win()
window.show()
sys.exit(app.exec_())

(the setAutoFillBackground(True) is a must, otherwise qt wont update the background color)

This concludes the writing-part of this blogpost. Now to some short examples of what I have found out.

Changing fonts of a QStandardItem and probably almost every other Qt object is done with the setFont(QFont) function. Example:

# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *

import sys
import time

class Win(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self)
        font = QFont()
        font.setPixelSize(25)

        a = QPushButton(self)
        a.setText("Push Me!")
        a.setFont(font)

app = QApplication(sys.argv)
window = Win()
window.show()
sys.exit(app.exec_())

Setting the size of objects is a bit different. There can be a set setSizeHint, or a setMinimumSize often with a QSize(). Look through the Qt docs (which I presume you do regularly btw). Here is how you set a qpushbutton to be a minimum 300×300 px:

# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *

import sys

class Win(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self)

        a = QPushButton(self)
        a.setText("Push Me!")

        size = QSize()
        size.setHeight(300)
        size.setWidth(300)
        a.setMinimumSize(size)

app = QApplication(sys.argv)
window = Win()
window.show()
sys.exit(app.exec_())

And last, ofcource, the everlasting unicode problem (at least if you speak other than ascii). When putting some text in your gui that you got from elsewhere, encode it to utf-8 first by doing:

unicode(string_to_encode, 'utf-8')

.
When going the other way around, first get a QString from the widget (QLineEdit.text() for example does this) and then do the QString.toUtf8() function, and then make it to a python string (might be better ways to do this…):

stringen = str(line_edit.text().toUtf8())

I have been catching up on my python programming the last week. Even more so, I have been catching up on GUI programming with PyQt4. I haven’t programmed anything graphical since maybe early 2005, so beginning again was a bit of a chock. I have spent two days on a ”New beginning” with python and Qt, and it is actually starting to shape up.

My first app was a small chatt client for an even smaller chat server I programmed earlier this week (it just delivers messages between the connected peers, and it has buggy-as-hell groupchat capabilities). Needles to say I encountered many small problems – and of course a couple of huge ones as well.

Out of nowhere I started getting some really weird ”XRender Bad glyphset 152″ output in my app, and All I was doing was appending UTF-8 text to a QTextEdit. Seems I overlooked a small thing:

You cannot access and change Widgets created in another thread. From what I remember from using GTK, and previous versions of Qt this has always been. (Qt was a bit better back then, though). You just cannot in any way modify the GUI from another thread.

Anyways: the way to get around this is of course to use signals and slots.

Another small promlem I kept getting was that a QTextEdit always got me ascii text when I converted  the QString to a pyhton string. I fiddled around with some various str.encode() and str.decode() before I found the QString.toUtf8(). That did the job.

I thought I would make this a small pyqt series with a bit of information about the problems I have had. People seemed to appreciate my lite info-thingie about how to get knemo running in KDE4.1, and perhaps someone might find this page through google. While googling for some pyqt stuff.

The resources I have found valuable are:

The Qt C++ reference – requires some aptness in understanding c++
ZetCode – Really not that great as a reference, but it helps the beginner in grokking the basics
Rempt’s book – Quite outdated, but still a great read. (can be downloaded with HTTRack)
Infopage on pyqt4 – not very explaining, but a good read.

EDIT: also found the Qt reference convertet to python:

http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html

And now, a screenshot of my editor, just to impress my brother:

dogshit

Valspråk

januari 17, 2009

Mitt tidigare valspråk var tråkigt nog identiskt med Svenska Akademiens valspråk ”Snille och smak”. Nu är den tiden över. Jag kände att det inte riktigt passade i tiden, men med tanke på att det valspråket har några hundra år på nacken är det rätt imponerande. Nu är den tiden förbi dock. Mitt nya valspråk är:

”Mot oändligheten, tills vidare”

Mitt nyårslöfte

januari 10, 2009

Trots att jag på tolvslaget mådde skit och hade livsångest så hann jag ändå ge ett nyårslöfte: Jag ska bli en lite sämre människa. Det är så tråkigt och så nittiotal att bli bättre. Jag går en annan väg.

Då menar jag dock såklart inte rent medmänskligt, utan ur duktighetssynpunkt. Nu när jag skriver detta är målet uppnått (och det ska tangeras!) genom att jag en enkel fredag struntat i att öva och gått ut och umgåtts och druckit öl. Imorn kommer jag må dåligt då jag för tillfälligt är salongsberusad, och det känns fantastiskt!

Det är laddat med dopaminersättare (kaffe) och huvudvärkstabletter inför morgondagen. Jag måste faktiskt säga att det blev trevligt. Råkade ta en lite ostrategisk plats då jag hamnade mellan två som (om jag förstått saker rätt) borde suttit bredvid varandra. Åh. om man ändå kunnat gå och bli förälskad.

Kände mig lite tråkig, men det har nog lite med att jag inte umgåtts med folk på riktigt på närmare sju månader. Lite ringrostig får man vara. God natt.

duktighet

januari 8, 2009

Jag känner det ibland. Jag stressar lite för mycket, övar lite för mycket och glömmer bort att umgås. När jag sedan kommer hem tänker jag på skalor, stycken och intonation. Kort sagt: jag är en sjukligt duktig fagottist.

Så plötsligt så stannar man upp och känner att man glömt sig själv nånstans i mellanspelet. Och inte bara har man glömt sig själv, man har också glömt varför det är kul att hålla på. Man gör det man ska, inget mer.

Jag gör så rätt ofta om jag ska vara ärlig – Identifierar mig lite för mycket med att spela fagott så att övningen inte längre är ett medel eller en process,utan något man gör utan att ifrågasätta. Utan att fråga sig själv nånting alls

Det är farligt att mata sin duktiga sida för mycket. Den blir för stor, och till slut kan man inte förhålla sig till en uppgift utan duktighetens infallsvinkel. Är det inte där nånstans ens arbete förlorar sin själ?

Han tog rådet bokstavligt. ”Le inte, men visa tänderna” hade hon sagt. Vad kunde man läsa ur det? Han bestämde sig för att testa på någon, men det fanns inte en människa så långt ögat såg. Eller vänta! Där! En man stod i ett gathörn längre bort, nonchalant rökande en morot.

Han ansträngde sig till sitt yttersta för att se normal ut, men inom honom bubblade förväntningarna som brinnande frityrolja. Ungefär tio meter ifrån morotsmannen skred han till verket. Blicken fixerad på mannens ögon och läpparna smakfullt tillbakadragna.

Under en kort sekund ramlade ett perplext uttryck över mannens ansikte. KATASTROF! Förlust. Ett misslyckande i det att vara människa! Men sekunden, som varade ymnigt, tog slut och mannens ansikte mjuknade. Läpparna drogs tillbaka och visade morotens hela blast. What a blast!

Uppmuntrad av segern gick han vidare och bemötte Stockholm med sina tänder. Vissa beakade nihilistiskt inte alls hans närmanden, men känslosvallet efter sådana bemötanden blev mindre och mindre då den överrumplade majoriteten faktiskt grinade tillbaka.

Det hela fortskred väldigt fint: Han visade tänderna för gubbar på parkbänkar, röda gubbar, kvinnliga gubbar, barngubbar, gravida gubbar, sega gubbar och andra gubbar.

När dagen sedan avlidit gick han hem. Lite tryggare i hur han skulle mota allmänheten.

visa_tanderna

Note to self: typing games

januari 4, 2009

http://play.typeracer.com/

http://www.ryanheise.com/typing-test/

Jag har suttit litegrand och tänkt på hur man kan förbättra svdvorak. Hur bra det är känns så kan det ju alltid bli bättre.

Det mest självklara man kan göra är att ändra byta plats på i och u samt d och h. Både i/u och h/d skrivs med samma finger, men det är h och u (de ovanligare i kombinationen) som ligger under pekfingret. Mysko.

Därefter kan man byta plats på a och o då a är vanligare än o, och således borde ligga under ett starkare finger.

Det är nu redigeringar börjar bli lite problematiska, då de också påverkar stavelser. Man vill ju gärna inte skriva två efterföljande bokstäver med samma finger. Något borde kunna göras åt bokstäverna CRL uppe till höger. Man kanske kan byta plats på c och l, men då blir ctrl+c obekvämare. Det kan man sedan kanske lösa med att göra en rokad med någon av bokstäverna qjkx nere till vänster. Det borde leda till att man kanske får något fler enfingersstavelser, men då bara med typ tl och sc (istället för sl, notera).

Det hela tål att tänkas på. Att man sedan kanske kan flytta ner R eller L istället för H kan nog bidra ännu mer.

Jag ska fundera lite, sen kommer jag nog med ett förslag på en layout.

Min första python-app

december 31, 2008

Ni kan hitta den påCLI-apps.

Det är ett litet script som är tänkt att användas med KDE4.1-plasmoiden Command-watch.

Hello world. I decided to take up my crappy python knowleage recently, and my second script was a small password generator. In the script I had the following:

import random
print(random.randint(0, 16))

It failed miserably with a ”TypeError: ‘module’ object is not callable”, even though it was perfectly valid code. It worked fine in the interactive python shell, but not when running the file. After a bit of googling i found that python prioritizes the current folder files before the regular modules, and my file was called random.py. Thus my script included itself and tried to access the random object – failing miserably.

So in todays life lesson we learned to not use filenames that are also present in the python stdlib.