Qt basic programming

Download Report

Transcript Qt basic programming

Qt basic programming
Markus Veijola
20.08.2009
Lisätietoja:
Sähköposti: [email protected],
Puh: 044-3120554
www.psk.fi
Qt & SQL (Structured Query Language)
• A database is an integrated collection of logically related records or files
which consolidates records into a common pool of data records that
provides data for many applications. A database is a collection of
information that is organized so that it can easily be accessed,
managed, and updated.
• The QSqlDatabase class represents a connection to a particular
database.
• The QSqlDatabase class provides an interface for accessing a
database through a connection. An instance of QSqlDatabase
represents the connection. The connection provides access to the
database via one of the supported database drivers, which are derived
from QSqlDriver. Alternatively, you can subclass your own database
driver from QSqlDriver.
www.psk.fi
Qt & SQL (Structured Query Language)
• Supported drivers
www.psk.fi
Qt & SQL (Structured Query Language)
• Some of the previous database plugins are ready to use, but some of
them you must compile yourself.
• From this www address you can find out how to do it:
http://doc.trolltech.com/3.3/sql-driver.html
• Let’s see an simple example how you connect to database and how you
are able to make queries and store data to database.
• First you must declare what kind of database driver you are using. It is
done with QSqlDatabase class:
QSqlDatabase db = QSqlDatabase::addDatabase(”QSQLITE”);
• After you have declared the driver normally you do the following things to
connect to particular database:
www.psk.fi
Qt & SQL (Structured Query Language)
•
db.setHostName(”edu.psk.database”);//Database server address
db.setDatabaseName(”student.db”);//Database you want to connect
db.setUserName(”Markus”);//Username
db.setPassword(”password”);//Password
After that you are able to try to connect to DB:
if(!db.open())
{
//Connection to database failed, show error
QMessageBox::critical(0,Qobject::tr(”Database error”),
db.lastError().text();
return;
}
www.psk.fi
Qt & SQL (Structured Query Language)
• The connection in the example will be the default connection, because
we don't pass the second argument to addDatabase(), which is the
connection name.
• For example, here we establish two MySQL database connections
named "first" and "second":
QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL",
"first");
QSqlDatabase secondDB =
QSqlDatabase::addDatabase("QMYSQL", "second");
• Note that you have to open both connections with open() function!
• Once a connection is established, we can call the static function
QSqlDatabase::database() from anywhere with a connection name to
get a pointer to that database connection. If we don't pass a connection
name, it will return the default connection. For example:
www.psk.fi
Qt & SQL (Structured Query Language)
QSqlDatabase defaultDB = QSqlDatabase::database();
QSqlDatabase firstDB = QSqlDatabase::database("first");
QSqlDatabase secondDB = QSqlDatabase::database("second");
www.psk.fi
Qt & SQL (Structured Query Language)
• If you connection succeeded, you are able to make queries or insert data
to DB.
• You write and read data to/from DB with QSqlQuery class.
• Example read firtname lastname…from table student where student
firstname is Markus:
QSqlQuery query;
query.exec(”SELECT firstname, surename, address, number from student WHERE
firstname = ”Markus””);
//After the exec call we can go trough the results
while(query.next() )
{
QString firstname = query.value(0).toString();
QString surename = query.value(1).toString();
….
….
}
www.psk.fi
Qt & SQL (Structured Query Language)
• Writing information to database:
query.exec("insert into student values(101, 'Jussi', 'Juonio', 'Kilotie
2', '12121' )");
• You can also create tables to database in ”fly”:
QSqlQuery query;
query.exec("create table studentinfo (id int primary key, ”
"firstname varchar(20), lastname varchar(20), address varchar(20),
studentnum varchar(20) )");
• For more information about SQL statements see i.e.:
http://www.w3schools.com/SQl/default.asp
• You are able to get all supported DB drivers with QSqlDatabase::drivers()
method. This method returns the supported drivers in QStringList. Next
example lists the supported drivers in combobox.
www.psk.fi
Qt & SQL (Structured Query Language)
QStringList list = db.drivers();
QComboBox* serverCombo = new QComboBox();
for( int i = 0; i < list.size(); i++)
{
serverCombo->addItem(list.at(i));
}
www.psk.fi
Qt & SQL (Structured Query Language)
• In addition to QSqlQuery, Qt offers three higher-level classes for
accessing databases.
• These classes are QSqlQueryModel, QSqlTableModel, and
QSqlRelationalTableModel.
• Let’s see an simple example how we can use the QSqlTableModel to get
and show data to user.
www.psk.fi
Qt & SQL (Structured Query Language)
void MyClass::showDBData()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//Use IMDB dayabase (so called in memory)
db.setDatabaseName(":memory:");
if(!db.open())
{
QMessageBox::critical(0, QObject::tr("Cannot open database"),
QObject::tr("Unable to establish a database connection.\n"
"Reason %1 \n"
"Click Cancel to exit.").arg(db.driverName()),
QMessageBox::Cancel);
return;
}
www.psk.fi
Qt & SQL (Structured Query Language)
QSqlTableModel* tableModel = new QSqlTableModel(this,db.getDataBase());
//Tell what table you want to use
tableModel->setTable("studentinfo");
//Set the sorting rule…we sort by firstname (STUDENT_FIRSTNAME, LASTNAME etc. Are defined as enum…)
tableModel->setSort(STUDENT_FIRSTNAME, Qt::AscendingOrder);
tableModel->setHeaderData(STUDENT_FIRSTNAME, Qt::Horizontal, tr("Student firstname"));
tableModel->setHeaderData(STUDENT_LASTNAME, Qt::Horizontal, tr("Student lastname"));
tableModel->setHeaderData(STUDENT_ADDRESS, Qt::Horizontal, tr("Student address"));
tableModel->setHeaderData(STUDENT_NUMBER, Qt::Horizontal, tr("Student number"));
tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
tableModel->select();
//Dont show the id
tableModel->removeColumn(0);
view = new QTableView();
view->setModel(tableModel);
view->setSelectionMode(QAbstractItemView::SingleSelection);
view->setSelectionBehavior(QAbstractItemView::SelectRows);
view->resizeColumnsToContents();
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(view);
mainLayout->addWidget(buttonGroupBox);
setLayout(mainLayout);
}
www.psk.fi
Garphics View
• Graphics View provides a surface for managing and interacting with
a large number of custom-made 2D graphical items, and a view
widget for visualizing the items, with support for zooming and
rotation.
• Graphical items can handle key events, mouse press, move, release
and double click events, and they can also track mouse movement.
• Graphics View provides an item-based approach to model-view
programming and it can be divided to three parts:
– The graphic scene
– The graphic view
– The graphic item
• Lets see an example how all of the parts bind together.
www.psk.fi
Garphics View
• First the let’s look the view scene part.
• QGraphicsScene provides the Graphics View scene. The scene has the
following responsibilities:
– Providing a fast interface for managing a large number of graphics
items
– Propagating events to each item
– Managing item state, such as selection and focus handling
– Providing untransformed rendering functionality; mainly for printing
www.psk.fi
Garphics View
• The scene serves as a container (like QList ) for QGraphicsItem
objects.
• Items are added to the scene by calling QGraphicsScene::addItem(),
and then retrieved by calling one of the many item discovery functions
i.e. QGraphicsScene::itemAt()
• QGraphicsScene's event propagation architecture schedules scene
events for delivery to items, and also manages propagation between
items. If the scene receives a mouse press event at a certain position,
the scene passes the event on to whichever item is at that position.
• QGraphicsScene also manages certain item states, such as item
selection and focus.
• i.e. you can set focus on an item by calling
QGraphicsScene::setFocusItem() or QGraphicsItem::setFocus(), or get
the current focus item by calling QGraphicsScene::focusItem().
www.psk.fi
Garphics View
• QGraphicsView provides the view widget, which visualizes the contents
of a scene.
• The view receives input events from the keyboard and mouse, and
translates these to scene events (converting the coordinates used to
scene coordinates where appropriate), before sending the events to the
visualized scene.
www.psk.fi
Garphics View
• QGraphicsItem is the base class for graphical items in a scene.
• Graphics View provides several standard items for typical shapes, such
as rectangles (QGraphicsRectItem), ellipses (QGraphicsEllipseItem)
and text items (QGraphicsTextItem), but the most powerful
QGraphicsItem features are available when you write a custom item.
Among other things, QGraphicsItem supports the following features:
– Mouse press, move, release and double click events, as well as
mouse hover events, wheel events, and context menu events.
– Keyboard input focus, and key events
– Drag and drop
– Grouping, both through parent-child relationships, and with
QGraphicsItemGroup
– Collision detection
www.psk.fi
Garphics View
• Let’s look an simple example how this all works…
• You can find from network drive an example called GraphicViewExample
which we look trough now, and see how it works.
• Excercice
– Change the code so that you are able to move the ball with arrow
keys.
www.psk.fi
XML
• XML or EXtensible Markup Language has same kind of syntax like
HTML.
• While HTML is designed to show data, XML is designed to transfer and
store data.
• XML tags are not predefined as in HTML, where every tag has some
meaning for parser (i.e. <body>).
• XML is just plain text where you define your own tag names.
• System that can handle plain ASCII text can handle XML -> platform
independent format!
• Let’s take alook what Qt offers us for handling XML files.
www.psk.fi
XML
• You get the handle to XML file by using QFile class
QFile file(”my_xml_file.xml”);
if(!file.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::critical(0,
QObject::tr("File Error"),
QObject::tr("Trying to read from file %1 failed.\n Reason:
%2").arg(fileName, file.errorString()),
QMessageBox::Close,
QMessageBox::NoButton);
return false;
}
www.psk.fi
XML
• When you have the handle to file, you can use QXmlStreamReader and
QXmlStreamWriter classes to read and write XML files.
• The QXmlStreamReader class provides a fast parser for reading wellformed XML via a simple streaming API.
• The QXmlStreamWriter class provides an XML writer with a simple
streaming API.
• Let’s look first QXmlStreamReader interface…
• First you define what device you use to read from (NOTE! The device
can also be an socket for example!):
QXmlStreamReader::setDevice(&file);
• QXmlStreamReader::readNext () function sets the file pointer to point to
next element in XML.
• QXmlStreamReader::atEnd() returns true if you reached the end of the
XML file.
www.psk.fi
XML
• QXmlStreamReader::isStartElement() with this function you can check if
the currently readed tag is an XML start tag (i.e. <NAME>) and with
QXmlStreamReader::isEndElement() you can check if the current tag is
an end element (i.e. </NAME>)
• QXmlStreamReader::name() function returns the tag name.
• QXmlStreamReader:: readElementText() returns the value between
start and end tags (i.e. <BAND>Ramones</BAND> would return
Ramones).
• Here is an simple XML file that we parse in our example.
• You can find the files xmlhandler.cpp and xmlhandler.h files from your
network drive.
• Let’s see how it works
www.psk.fi
XML
<?xml version="1.0" encoding="UTF-8"?>
<studentrecords>
<entry term="studentinfo">
<forename>Jussi</forename>
<surename>Juonio</surename>
<address>Juoniokuja 12</address>
<number>12122</number>
</entry>
<entry term="studentinfo">
<forename>Kalle</forename>
<surename>Kolmonen</surename>
<address>Kallentie 1</address>
<number>12312</number>
</entry>
</studentrecords>
www.psk.fi
XML
• Excercice: Create an UI that uses xmlhandler class and our simple xml
file. Create the UI so that user can also save the new data to XML.
www.psk.fi
ESITYKSEN LOPPU / KIITOS
www.psk.fi
Ammatillisen osaamisen ja kilpailukyvyn kehittäjä – tulevan tekijä.
www.psk.fi