int main( int argc, char** argv ) { QApplication app( argc, argv ); // Create a report KDReports::Report report; // open a DB connection to an in-memory database QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(":memory:"); if( !db.open() ) { QMessageBox::critical(0, QObject::tr("Cannot open database"), QObject::tr("Cannot create connection to the requested database. Your Qt is probably lacking the QSQLITE driver. Please check your Qt installation." ), QMessageBox::Cancel ); return false; } // fill the DB with some test data QSqlQuery query; query.exec("create table airlines (id int primary key, " "name varchar(20), homecountry varchar(2))"); query.exec("insert into airlines values(1, 'Lufthansa', 'DE')"); query.exec("insert into airlines values(2, 'SAS', 'SE')"); query.exec("insert into airlines values(3, 'United', 'US')"); query.exec("insert into airlines values(4, 'KLM', 'NL')"); query.exec("insert into airlines values(5, 'Aeroflot', 'RU')"); // Create a QSqlTableModel, connect to the previously created database, fill // the db with some data. QSqlTableModel tableModel( 0, db ); tableModel.setTable( "airlines" ); tableModel.select(); tableModel.removeColumn( 0 ); tableModel.setHeaderData( 0, Qt::Horizontal, QObject::tr("Name") ); tableModel.setHeaderData( 1, Qt::Horizontal, QObject::tr("Home country") ); QFont font = app.font(); font.setBold( true ); tableModel.setHeaderData( 0, Qt::Horizontal, font, Qt::FontRole ); tableModel.setHeaderData( 1, Qt::Horizontal, font, Qt::FontRole ); // associate the model and load the XML file report.associateModel( "airlines", &tableModel ); QFile reportFile( ":/Database.xml" ); if( !reportFile.open( QIODevice::ReadOnly ) ) { QMessageBox::warning( 0, QObject::tr( "Warning" ), QObject::tr( "Could not open report description file 'Database.xml'. Please start this program from the DatabaseXML directory." ) ); return -1; } KDReports::ErrorDetails details; if( !report.loadFromXML( &reportFile, &details ) ) { QMessageBox::warning( 0, QObject::tr( "Warning" ), QObject::tr( "Could not parse report description file:\n%1" ).arg(details.message()) ); reportFile.close(); return -2; } // To show a print preview: KDReports::PreviewDialog preview( &report ); return preview.exec(); //return app.exec(); }
int main( int argc, char** argv ) { QApplication app( argc, argv ); KDReports::Report report; // open a DB connection to an in-memory database QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(":memory:"); if( !db.open() ) { QMessageBox::critical(0, QObject::tr("Cannot open database"), QObject::tr("Cannot create connection to the requested database. Your Qt is probably lacking the QSQLITE driver. Please check your Qt installation." ), QMessageBox::Cancel ); return false; } // fill the DB with some test data QSqlQuery query; query.exec("create table airlines (id int primary key, " "name varchar(20), homecountry varchar(2))"); query.exec("insert into airlines values(1, 'Lufthansa', 'DE')"); query.exec("insert into airlines values(2, 'SAS', 'SE')"); query.exec("insert into airlines values(3, 'United', 'US')"); query.exec("insert into airlines values(4, 'KLM', 'NL')"); query.exec("insert into airlines values(5, 'Aeroflot', 'RU')"); // Create a QSqlTableModel, connect to the previously created database, fill // the db with some data. QSqlTableModel tableModel( 0, db ); tableModel.setTable( "airlines" ); tableModel.select(); tableModel.removeColumn( 0 ); tableModel.setHeaderData(0, Qt::Horizontal, QObject::tr("Name")); tableModel.setHeaderData(1, Qt::Horizontal, QObject::tr("Home country")); QFont font = app.font(); font.setBold( true ); tableModel.setHeaderData( 0, Qt::Horizontal, font, Qt::FontRole ); tableModel.setHeaderData( 1, Qt::Horizontal, font, Qt::FontRole ); KDReports::AutoTableElement tableElement( &tableModel ); tableElement.setVerticalHeaderVisible( false ); report.addElement( tableElement ); // To export to an image file: //qDebug() << "Exporting to output.png"; //report.exportToImage( QSize(300, 400), "output.png", "PNG" ); KDReports::PreviewDialog preview( &report ); return preview.exec(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QTableView *tableView = new QTableView; QTableModel tableModel(200,200); tableView->setModel(&tableModel); tableView->setGeometry(430,340,300,300); tableView->show(); return a.exec(); }
void GenericDAO::insert(const QSqlRecord& record, bool addToSyncQueue, DBMode dbMode) { QSqlDatabase& db = DBPool::getInstance()->getDabase(dbMode); QUuid id = Database::variantToUuid(record.value("id")); QString sid = record.value("id").toString(); QSqlTableModel tableModel(0, db); tableModel.setTable(m_table); tableModel.setFilter("id='" + sid + "'"); tableModel.setEditStrategy(QSqlTableModel::OnFieldChange); if (!tableModel.select()) { qDebug() << "GenericDAO::insert() point 1"; throw DatabaseException(tableModel.lastError()); } int n = tableModel.rowCount(); if (n > 1) qDebug() << "GenericDAO::insert() not uniq index id = " << ", table = " << m_table << ", count = " << n; bool sync = dbMode == Local && m_addToSyncQueue && addToSyncQueue; if (n == 0) { if (!tableModel.insertRecord(0, record) || tableModel.lastError().isValid()) { qDebug() << "GenericDAO::insert() point 2"; throw DatabaseException(tableModel.lastError()); } if (sync) Database::addToSyncQueue(db, m_table, id, Database::AddRecord); } else { if (!tableModel.setRecord(0, record) || tableModel.lastError().isValid()) { qDebug() << "GenericDAO::insert() point 3"; throw DatabaseException(tableModel.lastError()); } if (sync) Database::addToSyncQueue(db, m_table, id, Database::UpdateRecord); } }
QMimeData* DbStructureModel::mimeData(const QModelIndexList& indices) const { // Loop through selected indices QByteArray d; foreach(QModelIndex index, indices) { // Only export data for valid indices and only for the SQL column, i.e. only once per row if(index.isValid() && index.column() == 3) { // Add the SQL code used to create the object d = d.append(data(index, Qt::DisplayRole).toString() + ";\n"); // If it is a table also add the content if(data(index.sibling(index.row(), 1), Qt::DisplayRole).toString() == "table") { SqliteTableModel tableModel(0, m_db); tableModel.setTable(data(index.sibling(index.row(), 0), Qt::DisplayRole).toString()); for(int i=0; i < tableModel.rowCount(); ++i) { QString insertStatement = "INSERT INTO `" + data(index.sibling(index.row(), 0), Qt::DisplayRole).toString() + "` VALUES("; for(int j=1; j < tableModel.columnCount(); ++j) insertStatement += QString("'%1',").arg(tableModel.data(tableModel.index(i, j)).toString()); insertStatement.chop(1); insertStatement += ");\n"; d = d.append(insertStatement); } } } } // Create the MIME data object QMimeData* mime = new QMimeData(); mime->setProperty("db_file", m_db->curDBFilename); // Also save the file name to avoid dropping an object on the same database as it comes from mime->setData("text/plain", d); return mime; }
void MyPlugin2SelectionObserver::HandleSelectionChanged(const ISelectionMessage* selectionMessage) { // get selection manager for active selection. ISelectionManager* iSelectionManager = Utils<ISelectionUtils>()->GetActiveSelection(); return; //get pointer to textSelectionSuite using selection manager OR fCurrentSelection. InterfacePtr<ITextSelectionSuite> iTextSelectionSuite(iSelectionManager, UseDefaultIID()); CAlert::InformationAlert("Selection** changed.."); if (iTextSelectionSuite) { //get pointer to integrator target text using textSelectionSuite. //Use to Return a list of interfaces from the "concrete selection" InterfacePtr<const IIntegratorTarget> iIntegratorTarget_text(iTextSelectionSuite, UseDefaultIID()); if (iIntegratorTarget_text == nil) return; RangeData rangeData(0, RangeData::kLeanForward); UIDRef textRef; PMString tagName; PMString childCountString = "xml child count-"; PMString tagUIDString = "UID of TAG -"; UID tagUID; TextIndex startPosXML = 0, endPosXML = 0; int startIndexSelection; int endIndexSelection; // Return a list of interfaces from the "concrete selection" //auto_ptr automatically makes clean up of objects. std::auto_ptr<IIntegratorTarget::TargetSuiteCollection> selectionSuites_text(iIntegratorTarget_text->GetTarget(ITextTarget::kDefaultIID)); for (IIntegratorTarget::TargetSuiteCollection::size_type i = 0; i < selectionSuites_text->size(); i++) { //Get target text. ITextTarget* target = (ITextTarget*)selectionSuites_text->at(i).get(); if (!target) continue; // extract range from target text. rangeData = target->GetRange(); // get start and end index of range selected. startIndexSelection = rangeData.Start(nil); endIndexSelection = rangeData.End(); // get text model for target text. InterfacePtr<ITextModel>textModel(target->QueryTextModel()); // get UIDRef of text model. textRef = target->GetTextModel(); // query xml reference data for text model. IXMLReferenceData *xmlReferenceData = Utils<IXMLUtils>()->QueryXMLReferenceData(textRef); if (xmlReferenceData) { // get xml reference from xml reference data. XMLReference xmlRef = xmlReferenceData->GetReference(); // obtain xml element from xml reference InterfacePtr<IIDXMLElement> xmlElement(xmlRef.Instantiate()); if (xmlElement != nil) { childCountString.AppendNumber(xmlElement->GetChildCount()); XMLReference childRef = xmlElement->GetNthChild(0); InterfacePtr<IIDXMLElement> childXMLElement(childRef.Instantiate()); if (childXMLElement != nil){ tagUID = childXMLElement->GetTagUID(); tagName = childXMLElement->GetTagString(); Utils<IXMLUtils>()->GetElementMarkerPositions(childXMLElement, &startPosXML, &endPosXML); } } } } // for end int length = rangeData.Length(); if (length >= 1) { PMString textFrameContentLength = "selected content length-"; textFrameContentLength.AppendNumber(length); PMString srtPosString = "Start Position XML tag-"; PMString endPosString = "End postion XML tag-"; PMString srtPosSelString = "Start Position of Selection-"; PMString endPosSelString = "End postion Selection-"; srtPosString.AppendNumber(startPosXML); endPosString.AppendNumber(endPosXML); srtPosSelString.AppendNumber(startIndexSelection); endPosSelString.AppendNumber(endIndexSelection); CAlert::InformationAlert(textFrameContentLength); CAlert::InformationAlert(childCountString); CAlert::InformationAlert(tagName); CAlert::InformationAlert(srtPosString); CAlert::InformationAlert(endPosString); CAlert::InformationAlert(srtPosSelString); CAlert::InformationAlert(endPosSelString); if (startPosXML <= startIndexSelection && endPosXML >= endIndexSelection) { CAlert::InformationAlert("Selection inside tag- "+tagName); } else { CAlert::WarningAlert("Selection not inside tag- " + tagName); } } } // --------:: Table selection ::--------- InterfacePtr<ITableSelectionSuite> iTableSelectionSuite(fCurrentSelection, UseDefaultIID()); if (iTableSelectionSuite == nil) return; InterfacePtr<const IIntegratorTarget> iIntegratorTarget_table(iTableSelectionSuite, UseDefaultIID()); if (iIntegratorTarget_table == nil) return; UIDRef tableUIDRef; GridArea tableGridArea; PMString PMRowCount = "Total no of rows-"; PMString PMColCount = "Total no of cols-"; std::auto_ptr<IIntegratorTarget::TargetSuiteCollection> selectionSuites_table(iIntegratorTarget_table->GetTarget(ITableTarget::kDefaultIID)); for (IIntegratorTarget::TargetSuiteCollection::size_type i = 0; i < selectionSuites_table->size(); i++) { ITableTarget* target = (ITableTarget*)selectionSuites_table->at(i).get(); if (!target) continue; tableUIDRef = target->GetModel(); if (tableUIDRef != UIDRef(nil, kInvalidUID)) { CAlert::WarningAlert("Table selection occured"); tableGridArea = target->GetRange(); } InterfacePtr<ITableModel>tableModel(target->QueryModel()); if (tableModel != nil) { RowRange totalRows = tableModel->GetTotalRows(); ColRange totalCols = tableModel->GetTotalCols(); int rowCount = totalRows.count; int colCount = totalCols.count; PMRowCount.AppendNumber(rowCount); PMColCount.AppendNumber(colCount); CAlert::InformationAlert(PMRowCount); CAlert::InformationAlert(PMColCount); InterfacePtr<ITableLayout> tableLayout(tableModel, UseDefaultIID()); if (tableLayout == nil) { break; } CAlert::InformationAlert("table layout present"); ITableLayout::frame_iterator frameIter = tableLayout->begin_frame_iterator(); CAlert::InformationAlert("Frame Iterator ppresent"); CAlert::InformationAlert("Frame Iterator present"); InterfacePtr<ITableFrame> tableFrame(frameIter->QueryFrame()); CAlert::InformationAlert("table frame ppresent"); if (tableFrame == nil){ break; } CAlert::InformationAlert("table frame present"); UIDRef tableContainerUIDRef = tableFrame->GetFrameRef(); if (tableContainerUIDRef == nil){ break; } CAlert::InformationAlert("table container UIDRef present"); InterfacePtr<IFrameType> frameType(tableContainerUIDRef, UseDefaultIID()); //if (frameType == nil) { //break; //} CAlert::InformationAlert("container frame present"); PMString textFrameType = "Is container , text frame-"; // TYPE OF TEXT FRAME // bool isTextFrame = frameType->IsTextFrame(); CAlert::InformationAlert("Is text frame success"); if (true) { textFrameType.Append("YES"); CAlert::InformationAlert(textFrameType); } else { textFrameType.Append("NO"); CAlert::InformationAlert(textFrameType); } } } };
int main(int argc, char *argv[]) { QApplication app(argc, argv); // ![0] QStandardItemModel model(0, 1); populateListModel(&model); // ![0] QWidget toplevel; QVBoxLayout *layout = new QVBoxLayout(&toplevel); // ![1] QMaemo5ValueButton *button1 = new QMaemo5ValueButton("Value besides text"); button1->setValueLayout(QMaemo5ValueButton::ValueBesideText); QMaemo5ListPickSelector *selector1 = new QMaemo5ListPickSelector; selector1->setModel(&model); // not setting the current index means that the value is empty. button1->setPickSelector(selector1); // ![1] // ![2] QStandardItemModel tableModel(0, 0); populateTableModel(&tableModel); // ![2] // ![3] QMaemo5ValueButton *button2 = new QMaemo5ValueButton("Value under text"); button2->setValueLayout(QMaemo5ValueButton::ValueUnderText); QMaemo5ListPickSelector *selector2 = new QMaemo5ListPickSelector; selector2->setModel(&tableModel); selector2->setModelColumn(2); selector2->setCurrentIndex(5); button2->setPickSelector(selector2); // ![3] // create a custom view we want a table view instead of a list QTableView *view = new QTableView(); view->setEditTriggers(QAbstractItemView::NoEditTriggers); // try to get a sensible column width and row height view->setModel(&tableModel); // set the model in order to get correct column widths view->resizeColumnsToContents(); view->resizeRowsToContents(); view->horizontalHeader()->setStretchLastSection(true); view->verticalHeader()->setVisible(false); view->horizontalHeader()->setVisible(false); view->setSelectionBehavior(QAbstractItemView::SelectRows); view->setSelectionMode(QAbstractItemView::SingleSelection); // five rows should be visible as a default if (view->verticalHeader()->sectionSize(0)>0) view->setMinimumHeight(view->verticalHeader()->sectionSize(0) * 5); QMaemo5ValueButton *button3 = new QMaemo5ValueButton("Value centered under text"); button3->setValueLayout(QMaemo5ValueButton::ValueUnderTextCentered); QMaemo5ListPickSelector *selector3 = new QMaemo5ListPickSelector; selector3->setModel(&tableModel); selector3->setModelColumn(2); selector3->setView(view); // set our new custom view selector3->setCurrentIndex(0); button3->setPickSelector(selector3); layout->addWidget(button1); layout->addWidget(button2); layout->addWidget(button3); toplevel.show(); return app.exec(); }
bool DBBrowserDB::dump(const QString& filename) { // Open file QFile file(filename); if(file.open(QIODevice::WriteOnly)) { // Create progress dialog. For this count the number of all table rows to be exported first; // this does neither take the table creation itself nor // indices, views or triggers into account but compared to the number of rows those should be neglectable unsigned int numRecordsTotal = 0, numRecordsCurrent = 0; QList<DBBrowserObject> tables = objMap.values("table"); QMutableListIterator<DBBrowserObject> it(tables); while(it.hasNext()) { it.next(); // Remove the sqlite_stat1 table if there is one if(it.value().getname() == "sqlite_stat1" || it.value().getname() == "sqlite_sequence") { it.remove(); } else { // Otherwise get the number of records in this table SqliteTableModel tableModel(0, this); tableModel.setTable(it.value().getname()); numRecordsTotal += tableModel.totalRowCount(); } } QProgressDialog progress(QObject::tr("Exporting database to SQL file..."), QObject::tr("Cancel"), 0, numRecordsTotal); progress.setWindowModality(Qt::ApplicationModal); // Regular expression to check for numeric strings QRegExp regexpIsNumeric("\\d*"); // Open text stream to the file QTextStream stream(&file); // Put the SQL commands in a transaction block stream << "BEGIN TRANSACTION;\n"; // Loop through all tables first as they are required to generate views, indices etc. later for(QList<DBBrowserObject>::ConstIterator it=tables.begin();it!=tables.end();++it) { // Write the SQL string used to create this table to the output file stream << (*it).getsql() << ";\n"; // Get data of this table SqliteTableModel tableModel(0, this); tableModel.setTable((*it).getname()); while(tableModel.canFetchMore()) tableModel.fetchMore(); // Dump all the content of the table for(int row=0;row<tableModel.totalRowCount();row++) { stream << "INSERT INTO `" << (*it).getname() << "` VALUES("; for(int col=1;col<tableModel.columnCount();col++) { QString content; if(tableModel.isBinary(tableModel.index(row, col))) { content = QString("X'%1'").arg(QString(tableModel.data(tableModel.index(row, col), Qt::EditRole).toByteArray().toHex())); if(content.isNull()) content = "NULL"; } else { content = tableModel.data(tableModel.index(row, col)).toString().replace("'", "''"); if(content.isNull()) content = "NULL"; else if(content.length() && !regexpIsNumeric.exactMatch(content)) content = "'" + content + "'"; else if(content.length() == 0) content = "''"; } stream << content; if(col < tableModel.columnCount() - 1) stream << ","; else stream << ");\n"; } // Update progress dialog progress.setValue(++numRecordsCurrent); qApp->processEvents(); if(progress.wasCanceled()) { file.close(); file.remove(); return false; } } } // Now dump all the other objects for(objectMap::ConstIterator it=objMap.begin();it!=objMap.end();++it) { // Make sure it's not a table again if(it.value().gettype() == "table") continue; // Write the SQL string used to create this object to the output file stream << (*it).getsql() << ";\n"; } // Done stream << "COMMIT;\n"; file.close(); return true; } else { return false; } }
QMimeData* DbStructureModel::mimeData(const QModelIndexList& indices) const { // We store the SQL data and the names data separately QByteArray sqlData, namesData; // Loop through selected indices for(const QModelIndex& index : indices) { // Get the item the index points at QTreeWidgetItem* item = static_cast<QTreeWidgetItem*>(index.internalPointer()); // Only export data for valid indices and only once per row (SQL column or Name column). if(index.isValid()) { QString objectType = data(index.sibling(index.row(), ColumnObjectType), Qt::DisplayRole).toString(); // For names, export a (qualified) (escaped) identifier of the item for statement composition in SQL editor. if(objectType == "field") namesData.append(getNameForDropping(item->text(ColumnSchema), item->parent()->text(ColumnName), item->text(ColumnName))); else if(objectType == "database") namesData.append(getNameForDropping(item->text(ColumnName), "", "")); else if(!objectType.isEmpty()) namesData.append(getNameForDropping(item->text(ColumnSchema), item->text(ColumnName), "")); if(objectType != "field" && index.column() == ColumnSQL) { // Add the SQL code used to create the object sqlData.append(data(index, Qt::DisplayRole).toString() + ";\n"); // If it is a table also add the content if(objectType == "table") { SqliteTableModel tableModel(m_db); sqlb::ObjectIdentifier objid(data(index.sibling(index.row(), ColumnSchema), Qt::DisplayRole).toString(), data(index.sibling(index.row(), ColumnName), Qt::DisplayRole).toString()); tableModel.setQuery(sqlb::Query(objid)); if(tableModel.completeCache()) { // Only continue if all data was fetched for(int i=0; i < tableModel.rowCount(); ++i) { QString insertStatement = "INSERT INTO " + objid.toString() + " VALUES("; for(int j=1; j < tableModel.columnCount(); ++j) insertStatement += QString("'%1',").arg(tableModel.data(tableModel.index(i, j), Qt::EditRole).toString()); insertStatement.chop(1); insertStatement += ");\n"; sqlData.append(insertStatement); } } } } } } // Create the MIME data object QMimeData* mime = new QMimeData(); mime->setProperty("db_file", m_db.currentFile()); // Also save the file name to avoid dropping an object on the same database as it comes from // When we have both SQL and Names data (probable row selection mode) we give precedence to the SQL data if (sqlData.length() == 0 && namesData.length() > 0) { // Remove last ", " or "." if (namesData.endsWith(", ")) namesData.chop(2); else if (namesData.endsWith(".")) namesData.chop(1); mime->setData("text/plain", namesData); } else mime->setData("text/plain", sqlData); return mime; }