Showing posts with label Qt. Show all posts

What is Qt

Qt is a cross-platform application framework that is used for developing application software that can be run on various software and hardware platforms with little or no change in the underlying codebase, while still being a native application with native capabilities and speed.

Qt is used for developing multi-platform applications and graphical user interfaces (GUIs); however, programs without a GUI can be developed, such as command-line tools and consoles for servers. An example of a non-GUI program using Qt is the Cutelyst web framework. GUI programs created with Qt can have a native-looking interface, in which case Qt is classified as a widget toolkit.

Qt uses standard C++ with extensions including signals and slots that simplify handling of events, and this helps in development of both GUI and server applications which receive their own set of event information and should process them accordingly. Qt supports many compilers, including the GCC C++ compiler and the Visual Studio suite. Qt also provides Qt Quick, that includes a declarative scripting language called QML that allows using JavaScript to provide the logic. With Qt Quick, rapid application development for mobile devices became possible, although logic can be written with native code as well to achieve the best possible performance. Qt can be used in several other programming languages via language bindings. It runs on the major desktop platforms and some of the mobile platforms. It has extensive internationalization support. Non-GUI features include SQL database access, XML parsing, JSON parsing, thread management and network support.

A language construct introduced in Qt for communication between objects which makes it easy to implement the observer pattern while avoiding boilerplate code. The concept is that GUI widgets can send signals containing event information which can be received by other controls using special functions known as slots.

Qt works on many different platforms.

How to close a database connection in Qt?

In most cases a warning "QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed" occurred while adding or closing database in Qt.

How to solve this problem?

// WRONG
QSqlDatabase db = QSqlDatabase::database("mydb");
QSqlQuery query("SELECT ...", db);
QSqlDatabase::removeDatabase("mydb"); // will output the above warning
//Closing database connection in  CORRECT way
db.close();
db =  QSqlDatabase();
QSqlDatabase::removeDatabase("mydb");
And also you can check the database connection is empty or not.

if(db.connectionName().isEmpty())
{
       //Add database.
}

How to check whether a database is exist in Qt?

Check whether a PostgreSQL database is exist or not in Qt.

If we try to create a PostgreSQL database through a Qt application, we have to check whether the given database is exist or not. Otherwise an error occurred during database creation.

I have checked the below method in Qt5 and it is working fine. Please replace 'MY_DB_NAME' by your database name.

QSqlQuery DatabaseQuery;
if(DatabaseQuery.prepare("SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) =  lower('MY_DB_NAME')"))
{
     if(DatabaseQuery.exec())
     {
          if(DatabaseQuery.size() == 0)
          {
               //Database not exist
          }
          else
          {
               //Database exist
          }
     }
}

How to load Google map in Qt application?

Create an html file 'GMap.html' for Google map like this

<!DOCTYPE html>
<html>
<body>

<h1>How to load Google map in Qt application?</h1>

<div id="GMap" style="width:600px;height:600px;"></div>

<script>
function LoadGMap()
{
var mapOptions = {
    center: new google.maps.LatLng(36.778259, -119.417931),
    zoom: 5
}
var map = new google.maps.Map(document.getElementById("GMap"), mapOptions);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=LoadGMap"></script>

</body>
</html>
You must save 'GMap.html' file in your application directory. Then load this file in your Qt application.

In Qt5.5 =<
Header: #include <QWebView>
QString HTMLFilepath =  "YOUR_APPLICATION_PATH+/GMap.html";
QWebView *HTMLPage = new QWebView(parent);
HTMLPage->load(QUrl(QUrl::fromLocalFile(HTMLFilepath));
HTMLPage->show();
In Qt5.6 >=
Header: #include <QWebEngineView>
QString HTMLFilepath =  "YOUR_APPLICATION_PATH+/GMap.html";
QWebEngineView *HTMLPage = new QWebEngineView(parent);
HTMLPage->load(QUrl(QUrl::fromLocalFile(HTMLFilepath));
HTMLPage->show();
'load(url)' loads the specified url and displays it.

Is Qt supports JSON?

YES. Qt provides support for dealing with JSON data. JSON is a format to encode object data derived from Javascript, but now widely used as a data exchange format on the internet. The JSON support in Qt provides an easy to use C++ API to parse, modify and save JSON data. It also contains support for saving this data in a binary format that is directly "mmap"-able and very fast to access.

JSON is a format to store structured data. It has 6 basic data types:
bool, double, string, array, object, null
The text representation of JSON encloses arrays in square brackets ([ ... ]) and objects in curly brackets ({ ... }). Entries in arrays and objects are separated by commas. The separator between keys and values in an object is a colon (:).

A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "Phone numbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}
JSON support in Qt consists of these classes:
QJsonArrayEncapsulates a JSON array
QJsonDocumentWay to read and write JSON documents
QJsonParseErrorUsed to report errors during JSON parsing
QJsonObjectEncapsulates a JSON object
QJsonObject::const_iteratorQJsonObject::const_iterator class provides an STL-style const iterator for QJsonObject
QJsonObject::iteratorQJsonObject::iterator class provides an STL-style non-const iterator for QJsonObject
QJsonValueEncapsulates a value in JSON

Word highlighting in Qt using QRegExp


Highlight a searched word using QRegExp.

The QRegExp class provides pattern matching using regular expressions.QRegExp is modeled on Perl's regexp language. It fully supports Unicode. QRegExp can also be used in a simpler, wildcard mode that is similar to the functionality found in command shells. The syntax rules used by QRegExp can be changed with setPatternSyntax(). In particular, the pattern syntax can be set to QRegExp::FixedString, which means the pattern to be matched is interpreted as a plain string, i.e., special characters (e.g., backslash) are not escaped.

Example 1:

QString text = "A <i>bon mot</i>.";
text.replace(QRegExp("<i>([^<]*)</i>"), "<b>\\1</b>");

Output:
A <b>bon mot</b>.


Example 2:

QString text1 = "This is a sample text.";
text1.replace(QRegExp("(s)"), "<b>\\1</b>");

Output:
Thi<b>s</b> i<b>s</b> a <b>s</b>ample text.


How to initialize QStringList as Empty

QStringList list;
In the above code will generate an empty list.

list=QStringLIst();
This is used for initializing the QStringList as Empty.

Eg:
    QStringList list;
    list << "Web" << "Speckle";

    if(list.isEmpty())
    {
         qDebug("empty");
    }
    else
    {
         qDebug("not empty");
    }


//initializing the QStringList as Empty.
    list=QStringList();
    if(list.isEmpty())
    {
         qDebug("empty");
    }
    else
    {
         qDebug("not empty");
    }


Output of the above code is
not empty
empty

Which are the supported databases in qt?

Qt5 supports SQLite, MySQL, DB2, Borland InterBase, Oracle, ODBC, and PostgreSQL.

The table below lists the drivers included with Qt. Due to license incompatibilities with the GPL, not all of the plugins are provided with Open Source Versions of Qt.

Driver nameDBMS
QDB2IBM DB2 (version 7.1 and above)
QIBASEBorland InterBase
QMYSQLMySQL
QOCIOracle Call Interface Driver
QODBCOpen Database Connectivity (ODBC) - Microsoft SQL Server and other ODBC-compliant databases
QPSQLPostgreSQL (versions 7.3 and above)
QSQLITE2SQLite version 2
QSQLITESQLite version 3
QTDSSybase Adaptive Server
Note: obsolete from Qt 4.7