
Having created a window in Chapter 1, we will now go on to make the application quit properly when the user tells it to.
We will also use a font that is more exciting than the default one.
#****************************************************************
#**
#** Qt tutorial 2
#**
#****************************************************************
require 'Qt';
a = Qt::Application.new(ARGV)
quit = Qt::PushButton.new('Quit', nil)
quit.resize(75, 30)
quit.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))
Qt::Object.connect(quit, SIGNAL('clicked()'), a, SLOT('quit()'))
a.setMainWidget(quit)
quit.show
a.exec
exit
quit = Qt::PushButton.new( "Quit", nil )
This time, the button says "Quit" and that's exactly what the program will do when the user clicks the button. This is not a coincidence. We still pass nil as the parent, since the button is a top-level window.
quit.resize( 75, 30 )
We've chosen another size for the button since the text is a bit shorter than "Hello world!". We could also have used Qt::FontMetrics to set right size.
quit.setFont( Qt::Font.new( "Times", 18, Qt::Font::Bold ) )
Here we choose a new font for the button, an 18-point bold font from the Times family. Note that we create the font on the spot.
It is also possible to change the default font (using Qt::Application.setFont()) for the whole application.
Qt::Object.connect( quit, SIGNAL('clicked()'), a, SLOT('quit()') )
connect() is perhaps the most central feature of Qt. Note that connect() is a class method in Qt::Object. Do not confuse it with the connect() function in the socket library.
This line establishes a one-way connection between two Qt objects (objects that inherit Qt::Object, directly or indirectly). Every Qt object can have both signals (to send messages) and slots (to receive messages). All widgets are Qt objects. They inherit Qt::Widget which in turn inherits Qt::Object.
Here, the clicked() signal of quit is connected to the quit() slot of a, so that when the button is clicked, the application quits.
The Signals and Slots documentation describes this topic in detail.
When you run this program, you will see an even smaller window than in Chapter 1, filled with an even smaller button.
Try to resize the window. Press the button. Oops! That connect() would seem to make some difference.
Are there any other signals in Qt::PushButton you can connect to quit? Hint: The Qt::PushButton inherits most of its behavior from Qt::Button.
You're now ready for Chapter 3.
[Previous tutorial] [Next tutorial] [Main tutorial page]
| Copyright © 2004 Trolltech | Trademarks | Qt 3.3.3
|