📄 q3datatable.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the Qt3Support module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file. Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "q3datatable.h"#ifndef QT_NO_SQL_VIEW_WIDGETS#include "qevent.h"#include "qsqldriver.h"#include "q3sqleditorfactory.h"#include "q3sqlpropertymap.h"#include "qapplication.h"#include "qlayout.h"#include "qpainter.h"#include "q3popupmenu.h"#include "q3valuelist.h"#include "q3sqlmanager_p.h"#include "qsqlfield.h"#include "qdatetime.h"#include "qcursor.h"#include "qtimer.h"#include "qpointer.h"//#define QT_DEBUG_DATATABLEclass Q3DataTablePrivate{public: Q3DataTablePrivate() : nullTxtChanged( false ), haveAllRows( false ), continuousEdit( false ), editorFactory( 0 ), propertyMap( 0 ), editRow( -1 ), editCol( -1 ), insertRowLast( -1 ), insertPreRows( -1 ), editBuffer( 0 ), cancelMode( false ), cancelInsert( false ), cancelUpdate( false ) {} ~Q3DataTablePrivate() { if ( propertyMap ) delete propertyMap; } QString nullTxt; bool nullTxtChanged; typedef Q3ValueList< uint > ColIndex; ColIndex colIndex; bool haveAllRows; bool continuousEdit; Q3SqlEditorFactory* editorFactory; Q3SqlPropertyMap* propertyMap; QString trueTxt; Qt::DateFormat datefmt; QString falseTxt; int editRow; int editCol; int insertRowLast; QString insertHeaderLabelLast; int insertPreRows; QSqlRecord* editBuffer; bool cancelMode; bool cancelInsert; bool cancelUpdate; int lastAt; QString ftr; QStringList srt; QStringList fld; QStringList fldLabel; Q3ValueList<int> fldWidth; Q3ValueList<QIconSet> fldIcon; Q3ValueList<bool> fldHidden; Q3SqlCursorManager cur; Q3DataManager dat;};#ifdef QT_DEBUG_DATATABLEvoid qt_debug_buffer( const QString& msg, QSqlRecord* cursor ){ qDebug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); qDebug(msg); for ( uint j = 0; j < cursor->count(); ++j ) { qDebug(cursor->field(j)->name() + " type:" + QString(cursor->field(j)->value().typeName()) + " value:" + cursor->field(j)->value().toString() ); }}#endif/*! \enum Q3DataTable::Refresh This enum describes the refresh options. \value RefreshData refresh the data, i.e. read it from the database \value RefreshColumns refresh the list of fields, e.g. the column headings \value RefreshAll refresh both the data and the list of fields*//*! \class Q3DataTable qdatatable.h \brief The Q3DataTable class provides a flexible SQL table widget that supports browsing and editing. \compat Q3DataTable supports various functions for presenting and editing SQL data from a \l Q3SqlCursor in a table. If you want a to present your data in a form use QDataBrowser, or for read-only forms, use QDataView instead. When displaying data, Q3DataTable only retrieves data for visible rows. If the driver supports the 'query size' property the Q3DataTable will have the correct number of rows and the vertical scroll bar will accurately reflect the number of rows displayed in proportion to the number of rows in the dataset. If the driver does not support the 'query size' property, rows are dynamically fetched from the database on an as-needed basis with the scroll bar becoming more accurate as the user scrolls down through the records. This allows extremely large queries to be displayed as quickly as possible, with minimum memory usage. Q3DataTable inherits Q3Table's API and extends it with functions to sort and filter the data and sort columns. See setSqlCursor(), setFilter(), setSort(), setSorting(), sortColumn() and refresh(). When displaying editable cursors, cell editing will be enabled. (For more information on editable cursors, see \l Q3SqlCursor). Q3DataTable can be used to modify existing data and to add new records. When a user makes changes to a field in the table, the cursor's edit buffer is used. The table will not send changes in the edit buffer to the database until the user moves to a different record in the grid or presses Enter. Cell editing is initiated by pressing F2 (or right clicking and then clicking the appropriate popup menu item) and canceled by pressing Esc. If there is a problem updating or adding data, errors are handled automatically (see handleError() to change this behavior). Note that if autoEdit() is false navigating to another record will cancel the insert or update. The user can be asked to confirm all edits with setConfirmEdits(). For more precise control use setConfirmInsert(), setConfirmUpdate(), setConfirmDelete() and setConfirmCancels(). Use setAutoEdit() to control the behavior of the table when the user edits a record and then navigates. (Note that setAutoDelete() is unrelated; it is used to set whether the Q3SqlCursor is deleted when the table is deleted.) Since the data table can perform edits, it must be able to uniquely identify every record so that edits are correctly applied. Because of this the underlying cursor must have a valid primary index to ensure that a unique record is inserted, updated or deleted within the database otherwise the database may be changed to an inconsistent state. Q3DataTable creates editors using the default \l Q3SqlEditorFactory. Different editor factories can be used by calling installEditorFactory(). A property map is used to map between the cell's value and the editor. You can use your own property map with installPropertyMap(). The contents of a cell is available as a QString with text() or as a QVariant with value(). The current record is returned by currentRecord(). Use the find() function to search for a string in the table. Editing actions can be applied programmatically. For example, the insertCurrent() function reads the fields from the current record into the cursor and performs the insert. The updateCurrent() and deleteCurrent() functions perform similarly to update and delete the current record respectively. Columns in the table can be created automatically based on the cursor (see setSqlCursor()). Columns can be manipulated manually using addColumn(), removeColumn() and setColumn(). The table automatically copies many of the properties of the cursor to format the display of data within cells (alignment, visibility, etc.). The cursor can be changed with setSqlCursor(). The filter (see setFilter()) and sort defined within the table are used instead of the filter and sort set on the cursor. For sorting options see setSort(), sortColumn(), sortAscending() and sortDescending(). Note that sorting operations will not behave as expected if you are using a QSqlSelectCursor because it uses user-defined SQL queries to obtain data. The text used to represent NULL, true and false values can be changed with setNullText(), setTrueText() and setFalseText() respectively. You can change the appearance of cells by reimplementing paintField(). Whenever a new row is selected in the table the currentChanged() signal is emitted. The primeInsert() signal is emitted when an insert is initiated. The primeUpdate() and primeDelete() signals are emitted when update and deletion are initiated respectively. Just before the database is updated a signal is emitted; beforeInsert(), beforeUpdate() or beforeDelete() as appropriate.*//*! Constructs a data table which is a child of \a parent, called name \a name.*/Q3DataTable::Q3DataTable ( QWidget * parent, const char * name ) : Q3Table( parent, name ){ init();}/*! Constructs a data table which is a child of \a parent, called name \a name using the cursor \a cursor. If \a autoPopulate is true (the default is false), columns are automatically created based upon the fields in the \a cursor record. Note that \a autoPopulate only governs the creation of columns; to load the cursor's data into the table use refresh(). If the \a cursor is read-only, the table also becomes read-only. In addition, the table adopts the cursor's driver's definition for representing NULL values as strings.*/Q3DataTable::Q3DataTable ( Q3SqlCursor* cursor, bool autoPopulate, QWidget * parent, const char * name ) : Q3Table( parent, name ){ init(); setSqlCursor( cursor, autoPopulate );}/*! \internal*/void Q3DataTable::init(){ d = new Q3DataTablePrivate(); setAutoEdit( true ); setSelectionMode( SingleRow ); setFocusStyle( FollowStyle ); d->trueTxt = tr( "True" ); d->falseTxt = tr( "False" ); d->datefmt = Qt::LocalDate; reset(); connect( this, SIGNAL(selectionChanged()), SLOT(updateCurrentSelection()));}/*! Destroys the object and frees any allocated resources.*/Q3DataTable::~Q3DataTable(){ delete d;}/*! Adds the next column to be displayed using the field \a fieldName, column label \a label, width \a width and iconset \a iconset. If \a label is specified, it is used as the column's header label, otherwise the field's display label is used when setSqlCursor() is called. The \a iconset is used to set the icon used by the column header; by default there is no icon. \sa setSqlCursor() refresh()*/void Q3DataTable::addColumn( const QString& fieldName, const QString& label, int width, const QIconSet& iconset ){ d->fld += fieldName; d->fldLabel += label; d->fldIcon += iconset; d->fldWidth += width; d->fldHidden += false;}/*! Sets the \a col column to display using the field \a fieldName, column label \a label, width \a width and iconset \a iconset. If \a label is specified, it is used as the column's header label, otherwise the field's display label is used when setSqlCursor() is called. The \a iconset is used to set the icon used by the column header; by default there is no icon. \sa setSqlCursor() refresh()*/void Q3DataTable::setColumn( uint col, const QString& fieldName, const QString& label, int width, const QIconSet& iconset ){ d->fld[col]= fieldName; d->fldLabel[col] = label; d->fldIcon[col] = iconset; d->fldWidth[col] = width; d->fldHidden[col] = false;}/*! Removes column \a col from the list of columns to be displayed. If \a col does not exist, nothing happens. \sa QSqlField*/void Q3DataTable::removeColumn( int col ){ if ( d->fld.begin() + col != d->fld.end() ) { d->fld.remove( d->fld.at( col ) ); d->fldLabel.remove( d->fldLabel.at( col ) ); d->fldIcon.remove( d->fldIcon.at( col ) ); d->fldWidth.remove( d->fldWidth.at( col ) ); d->fldHidden.remove( d->fldHidden.at( col ) ); }}/*! Sets the column \a col to the width \a w. Note that unlike Q3Table the Q3DataTable is not immediately redrawn, you must call refresh(Q3DataTable::RefreshColumns) yourself. \sa refresh()*/void Q3DataTable::setColumnWidth( int col, int w ){ if ( d->fldWidth.at( col ) != d->fldWidth.end() ) { d->fldWidth[col] = w; }}/*! Resizes column \a col so that the column width is wide enough to display the widest item the column contains (including the column label). If the table's Q3SqlCursor is not currently active, the cursor will be refreshed before the column width is calculated. Be aware that this function may be slow on tables that contain large result sets.*/void Q3DataTable::adjustColumn( int col ){ Q3SqlCursor * cur = sqlCursor(); if ( !cur || cur->count() <= col ) return; if ( !cur->isActive() ) { d->cur.refresh(); } int oldRow = currentRow(); int w = fontMetrics().width( horizontalHeader()->label( col ) + QLatin1Char('W') ); cur->seek( QSql::BeforeFirst ); while ( cur->next() ) { w = QMAX( w, fontMetrics().width( fieldToString( cur->fieldPtr( indexOf( col ) ) ) ) + 10 ); } setColumnWidth( col, w ); cur->seek( oldRow ); refresh( RefreshColumns );}/*! \reimp*/void Q3DataTable::setColumnStretchable( int col, bool s ){ if ( numCols() == 0 ) { refresh( RefreshColumns ); } if ( numCols() > col ) { Q3Table::setColumnStretchable( col, s ); }}QString Q3DataTable::filter() const{ return d->cur.filter();}/*! \property Q3DataTable::filter \brief the data filter for the data table The filter applies to the data shown in the table. To view data with a new filter, use refresh(). A filter string is an SQL WHERE clause without the WHERE keyword. There is no default filter. \sa sort()*/void Q3DataTable::setFilter( const QString& filter ){ d->cur.setFilter( filter );}/*! \property Q3DataTable::sort \brief the data table's sort The table's sort affects the order in which data records are displayed in the table. To apply a sort, use refresh(). When examining the sort property, a string list is returned with each item having the form 'fieldname order' (e.g., 'id ASC', 'surname DESC'). There is no default sort. Note that if you want to iterate over the sort list, you should iterate over a copy, e.g. \code QStringList list = myDataTable.sort(); QStringList::Iterator it = list.begin(); while( it != list.end() ) { myProcessing( *it ); ++it; } \endcode \sa filter() refresh()*/void Q3DataTable::setSort( const QStringList& sort ){
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -