Post some basic knowledge

Source: Internet
Author: User
Tags qt designer
Document directory
  • Encoding support:
  • Single thread-safe template class in the boost Library:
  • Qt's support for MD5:
  • Sqlite3 database operations in QT:
  • Use of QT designer and UI files
  • Set the icon of the QT application:
  • Q_object
  • Qsetting
  • Create System Tray Icon
  • Automatic destruction of pointers in QT
  • Mainwindow Status Bar
  • Exit Program
  • Mainwindow center display
  • Qlist template class
  • Qitemdelegate and rewrite qtableview Editor
  • Qtableview and qsqltablemodel
  • Foreach
  • Event Processing When mainwindow is maximized
  • Hide to system tray when mainwindow is closed
  • Release of QT applications
Qt Study Notes Time:2010-07-29 20:35 Source:Unknown Author:Devwing was learning QT some time ago and developed a small program "Henan Normal University dormitory Repair System" while learning. Now I have time to summarize it. Some of the Code comes from the network and has forgotten the source. We also point out that we respect the rights and interests of the original author.

Some time ago, while learning QT, I made a small program "Henan Normal University dormitory Repair System". Now I have time to summarize it. Some of the Code comes from the network and has forgotten the source. We also point out that we respect the rights and interests of the original author.

The development environment uses QT creator 1.2.1 Based on QT 4.5.3. The operating system is Windows XP SP3.

  1. Encoding support:
    QTextCodec::setCodecForTr(QTextCodec::codecForName("GB18030"));
  2. Single thread-safe template class in the boost Library:
     template   struct Singleton {     struct object_creator     {         object_creator(){ Singleton::instance(); }         inline void do_nothing()const {}     };       static object_creator create_object;   public:     typedef T object_type;     static object_type& instance()     {         static object_type obj;         create_object.do_nothing();         return obj;     }   };   template   typename Singleton::object_creator Singleton::create_object; 

    Usage:

    QDevWing& devwing = Singleton::instance();
  3. Qt's support for MD5:
    QObject::tr(QCryptographicHash::hash(str.toAscii(),QCryptographicHash::Md5).toHex());
  4.  

  5. Sqlite3 database operations in QT:

    1) first, you must modify the project file (PRO file) and add or modify the following statements:

    QT += sql

    2) Introduce the following header files:

    QtSql

    3) use the qsqldatabase class and qsqlquery for database operations

     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");QString appDir(QApplication::applicationDirPath());db.setDatabaseName(appDir.append("/").append(dbName));//qDebug()<
  6. Use of QT designer and UI files

    After the UI is designed using QT designer, it is saved as a UI file, imported into the project, compiled, and the "UI _ file name. H" file is automatically generated. One of these Interface Usage methods is the multi-Inheritance Method:

    1) introduce the automatically generated header file;

    2) create a class that inherits a qt ui class and the generated UI class:

     class LoginDialog : public QDialog,                    public Ui::Dialog{    Q_OBJECTpublic:    LoginDialog(QDialog* = 0);public slots:    virtual void accept();};

    3) In This subclass, you can easily use the UI components:

    1. First, install the UI in the constructor:

      this->setupUi(this);
    2. You can use the following code to access the UI component:

      this->edit_ID->setFocus();
  7. Set the icon of the QT application:

    1) Create an RC file in the project directory, for example, reportsystem. RC. Content:

    IDI_ICON1ICONDISCARDABLE"reportSystem.ico"

    The reportsystem. ICO is the icon to be set.

    2) add a line to the Pro file:

    RC_FILE = reportSystem.rc
  8. Signal and slot mechanisms:

    1) automatically bound signals and slots:

    If the UI component name is btn_finished, that is, it is a button, and the slot automatically bound to the signal is on_btn_finished_clicked (), that is, add on _ before the Object Name _, the object name is followed by an underscore and a signal name. Therefore, if you want to add processing code for the Click Event of the button, you only need to declare and implement the on_btn_finished_clicked () function in the class where the UI component is located, and the declaration must be written in private slots. Other components and events are similar. For example, the trigger signal of actuserinfo of the action component corresponds to on_actuserinfo_triggered ().

    2) manually bound signals and slots:

    If the function name of the slot to be bound does not meet the requirements above, or you want to create a slot by yourself, you need to manually bind the signal and slot.

    First, create a slot function: declare a member function in the private slots declaration area of the class, such as void registeruser (const qstring &). In addition to common member functions (the return value is useful at this time), the slot function can also be used to bind a certain signal to become a signal processing function. The slot of a signal must have the same parameter signature as that of the signal.

    Second, bind signals and slots: for example, write in the class constructor:

    connect(this->l_register,SIGNAL(linkActivated(QString)),this,SLOT(registerUser(QString)));

    The connect function is a member function of the qobject class. It is used to manually bind signals and slots. The first parameter is the trigger signal object, and the second parameter is the signal type, which is encapsulated with macro signal. The third parameter is the slot object, and the fourth parameter is the slot function, which is encapsulated using the slot () Macro.

  9. Q_object

    All user-defined UI classes in the QT application must inherit from a pre-defined UI class of QT, and add q_object to the class declaration to occupy one row, and use qmake, in this way, you can fully possess the powerful functions (meta objects) of QT, such as signal and slot mechanisms, runtime type information and dynamic attribute systems.

  10. Qsetting

    Qsetting is used to save configuration information in the system. Different systems have different storage locations. For example, Windows stores data in the registry, while Linux stores data in the configuration file. For example:

    1) create an object and specify the storage node: qsettings settings (TR ("devwing"), TR ("reportsystem "));

    2) Setting Value: settings. setvalue ("uid", "1 ");

    3) obtain the value: qstring USTR = settings. Value ("uid", ""). tostring ();

    In the preceding example, in Windows XP, The devwing/reportsystem item is created under HKEY_CURRENT_USER/software/in the registry, and the string uid is added with the value "1 ".

  11. Create System Tray Icon

    1) Add the private member qsystemtrayicon * trayicon to mainwindow;

    2) Add the following code to the mainwindow constructor to create a system tray:

    Qicon icon (":/New/devwing/reportsystem. ICO "); // create a qicon object. The parameter is an icon resource. The value is trayicon = new qsystemtrayicon (this) in the resource file of the Project. trayicon-> seticon (icon ); // use the created qicon object as the system tray icon trayicon-> show (); // display the tray icon qmenu * traymenu = new qmenu (this ); // create a menu traymenu-> addaction (ui-> actreportadd); // Add a menu item traymenu-> addseparator () for the tray menu (); // Add the delimiter trayicon-> setcontextmenu (traymenu) for the tray menu ); // use the create menu as the system tray menu trayicon-> settooltip (TR ("Henan Normal University dormitory repair system"); // set the system tray prompt connect (trayicon, signal (activated (qsystemtrayicon: activationreason), this, slot (onsystemtrayiconclicked (qsystemtrayicon: activationreason); // bind a click signal slot to the system tray

    3) the system tray displays the bubble message prompt:

    Trayicon-> showmessage (TR ("Henan Normal University dormitory repair system"), TR ("minimized here"), qsystemtrayicon: information, 5000 );

    4) Hide the system tray icon:

    trayIcon->hide();
  12. Automatic destruction of pointers in QT

    Qt extends C ++. If the pointer object has a parent object, you do not need to explicitly release the memory. You can delete the Q class (qobject inheritance class) when a pointer or Q-class object is destructed, its sub-objects are also deleted or destructed. Here, the parent-child relationship is not an inheritance relationship, but a parent class specified in the constructor's parameters or a parent class specified through the setparent () function. We need to explicitly release isolated pointers without parent objects.

  13. Mainwindow Status Bar

    1) set the font:

    QFont font;font.setPointSize(10);ui->statusBar->setFont(font);

    2) display the message:

    UI-> statusbar-> showmessage (TR ("ready "));

    3) Clear the message:

    ui->statusBar->clearMessage();
  14. Exit Program

    By default, the QT application exits when the user closes the last window. This is determined by the qapplication: quitonlastwindowclosed attribute. You can use qapplication: setquitonlastwindowclosed (false) to Prevent Automatic exit of the QT application. In this way, you can use the system tray to display and hide the program window.

  15. Mainwindow center display

    By default, mainwindow is not centered. However, it provides the move function to achieve the same effect:

     QDesktopWidget* desktop = QApplication::desktop();move((desktop->width() - this->width())/2, (desktop->height() - this->height())/2);
  16. Qlist template class

    The qlist template class is used for linked list operations. It reloads <and other operators to simplify operations. Qstringlist inherits from qlist, which also inherits these operators. For example:

     QStringList head;head<
  17. Qitemdelegate and rewrite qtableview Editor

    Generally, the qtableview editor is in the text format. When you click a cell in qtableview to modify the data, a text box is displayed. If you want to change the editor, you need to specify qitemdelegate for it. The following uses the drop-down box as an example to describe:

    1) first, you need to create a custom class selectdelegate, which inherits from qitemdelegate and declares the q_object macro.

    2) Reload the following public member functions in this class:

    Qwidget * createeditor (qwidget * parent, const qstyleoptionviewitem & option, const qmodelindex & Index) const; // return the UI control constructed in parent, such as new qcombobox (parent ); void seteditordata (qwidget * Editor, const qmodelindex & Index) const; // set the value in the known model and void setmodeldata (qwidget * Editor, q1_actitemmodel * Model) of the editor, const qmodelindex & Index) const; // set the value of the known editor to void updateeditorgeometry (qwidget * Editor, const qstyleoptionviewitem & option, const qmodelindex & Index) const; // set the geometric size of the editor, such as editor-> setgeometry (option. rect );

    3) in this way, you can set an editor for a column or a row or all cells in qtableview:

    Selectdelegate * delegate = new selectdelegate (); UI-> tableview-> setitemdelegateforcolumn (1, delegate); // set the drop-down box of the 2nd-column editor.
  18. Qtableview and qsqltablemodel

    Qtableview is a table View class. You can specify a model for it to configure its data and operations. For example, if you set the model to the object of qsqltablemodel, its data will come from the data queried in the database, and modification to it will affect the database.

    1) create a qsqltablemodel object and perform necessary initialization:

    Qsqltablemodel * model = new qsqltablemodel; model-> settable ("record"); // you can specify the table model> setsort (3, QT: descendingorder) in the database ); // set the sorting rule: sort model-> setfilter ("user = 'admin'") in descending order of 4th columns; // set the filter: here, the user must be adminmodel-> seteditstrategy (qsqltablemodel: onmanualsubmit); // set the Editing Policy: submit data manually. Possible values include: qsqltablemodel: onfieldchange (submitted when the cell is changed) and qsqltablemodel: onrowchange (changing row transactions ). Model-> select (); // query data for (INT I = 0; I

    2) bind a model to qtableview:

    ui->tableView->setModel(model);

    3) set qtableview:

    UI-> tableview-> setcolumnhidden (0, true); // hide the 1st Columns

    4) set the focus to a cell to edit:

    UI-> tableview-> edit (model-> index (1st); // modex-> (index (2nd) is used to specify cells in rows and columns.

    5) set the value in a cell of the model:

    Model-> setdata (model-> index (0, 6), TR ("not processed "));

    6) obtain all selected rows:

    QItemSelectionModel *selectionModel = ui->tableView->selectionModel();QModelIndexList indexes = selectionModel->selectedRows();
  19. Foreach

    The foreach keyword is qt's extension to the Standard C ++. You need to pre-compile qmake with QT. You can also use the q_foreach macro, which can be recognized by the Standard C ++ compiler. Foreach is used to easily traverse a set. Syntax:

     foreach(item, collection){//...}
  20. Event Processing When mainwindow is maximized

    1) The protection member of mainwindow needs to be reloaded: Virtual void changeevent (qevent * event );

    2) in the implementation of the changeevent () function, determine the event category. If it is windowstatechange and the current window is maximized, perform related operations. For example:

     if(event->WindowStateChange){if(this->isMaximized()){ui->actToolText->trigger();return;}}
  21. Hide to system tray when mainwindow is closed

    1) The protection member of mainwindow needs to be reloaded: Virtual void closeevent (qcloseevent * event)

    2) display the system tray prompt and hide the window in closeevent () function implementation.

    Trayicon-> showmessage (TR ("Henan Normal University dormitory repair system"), TR ("minimized here"), qsystemtrayicon: information, 5000); hide (); event-> ignore ();
  22. Release of QT applications
    1. First, you need to compile the application in release mode and copy the compiled program file to the release folder.

    2. Next, copy the following dynamic link library to the release Folder: mingwm10.dll, qtcore4.dll, and qtgui4.dll. You can find them under "QT installation directory/QT/bin.

    3. If other functions, such as OpenGL, are used, copy qtopengl4.dll to the release folder.

    4. If the application has the function of accessing the database, you must not only copy qtsql4.dll to the release folder, but also copy the corresponding database Driver (also DLL, put it under the "Publish Folder/sqldrivers" directory. You can find them from the "QT installation directory/QT/plugins/sqldrivers", such as qsqlite4.dll.

    5. If the application contains Chinese characters, you also need to create the codecs directory under the release folder and copy the qcncodecs4.dll under the "QT installation directory/QT/plugins/codecs" directory.

    6. For other functions provided in Plug-In mode, such as imageformats, you also need to copy all required DLL files in the above way.

The source code can be downloaded from here.

22.Why can't I connect to a database if I publish the database program I developed to another machine?

A: This is because the program cannot find the database plug-in. The solution is as follows:

Add the following statement to the main function:

 

Quote:

Qapplication: addlibrarypath (strpluginspath ");

 

 

Strpluginspath is the directory where the plug-in is located. For example, the directory is/myapplication/plugins.

Put the required SQL driver, such as qsqlmysql. dll, qsqlodbc. dll, or the corresponding. So file

/Myapplication/plugins/sqldrivers/

Directory.

This is a solution and a common solution, that is, to write QT under the executable file directory. CONF file to write some system-related directory configurations to QT. for details, see Qt in QT document reference. conf

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.