designer-manual-7.html
来自「QT 下载资料仅供参考」· HTML 代码 · 共 407 行 · 第 1/4 页
HTML
407 行
BookForm bookForm; app.<a href="qapplication.html#setMainWidget">setMainWidget</a>( &bookForm ); bookForm.show(); return app.<a href="qapplication.html#exec">exec</a>(); }</pre><!-- index Databases!Connecting to Multiple Database Servers --><!-- index createConnections() --><!-- index main.cpp --><!-- index addDatabase() --> <p>All the examples presented in this chapter call <tt>createConnections()</tt> after creating the <b>QApplication</b> object in their <tt>main.cpp</tt> file and make use of the default connection. If you need to connect to multiple databases use the two-argument form of <tt>addDatabase()</tt>, passing it both the name of the driver and a unique identifier. This is explained further in the <a href="http://doc.trolltech.com/sql.html">Qt SQL Module documentation</a>.</p><!-- index QSqlDatabase::database() --><p>You do not need to keep a reference to database connections. If you use a single database connection, this becomes the default connection and database functions will use this connection automatically. We can always get a pointer to any of our connections by calling <tt>QSqlDatabase::database()</tt>.</p><p>If you create a <tt>main.cpp</tt> file using <em>Qt Designer</em>, this file will <em>not</em> include <tt>createConnections()</tt>. We do not include this function because it needs the username and password for the database connection, and you may prefer to handle these differently from our simple example function. As a result, applications that preview correctly in <em>Qt Designer</em> will not run unless you implement your own database connections function.</p><h3><a name="2"></a>Using <b>QDataTable</b></h3><p><b>QDataTable</b>s may be placed on any form to provide browsing of database tables and views. <b>QDataTable</b>s can also be used to update or delete records in-place, i.e. inside the cells themselves. Inserting records via a <b>QDataTable</b> usually requires connecting to the<!-- index primeInsert() --> <tt>primeInsert()</tt> signal, so that we can generate primary keys for example, or provide default values. If we wish to present records using a form view (perhaps combining data from several tables and views) we might use several <b>QDataBrowser</b>s and <b>QDataView</b>s.</p><h4><a name="2-1"></a>Quickly Viewing a Database Table</h4><p>This example, along with all the other examples in this chapter, has the project name 'book' and uses the database created by the<!-- index book.sql --> <tt>book.sql</tt> script. As we work through the chapter we will build the 'book' application step by step. Create or copy the <tt>qt/tools/designer/examples/book/book1/main.cpp</tt> file shown earlier. The project file for this first example is <tt>qt/tools/designer/examples/book/book1/book.pro</tt>. Start a new project by clicking <b>File|New</b>, then click the 'C++ Project' icon to invoke the <em>Project Settings</em> dialog. Click the ellipsis button to invoke the <em>Save As</em> dialog; navigate to the project's directory (creating it if necessary). Make sure you're in the project's directory, then enter a project name of 'book.pro'. Click the <b>Save</b> button to return to the <em>Project Settings</em> dialog, then click <b>OK</b>. Now click <b>Project|Database Connections</b>. Fill in the connection information appropriate to your database then press <b>Connect</b>. The connection name should now appear in the left hand list box. (If this doesn't happen you'll need to contact your database systems administrator for help.) Close the dialog.</p><p>We will now create a new form with a <b>QDataTable</b> that's connected to one of our database tables.</p><p>Click <b>File|New</b>. The <em>New File</em> dialog presents us with a number of form templates to choose from. Choose the 'Dialog' form and click <b>OK</b>. Now click <b>File|Save</b>. You will be prompted for a filename, call it <tt>book.ui</tt>.</p><h5><a name="2-1-1"></a>Setting up a <b>QDataTable</b></h5><!-- index Databases!SQL Table Wizard --><!-- index Wizards!SQL Table --><p>To place a <b>QDataTable</b> widget on the form either click <b>Tools|Views|QDataTable</b> or click the <b>QDataTable</b> toolbar button. Click on the form and the SQL Table Wizard will appear.</p><ol type=1><li><p>The <em>Database Connection and Table</em> wizard page is used to set up a connection if one doesn't exist and to choose the table or view for the <b>QDataTable</b>. (See <a href="designer-manual-7.html#1-1">Setting Up Qt Designer's Connections</a>.)</p><p>Click the connection you wish to use, listed in the left hand list box, e.g. "(default)". The available tables and views will appear in the right hand Table list box. Click the 'author' table and then click the <b>Next</b> button.</p><li><p>The <em>Displayed Fields</em> wizard page provides a means of selecting which fields should be displayed in the <b>QDataTable</b> and in what order. By default all fields except the primary key (if there is one) are in the Displayed Fields list box. The left- and right-pointing blue arrow buttons can be used to move fields between the Displayed Fields and the Available Fields list boxes. The blue up and down pointing arrow buttons are used to select the display order of the displayed fields.</p><p>The default settings are the ones we want so simply click <b>Next</b>.</p><li><!-- index Properties!DataTable --><p>The <em>Table Properties</em> wizard page provides convenient access to some of the database-related properties of the <b>QDataTable</b>.</p><p>Make sure the Confirm Deletes checkbox is checked, then click <b>Next</b>.</p><li><p>The <em>SQL</em> wizard page is used to set the <b>QDataTable</b>'s Filter and Sort properties. The Filter is an SQL <tt>WHERE</tt> clause (without the word 'WHERE'). For example, to only list authors whose surnames begin with 'P', we would enter <tt>title LIKE 'P%'</tt>. We'll leave the filter empty. The Available Fields list box lists all the fields. The Sort By list box lists the fields that the <b>QDataTable</b> is to sort by and the direction of their sorting (ASCending or DESCending). The left and right blue arrows are used to move fields between the two list boxes. The up and down blue arrows move fields up and down within the Sort By list box. The ASC or DESC setting is changed with the 'sort order' toolbar button.</p><p>Move the surname and forename fields into the Sort By list box and click <b>Next</b>.</p><li><p>The <em>Finish</em> wizard page gives us the opportunity to go back and change any of our settings. We will be able to change them later through the <b>QDataTable</b>'s properties so we can finish with the wizard.</p><p>Click <b>Finish</b>.</p></ol><p>The table will appear on the form with each column labelled with a default column name. If you wish to change the settings then most of them are available in the property window. The display names, the fields they are based upon, and the order of appearance of the columns can be changed using the <em>Edit Table</em> dialog (explained later) by right clicking the <b>QDataTable</b> and left clicking <b>Edit</b>.</p><h5><a name="2-1-2"></a>Laying out the Form</h5><p>Click on the form and click the <b>Lay Out Vertically</b> toolbar button. Now click <b>Preview|Preview Form</b>; the form will run and the table will automatically display all the records.</p><p>To turn the form we've created into an executable application we must add the<!-- index main.cpp --> <tt>main.cpp</tt> file to the project file and make the project. We should also do some renaming to make things easier to understand.</p><ol type=1><li><p>Click on the form and change its name to 'BookForm' and its caption to 'Book'. Click on the <b>QDataTable</b> and change its name to 'AuthorDataTable'.</p><li><p>Click <b>File|Save All</b>.</p><li><p>Open the project file, e.g.<!-- index book.pro --> <tt>book.pro</tt>, in a plain text editor and add the line: <tt>SOURCES += main.cpp</tt> at the end of the file.</p><li><p>Run <tt>qmake</tt> to generate the make file, e.g. <tt>qmake -o Makefile book.pro</tt>, then make and run the <tt>book</tt> program.</p></ol><p>This example shows how easy it is to use <b>QDataTable</b> to show the contents of a database table or view. You can use the application we've just built to update and delete author records. In the examples that follow we will cover insertions, setting up master-detail relationships, drilldown and foreign key lookups.</p><blockquote><p align="center"><b> A Note on Foreign Keys</b></p><!-- index Foreign Keys --><!-- index Databases!Foreign Keys --><p>In most relational databases tables contain fields which are foreign keys into other tables. In our 'book' database example the authorid in the book table is a foreign key into the author table. When we present a form to the end user we do not usually want the foreign key itself to be visible but rather the text associated with it. Thus, we would want the author's name to appear rather than the author id when we show book information. In many databases, this can be achieved by using a view. See your database's documentation for details.</p></blockquote><h4><a name="2-2"></a>Inserting Records in <b>QDataTable</b>s</h4><!-- index Inserting Records --><!-- index Databases!Inserting Records --><p>Record insertion into a relational database usually requires the generation of a primary key value which uniquely identifies the record in the table. Also we often want to create default values for some fields to minimize the user's work. We will create a slot to capture the <b>QDataTable</b>s<!-- index primeInsert() --> <tt>primeInsert()</tt> signal and populate the <b>QSqlRecord</b> insertion buffer with a unique primary key.</p><ol type=1><li><p>Click <b>Edit|Slots</b> to invoke the <em>Edit Slots</em> dialog. Click <b>New Slot</b>, then enter the slot name <tt>primeInsertAuthor(QSqlRecord*)</tt> into the Slot Properties' Slot line edit box. Click <b>OK</b>.</p><li><p>Click the <b>Connect Signals/Slots</b> toolbar button, then click the AuthorDataTable, drag to the form and release the mouse. The <em>Edit Connections</em> dialog will now appear. Click the<!-- index primeInsert() --> <tt>primeInsert()</tt> signal and then the <tt>primeInsertAuthor()</tt> slot to make the connection. Now click <b>OK</b>.</p><li><p>Click the Source tab of the Object Hierarchy window (click <b>Window|Object Hierarchy</b> to make the window visible if necessary). Click the <tt>primeInsertAuthor()</tt> slot and an editor window will appear.</p><li><p>We must change the <tt>BookForm::primeInsertAuthor()</tt> slot to specify the parameter name and perform the necessary action:</p><pre> void BookForm::primeInsertAuthor( <a href="qsqlrecord.html">QSqlRecord</a> * buffer ) { <a href="qsqlquery.html">QSqlQuery</a> query; query.<a href="qsqlquery.html#exec">exec</a>( "UPDATE sequence SET sequence = sequence + 1 WHERE tablename='author';" ); query.<a href="qsqlquery.html#exec">exec</a>( "SELECT sequence FROM sequence WHERE tablename='author';" ); if ( query.<a href="qsqlquery.html#next">next</a>() ) { buffer-><a href="qsqlrecord.html#setValue">setValue</a>( "id", query.<a href="qsqlquery.html#value">value</a>( 0 ) ); } }</pre> <p>A <b>QSqlQuery</b> object is used to increment and retrieve a unique 'sequence' number for the author table. The signal passed us a pointer to the insertion buffer and we then put the value we've retrieved, i.e. the next sequence number, into the buffer's id field. (Again, note that SQL databases often support a native 'sequence' function. The method used here is inappropriate for production systems, and is for example purposes only. See your database's documentation for details on how to generate unique keys in code. In many cases, the database can generate them automatically, or the database may provide a special syntax for dealing with sequences.)</p></ol><!-- index Deleting!Records!Databases --><!-- index Databases!Deleting Records --><!-- index Updating Records --><!-- index Databases!Updating Records --><p>If we rebuild the application it will now support <tt>INSERT</tt> as well as <tt>UPDATE</tt> and <tt>DELETE</tt>. We could easily have added additional code to insert default values, e.g. today's date into a date field, if necessary.</p><!-- index Databases!Browsing --><!-- index Databases!Confirmations --><!-- index Browsing Databases --><p>Browsing is supported by clicking records and by using the arrow keys. Once a record is active (highlighted) we can edit the it. Press the <b>Insert</b> key to <tt>INSERT</tt> a new record; press <b>F2</b> to <tt>UPDATE</tt> the current record; press the <b>Del</b> key to <tt>DELETE</tt> the current record. All these operations take place immediately. Users can be given the opportunity to confirm their edits by setting the <b>QDataTable</b>'s confirmEdits property to True. If the confirmEdits property is True then user confirmation will be required for all insertions, updates and deletes. For finer control you can set the confirmInsert, confirmUpdate and confirmDelete properties individually.</p><blockquote><p align="center"><b> <b>QDataTable</b> User Interface Interaction</b></p><!-- index Databases!User Interface Interaction --><!-- index User Interface Interaction, Databases --><p>The default user-interface behaviour for <b>QDataTable</b>s is as follows:</p><ul><li><p>Users can move to records by clicking the scrollbar and clicking records with the mouse. They can also use the keyboard's navigation keys, e.g. <b>Left Arrow</b>, <b>Right Arrow</b>, <b>Up Arrow</b>, <b>Down Arrow</b>, <b>Page Up</b>, <b>Page Down</b>, <b>Home</b> and <b>End</b>.</p><li><p><tt>INSERT</tt> is initiated by right-clicking the record and clicking Insert or by pressing the <b>Ins</b> (Insert) key. The user moves between fields using <b>Tab</b> and <b>Shift+Tab</b>. The <tt>INSERT</tt> will take place if the user presses <b>Enter</b> or <b>Tab</b>s off the last field. If autoEdit is TRUE the insert will take place if the user navigates to another record. <tt>INSERT</tt> is cancelled by pressing <b>Esc</b> (Escape). If autoEdit is FALSE navigating to another record also cancels the <tt>INSERT</tt>. Setting confirmInsert to TRUE will require the user to confirm each <tt>INSERT</tt>.</p><li><p><tt>UPDATE</tt> is initiated by right-clicking the record and clicking Update or by pressing <b>F2</b>. The update will take place if the user presses Enter or Tabs off the last field. If autoEdit is TRUE the update will take place if the user navigates to another record. <tt>UPDATE</tt> is cancelled by pressing <b>Esc</b>. If autoEdit is FALSE navigating to another record also cancels the <tt>UPDATE</tt>. Setting confirmUpdate to TRUE will require the user to confirm each <tt>UPDATE</tt>.</p><li><p><tt>DELETE</tt> is achieved by right-clicking the record and clicking Delete or by pressing the <b>Del</b> (Delete) key. Setting confirmDelete to TRUE will require the user to confirm each <tt>DELETE</tt>.</p></ul><p>You can change this default behaviour programmatically if required.</p></blockquote><h4><a name="2-3"></a>Relating Two Tables Together (Master-Detail)</h4><!-- index Databases!Master-Detail Relationships --><!-- index Master-Detail Relationships --><p>Databases often have pairs of tables that are related. For example, an invoice table might list the numbers, dates and customers for invoices, but not the actual invoice items, which an invoice item table might store. In the 'book' application we wish to have a <b>QDataTable</b> that we can use to browse through the authors table and a second <b>QDataTable</b> to show the books they've written.</p><p>Open the book project if it isn't already open <em>Qt Designer</em>. We will modify this project to show two <b>QDataTable</b>s that relate the author table to the book table.</p><ol type=1><li><p>Click the author <b>QDataTable</b> and then click the <b>Break Layout</b> toolbutton.</p><li><p>Resize the <b>QDataTable</b> so that it only occupies the top half of the form.</p><li><p>Now click on the <b>QDataTable</b> toolbutton and click on the bottom half of the form. The SQL Table Wizard will appear. (This Wizard is explained in <a href="designer-manual-7.html#2-1">Quickly Viewing a Database Table</a>.)</p><ol type=1><li><p>Click the connection you're using and click the book table. Click the <b>Next</b> button.</p><li><p>Since we do not want them visible, make sure the authorid and id fields are moved to the Available Fields list box by using the arrow buttons. Move the title field to the top of the Displayed Fields, and move the price field above the notes field. Click the <b>Next</b> button.</p><li><p>On the Table Properties page click the Read Only checkbox then click the <b>Next</b> button.</p><li><p>On the SQL page we will leave the Filter (<tt>WHERE</tt> clause) empty. Move the title field to the Sort By list box and click <b>Next</b>. Now click <b>Finish</b>.</p><li><p>Change this <b>QDataTable</b>'s name to "BookDataTable".</p></ol><li><p><b>Shift+Click</b> the top <b>QDataTable</b> so that both <b>QDataTable</b>s are selected and then click the <b>Lay Out Vertically (in Splitter)</b> toolbar button.</p><li><p>Click on the form and click the <b>Lay Out Vertically</b> toolbar button.</p></ol><p>Run the form by clicking <b>Preview|Preview Form</b>. All the authors are displayed in the top <b>QDataTable</b> and all the books are displayed in the bottom <b>QDataTable</b>. However we only want the books of the currently selected author showing in the bottom <b>QDataTable</b>. We will deal with this by filtering the records in the book table according to the author selected in the author table.</p><blockquote><p align="center"><b> Using the Table Editor</b></p><!-- index Value Editors!SQL Table Editor --><p align="center"><img align="middle" src="edit-dbtable-dialog.png" width="613" height="405"></p><blockquote><p align="center"><em>Edit Table Dialog</em></p></blockquote><p><b>QDataTable</b>s are created and set up using the SQL Table Wizard. Like any other <em>Qt Designer</em> widget their properties may be changed in the Properties window. Some of the column and row based properties can also be be changed using the <em>Edit Table</em> dialog. This dialog is invoked by right clicking the <b>QDataTable</b> and left clicking the <b>Edit</b> menu item. The right hand half of the <em>Edit Table</em> dialog is where we choose the fields we wish to display, their order and their labels. The procedure for creating columns is as follows:</p><ol type=1><li><p>Click the <b>New Column</b> button.</p><li><p>Drop down the Field combobox to list the available fields.</p><li><p>Click the field you wish to include at this point.</p><li><p><em>Optionally</em> edit the Label if the default isn't appropriate.</p><li><p><em>Optionally</em> click the Pixmap ellipsis (<b>...</b>) button to choose a pixmap to be displayed to the left of the column's label. (The ellipsis button appears when you click in the Value part of the Properties list by a <em>pixmap</em> or <em>iconSet</em> property.)</p></ol><p>Repeat the steps listed above for each column you wish to add. Once all the fields have been added you can change their ordering by using the blue up and down arrow buttons. At any point you can press <b>Apply</b> to see how the table will look. Finally click the <b>OK</b> button to save the properties you have set. You can always return to the table editor to change these settings later.</p></blockquote><h5><a name="2-3-1"></a>Filtering One <b>QDataTable</b> by Another</h5><!-- index Databases!Relating Tables --><p>To filter the book table's records we need to capture the author <b>QDataTable</b>'s<!-- index currentChanged() --> <tt>currentChanged()</tt> signal and change the BookDataTable's filter accordingly.</p><ol type=1><li><p>Click <b>Edit|Slots</b>. In the <em>Edit Slots</em> dialog click <b>New Slot</b> and enter a slot name of <tt>newCurrentAuthor(QSqlRecord*)</tt>. Click <b>OK</b>.</p><li><p>Click <b>Connect Signals/Slots</b>, then click the AuthorDataTable <b>QDataTable</b> and drag to the form; release the mouse on the form. The <em>Edit Connections</em> dialog will appear. Click the<!-- index currentChanged() --> <tt>currentChanged()</tt> signal and the <tt>newCurrentAuthor</tt> slot. Click <b>OK</b>.</p><li><p>Click the Source tab of the Object Hierarchy window (click <b>Window|Object Hierarchy</b> to make the window visible if necessary). Click the <tt>newCurrentAuthor()</tt> slot and an editor window will appear.</p>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?