Beginning Linux Programming Third Edition phần 9 pdf

89 486 0
Beginning Linux Programming Third Edition phần 9 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

GTK_BUTTONS_YES_NO, “Are you sure you want to quit?”); result = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); return (result == GTK_RESPONSE_YES); } 4. delete_event_handler is a callback function that we connect to the Gdk delete event of the main window. The event is emitted when we attempt to close a window, but critically before the GTK+ destroy signal is sent. gboolean delete_event_handler ( GtkWidget *window, GdkEvent *event, gpointer data) { return !confirm_exit(); } 5. When we want to add a CD to the database, the next function is called when a button is clicked on the add CD dialog. If we clicked on Ok, we copy the strings into a non– const char array and pass the data in it to the MySQL interface function add_cd. void addcd_dialog_button_clicked (GtkDialog * dialog, gint response, gpointer userdata) { const gchar *artist_const; const gchar *title_const; const gchar *catalogue_const; gchar artist[200]; gchar title[200]; gchar catalogue[200]; gint *cd_id; if (response == GTK_RESPONSE_ACCEPT) { artist_const = gtk_entry_get_text(GTK_ENTRY (artist_entry)); title_const = gtk_entry_get_text(GTK_ENTRY (title_entry)); catalogue_const = gtk_entry_get_text(GTK_ENTRY (catalogue_entry)); strcpy(artist, artist_const); strcpy(title, title_const); strcpy(catalogue, catalogue_const); add_cd(artist, title, catalogue, cd_id); } addcd_dialog = NULL; gtk_widget_destroy(GTK_WIDGET(dialog)); } 670 Chapter 16 b544977 Ch16.qxd 12/1/03 8:57 AM Page 670 6. This is the heart of the application: retrieving the search results and populating the GtkTreeView. void on_search_button_clicked (GtkButton *button, gpointer userdata) { struct cd_search_st cd_res; struct current_cd_st cd; struct current_tracks_st ct; gint res1, res2, res3; gchar track_title[110]; const gchar *search_string_const; gchar search_string[200]; gchar search_text[200]; gint i = 0, j = 0; GtkTreeStore *tree_store; GtkTreeIter parent_iter, child_iter; memset(&track_title, 0, sizeof(track_title)); 7. Here we get the search string from the entry widget, copy into a non-const variable, and fetch the matching CD IDs. search_string_const = gtk_entry_get_text(GTK_ENTRY (userdata)); strcpy (search_string, search_string_const); res1 = find_cds(search_string, &cd_res); 8. Next we update the appbar to display a message informing the user the result of the search. sprintf(search_text, “ Displaying %d result(s) for search string ‘ %s ‘“, MIN(res1, MAX_CD_RESULT), search_string); gnome_appbar_push (GNOME_APPBAR( appbar), search_text); 9. Now we have the search results and can populate the GtkTreeStore with the results. For each CD ID we need to fetch the corresponding current_cd_st struct that contains the title and author of the CD and then fetch the list of its tracks. We limit the number of entries to MAX_CD_RESULT defined in app_mysql.h to ensure we don’t overfill the GtkTreeStore. tree_store = gtk_tree_store_new (N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); while (i < res1 && i < MAX_CD_RESULT) { res2 = get_cd(cd_res.cd_id[i], &cd); /* Add a new row to the model */ gtk_tree_store_append (tree_store, &parent_iter, NULL); gtk_tree_store_set (tree_store, &parent_iter, COLUMN_TITLE, cd.title, COLUMN_ARTIST, cd.artist_name, COLUMN_CATALOGUE, cd.catalogue, -1 ); 671 Programming GNOME Using GTK+ b544977 Ch16.qxd 12/1/03 8:57 AM Page 671 res3 = get_cd_tracks(cd_res.cd_id[i++], &ct); j = 0; /* Populate the tree with the current cd’s tracks */ while (j < res3) { sprintf(track_title, “ Track %d. “, j+1); strcat(track_title, ct.track[j++]); gtk_tree_store_append (tree_store, &child_iter, &parent_iter); gtk_tree_store_set (tree_store, &child_iter, COLUMN_TITLE, track_title, -1); } } gtk_tree_view_set_model (GTK_TREE_VIEW (treeview), GTK_TREE_MODEL(tree_store)); } 10. The addcd dialog is nonmodal. Therefore, we check to see if it’s already active before creating and showing it. void on_addcd_activate (GtkMenuItem * menuitem, gpointer user_data) { if (addcd_dialog != NULL) return; addcd_dialog = create_addcd_dialog(); gtk_widget_show_all (addcd_dialog); } gboolean close_app ( GtkWidget * window, gpointer data) { gboolean exit; if ((exit = confirm_exit())) { quit_app(NULL, NULL); } return exit; } 11. When we click the About button, a standard GNOME about box pops up. void on_about_activate (GtkMenuItem * menuitem, gpointer user_data) { const char * authors[] = {“Wrox Press”, NULL}; GtkWidget *about = gnome_about_new (“CD Database”, “1.0”, “(c) Wrox Press”, “Beginning Linux Programming”, (const char ** ) authors, NULL, “Translators”, NULL); gtk_widget_show(about); } 672 Chapter 16 b544977 Ch16.qxd 12/1/03 8:57 AM Page 672 Try It Out—main.c 1. After the include statements, we reference username and password entry boxes from interface.c. #include <stdio.h> #include <stdlib.h> #include “app_gnome.h” extern GtkWidget *username_entry; extern GtkWidget *password_entry; gint main(gint argc, gchar *argv[]) { GtkWidget *main_window; GtkWidget *login_dialog; const char *user_const; const char *pass_const; gchar username[100]; gchar password[100]; gint result; 2. We initialize the GNOME libraries as usual, then create and display the main window and our login dialog. gnome_program_init (“CdDatabase”, “0.1”, LIBGNOMEUI_MODULE, argc, argv, GNOME_PARAM_APP_DATADIR, “”, NULL); main_window = create_main_window(); gtk_widget_show_all(main_window); login_dialog = create_login_dialog(); 3. We loop until the user enters a correct username-password combination. The user can quit by clicking Cancel, in which case she is then asked to confirm the action. while (1) { result = gtk_dialog_run (GTK_DIALOG (login_dialog)); if (result != GTK_RESPONSE_ACCEPT) { if (confirm_exit()) return 0; else continue; } user_const = gtk_entry_get_text(GTK_ENTRY (username_entry)); pass_const = gtk_entry_get_text(GTK_ENTRY (password_entry)); strcpy(username, user_const); strcpy(password, pass_const); if (database_start(username, password) == TRUE) break; 673 Programming GNOME Using GTK+ b544977 Ch16.qxd 12/1/03 8:57 AM Page 673 4. If database_start fails, we display an error message and the logon dialog is shown again. GtkWidget * error_dialog = gtk_message_dialog_new (GTK_WINDOW(main_window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, “Could not log on! - Check Username and Password”); gtk_dialog_run (GTK_DIALOG (error_dialog)); gtk_widget_destroy (error_dialog); } gtk_widget_destroy (login_dialog); gtk_main(); return 0; } 5. We’ll write a makefile to compile this application. all: app app: app_mysql.c callbacks.c interface.c main.c app_gnome.h app_mysql.h gcc -o app -I/usr/include/mysql app_mysql.c callbacks.c interface.c main.c - lmysqlclient `pkg-config —cflags —libs libgnome-2.0 libgnomeui-2.0` clean: rm -f app 6. Now we just use the make command to compile the CD application: make –f Makefile When we run app, we should get our CD application—GNOME style (see Figure 16-15)! Figure 16-15 674 Chapter 16 b544977 Ch16.qxd 12/1/03 8:57 AM Page 674 Summary In this chapter, you’ve learned about programming with the GTK+/Gnome libraries to produce profes- sional-looking GUI applications. First, we looked at the X Window System and how toolkits fit into the picture and then saw briefly how GTK+ works under the hood with its object system and signal/call- back mechanism. We then moved on to look at the API of GTK+ widgets, showing simple and more advanced examples in action in several program listings. In looking at the GnomeApp widget, we saw how to easily create menus using helper macros. Finally, we saw how to create modal and nonmodal dialog boxes to interact with the user. Last, we created a GNOME/GTK+ GUI for our CD database, enabling us to log on to the database, search for CDs, and add CDs to the database. In Chapter 17, we’ll look at the rival toolkit to GTK+ and learn how to program KDE using Qt. 675 Programming GNOME Using GTK+ b544977 Ch16.qxd 12/1/03 8:57 AM Page 675 b544977 Ch16.qxd 12/1/03 8:57 AM Page 676 17 Programming KDE Using Qt In Chapter 16, we looked at the GNOME/GTK+ GUI libraries for creating graphical user inter- faces under X. These libraries are only half of the story; the other big player on the GUI scene in Linux is KDE/Qt, and in this chapter we’ll look at these libraries and see how they shape up against the competition. Qt is written in C++, the standard language to write Qt/KDE applications in, so in this chapter we’ll be obliged to take a diversion from our usual C and get our hands dirty with C++. You might like to take this opportunity to refresh your memory on C++, especially reminding yourself of the principles of derivation, encapsulation, method overloading, and virtual functions. In this chapter, we’ll be covering ❑ An introduction to Qt ❑ Installing Qt ❑ Getting started ❑ Signal/slot mechanism ❑ Qt widgets ❑ Dialogs ❑ Menus and toolbars with KDE ❑ Building our CD database application with KDE/Qt Introducing KDE and Qt KDE (K Desktop Environment) is an open source desktop environment based on the Qt GUI library. A host of applications and utilities are part of KDE, including a complete office suite, a Web browser, and even a fully featured IDE for programming KDE/Qt applications. Industry b544977 Ch17.qxd 12/1/03 8:57 AM Page 677 recognition of how advanced KDE’s applications are came when Apple chose to use KDE’s Web browser as the core of an alternative Web browser for Mac OS X, called Safari, that’s faster and offers more func- tionality than Internet Explorer for Macintosh. The KDE project’s homepage is at http://www.kde.org, where you can find detailed information, download KDE and KDE applications, find documentation, join mailing lists, and get other developer information. The latest version of KDE at the time of writing is 3.1, and as this is the version that ships with current Linux distributions, we’ll assume you have KDE 3.1 installed. From a programmer’s perspective, KDE offers dozens of KDE widgets, usually derived from their Qt counterparts to provide enhancements and greater ease of use. KDE widgets offer greater integration with the KDE desktop than we get if we use Qt alone; for example, we get session management. Qt is a mature, cross-platform GUI toolkit written in C++. Qt is the brainchild of Trolltech, a Norwegian company that develops, markets, and supports Qt and Qt-related software for the commercial market. Trolltech loudly touts the cross-platform capabilities of Qt, which is undeniably impressive; Qt has native support on Linux and Unix derivatives, Windows, Mac OS X, and even embedded platforms, which gives Qt a great competitive advantage over its rivals. Trolltech currently sells the commercial versions of Qt at a prohibitively high price for the casual user or hobbyist. Fortunately, Trolltech realizes the value in offering a zero-price version to the free software community, and therefore they offer a Qt Free edition for Linux, Windows, and MacOS. In return for a free version of Qt, Trolltech gets a large user install base, a large programmer community, and a high profile for its product. Qt Free is licensed under the GPL, which means we can program using the Qt libraries and distribute our own GPL software free of charge. As far as we can tell, the two main differences between Qt Free and Qt Professional are the lack of support and the fact that you can’t use Qt software in commercial applications. Trolltech’s Web site at http://www.trolltech.com has all the API documentation that we need. Installing Qt Unless you have a particular reason to compile from source, it’s easiest to find a binary package or RPM for your distribution. Red Hat Linux 9 ships with qt-3.1.1-6.i386.rpm, which we can install using the following command: $ rpm –Uvh qt-3.1.1-6.i386.rpm We can also install it with the package manager application (see Figure 17-1). 678 Chapter 17 b544977 Ch17.qxd 12/1/03 8:57 AM Page 678 Figure 17-1 If you do want to download the source code and build Qt yourself, you can get the latest source from the Trolltech FTP site at ftp://ftp.trolltech.com/qt/source/. The source package comes with exten- sive instructions on how to compile and install Qt in the INSTALL file in the tarred package. $ cd /usr/local $ tar –xvzf qt-x11-free-3.2.0.tar.gz $ ./configure $ make You’ll also need to add a line to /etc/ld.so.conf: /usr/lib/qt3/lib When Qt is properly installed, the QTDIR environment variable should be set to the Qt installation directory. You can check that this is the case as follows: $ echo $QTDIR /usr/lib/qt3 Also make sure the lib directory is added to /etc/ld.so/conf. 679 Programming KDE Using Qt b544977 Ch17.qxd 12/1/03 8:57 AM Page 679 [...]... allowed input: “AAAAAA -99 9D” Allows Athens-2004 but not Sydney-2000 or Atlanta- 199 6 “AAAAnn -99 -99 ;” Allows March–03-12 but not May-03-12 or September-03-12 “000.000.000.000” Allows IP address, for example, 192 .168.0.1 Try It Out—QLineEdit Now let’s see QLineEdit in action 1 First, the header file, LineEdit.h: #include #include #include 6 89 Chapter 17 class LineEdit... present, and those that, if a character is present, restrict it to fall under the rule Meaning Required Character Optional Characters ASCII A–Z, a– z A a ASCII A– Z, a– z, 0– 9 N n Any character X x Numeric 0– 9 9 0 Numeric 1– 9 D d Our inputMask is a string made up from a combination of these characters, optionally terminated by a semicolon There are further special characters that also have meaning:... Windows, etc.) but is usually drawn as a ticked box with text to the right QCheckBox can also be set by us to be a third, in-between state that indicates “no change.” This is useful in the rare occasions when we can’t read the state of the option the QCheckBox represents (and therefore 692 Programming KDE Using Qt set the QCheckBox on or off ourselves), but still want to give the user a chance to leave... 2,1,Qt::AlignRight); resize( 350, 200 ); connect (button, SIGNAL(clicked()), this, SLOT(Clicked())); } void LineEntry::Clicked(void) { std::cout text() show(); return app.exec(); } When we run this program, we get the example... *widget = new QWidget(this); setCentralWidget(widget); QVBoxLayout *vbox = new QVBoxLayout(widget,5, 10,”vbox”); checkbox = new QCheckBox(“CheckButton”, widget, “check”); vbox->addWidget(checkbox); 694 Programming KDE Using Qt 4 Here we create a QButtonGroup for our two radio buttons: QButtonGroup *buttongroup = new QButtonGroup(0); radiobutton1 = new QRadioButton(“RadioButton1”, widget, “radio1”);... the entry before the previously selected option QComboBox::AfterCurrent Inserts the entry after the previously selected option QComboBox::NoInsertion 696 Inserts the new entry as the first option in the list New entry is not inserted into option list Programming KDE Using Qt To set the policy, we call the setInsertionPolicy method on the QComboBox: combo->setInsertionPolicy(QComboBox::AtTop); Let’s... app(argc,argv); ComboBox *window = new ComboBox(); app.setMainWidget(window); window->show(); return app.exec(); } You can see the newly selected options printed out on the command line in Figure 17-6 Figure 17-6 698 Programming KDE Using Qt QListView Lists and trees in Qt are provided by the QListView widget QListView displays both plain lists and hierarchical data divided into rows and columns It’s perfect for... methods to traverse the tree, should we wish to modify particular rows: #include virtual void virtual void insertItem ( QListViewItem * newChild ) setText ( int column, const QString & text ) 699 Chapter 17 virtual QString QListViewItem QListViewItem QListViewItem QListViewItem QListViewItem text ( int column ) const *firstChild () const *nextSibling () const *parent () const *itemAbove () *itemBelow... menus, a toolbar, and a status bar It’ll be featured a great deal in this chapter as you learn how to extend it and add widgets to create an interface We’ll now introduce the mechanism of event-driven programming and add a PushButton widget to our application Signals and Slots As we saw in Chapter 16, signals and signal handling are the primary mechanisms a GUI application uses to respond to user input... and slots, which are Qt’s names for signals and callback functions in GTK+ Note that a Qt signal is quite separate from a UNIX signal, as discussed in Chapter 11 Let’s remind ourselves how event-driven programming works A GUI consists of menus, toolbars, buttons, entry boxes, and many other GUI elements that are collectively known as widgets When the user interacts with a widget, for example activating . input: “AAAAAA -99 9D” Allows Athens-2004 but not Sydney-2000 or Atlanta- 199 6. “AAAAnn -99 -99 ;” Allows March–03-12 but not May-03-12 or September-03-12. “000.000.000.000” Allows IP address, for example, 192 .168.0.1. Try. learn how to program KDE using Qt. 675 Programming GNOME Using GTK+ b54 497 7 Ch16.qxd 12/1/03 8:57 AM Page 675 b54 497 7 Ch16.qxd 12/1/03 8:57 AM Page 676 17 Programming KDE Using Qt In Chapter 16,. $QTDIR /usr/lib/qt3 Also make sure the lib directory is added to /etc/ld.so/conf. 6 79 Programming KDE Using Qt b54 497 7 Ch17.qxd 12/1/03 8:57 AM Page 6 79 Then run the following command as superuser: $ ldconfig Let’s

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

Mục lục

  • Chapter 16: Programming GNOME Using GTK+

    • CD Database Application

      • Try It Out-main.c

      • Summary

      • Chapter 17: Programming KDE Using Qt

        • Introducing KDE and Qt

        • Installing Qt

          • Try It Out-QMainWindow

          • Signals and Slots

            • Try It Out-Signals and Slots

            • Try It Out-Using QBoxLayout Classes

            • Qt Widgets

            • QLineEdit

              • Try It Out-QLineEdit

              • Qt Buttons

                • QButton-The Button Base Class

                • QPushButton

                • QCheckBox

                • QRadioButton

                  • Try It Out-QButtons

                  • QComboBox

                  • Try It Out-QComboBox

                    • QListView

                    • Try It Out-QListView

                    • Dialogs

                      • QDialog

                        • Modal Dialogs

                        • Nonmodal Dialogs

                        • Semimodal Dialog

                        • QMessageBox

                        • QInputDialog

Tài liệu cùng người dùng

Tài liệu liên quan