The dialog box for Qt learning and the creation of the Main Window

Source: Internet
Author: User
Tags emit
The signal and slot mechanisms in QT are almost the same as the common C ++ member functions in QT, which can be virtual functions, overloaded functions, and common functions, protected or private. The slot can be connected with the signal. In this case, every time the signal is sent, the connect statement of the slot is automatically called: connect (sende, signal (signal), receiver, slot (slot) The sender and handler here are pointers to qobject, while signal and slot are function names without parameters, in fact, the signal and slot macros will convert their parameters into corresponding strings. Note: A signal can be connected to multiple connect (slider, signal (valuechanged (INT), spinbox, slot (setvalue (INT); Connect (slider, signal (valuechanged (INT), this, slot (updatestatusbarindicator (INT ))); multiple signals can be connected to the same connect (LCD, signal (overflow), this, slot (handlematherror (); Connect (calculator, signal (divisionbyzero), this, slot (handlematherror (); a signal can be connected to another signal connect (lineedit, signal (textchanged (const qstring &), this, signal (UpdateRecord (const qstring &); QT metadata system mechanism working principle: 1. q_object macro declares that some internal functions must be implemented in each qobject subclass: metaobject (), TR (), qt_metacall (), and other functions. the MOC tool of QT generates the implementation of all functions and signals declared by q_object. 3. use these introspection functions for the qobject member functions such as connect () and disconnect () to complete their work. Use C ++ code to implement the simple dialog box header file: finddialog. h
#ifndef FINDDIALOG_H#define FINDDIALOG_H
#include <QLabel>#include <QDialog>class QCheckBox;//class QLabel;class QLineEdit;class QPushButton;class FindDialog : public QDialog{    Q_OBJECTpublic:    //construct function    FindDialog(QWidget *parent = 0);signals:    void findNext(const QString &str, Qt::CaseSensitivity cs);    void findPrevious(const QString &str, Qt::CaseSensitivity cs);private slots:    void findCliked();    void enabledFindButton(const QString &text);private:    QLabel *label;    QCheckBox *caseCheckBox;    QCheckBox *backwardCheckBox;    QPushButton *findButton;    QPushButton *closeButton;    QLineEdit *lineEdit;};

Implement finddialog. cpp

#include <QtGui>#include <QHBoxLayout>#include <QVBoxLayout>#include <QCheckBox>#include <QLineEdit>#include <QPushButton>#include <QMessageBox>#include "finddialog.h"FindDialog::FindDialog(QWidget *parent)    :QDialog(parent){    label = new QLabel(tr("Find &what:"));    lineEdit = new QLineEdit;    label->setBuddy(lineEdit);    caseCheckBox = new QCheckBox(tr("Match &case"));    backwardCheckBox = new QCheckBox(tr("Search &backword"));    findButton = new QPushButton(tr("&Find"));    findButton->setDefault(true);    findButton->setEnabled(false);    closeButton = new QPushButton(tr("&Clase"));
// Connect (lineedit, signal (textchanged (const qstring), this, slot (enabledfindbutton (const qstring &); Connect (findbutton, signal (clicked (), this, slot (findcliked (); Connect (closebutton, signal (clicked (), this, slot (close ())); // set layout, horizontal layout manager qhboxlayout * topleftlayout = new qhboxlayout; topleftlayout-> addwidget (Label); topleftlayout-> addwidget (lineedit); // vertical layout manager qvboxlayout lef Tlayout = new layout; leftlayout-> addlayout (topleftlayout); leftlayout-> addwidget (casecheckbox); leftlayout-> addwidget (backwardcheckbox); required * rightlayout = new layout; rightlayout-> addwidget (findbutton); rightlayout-> addwidget (closebutton); // adds a stretchable space (A qspaceritem) with zero minimum size // and stretch factor stretch to the end of this box layout. rightlayout-> Ddstretch (); qhboxlayout * mainlayout = new qhboxlayout; mainlayout-> addlayout (leftlayout); mainlayout-> addlayout (rightlayout ); // set the dialog's main layout setlayout (mainlayout); // set the layout of the Main Dialog Box setwindowtitle ("find"); // set the title setfixedheight (sizehint () of the dialog box (). height ();} // The Void finddialog: findcliked () {qmessagebox msgbox; msgbox. settext (TR ("find successfully! "); Msgbox.exe C (); qstring text = lineedit-> text (); QT: casesensiti1_cs = casecheckbox-> ischecked ()? Qt: casesensitive: QT: caseinsensitive; If (backwardcheckbox-> ischecked () {emit findprevious (text, CS);} else {emit findnext (text, CS) ;}} void finddialog: enabledfindbutton (const qstring & text) {findbutton-> setenabled (! Text. isempty ());}
Create Main Window

The main window is a framework for building the application user interface, including menus, tool bars, and dialogs required by the application. How can we implement these functions?

Subclass qmainwindow (inheriting mainwindow)
class MainWindow : public QMainWindow{    Q_OBJECTpublic:    MainWindow();protected:    void closeEvent(QCloseEvent *event);private slots:    void newFile();    void open();    bool save();    bool saveAs();    void find();    void goToCell();    void sort();    void about();    void openRecentFile();    void updateStatusBar();    void spreadsheetModified();
......
};

Implementation Code

Mainwindow: mainwindow () {spreadsheet = new spreadsheet; setcentralwidget (spreadsheet); createactions (); // create action createmenus (); // create menu createcontextmenu (); // create content menu createmedilbars (); // create the toolbar createstatusbar (); // create the status bar readsettings (); // read the configuration finddialog = 0; setmediawicon (qicon (": /images/icon.png "); setcurrentfile (" ");} void mainwindow: closeevent (qcloseevent * event) {If (oktocontinue () {writesettings (); event-> Accept () ;}else {event-> ignore ();}}
......

Graphical user interface (GUI) applications usually use images. method 1 of using images in QT. save images to files and load them at runtime. include the XPM file in the source code. 3. use the resource mechanism of QT (resource = app_name.qrc) app_name.qrc:

<RCC><qresource>    <file>images/icon.png</file>    <file>images/new.png</file>    <file>images/open.png</file>    <file>images/save.png</file>    <file>images/cut.png</file>    <file>images/copy.png</file>    <file>images/paste.png</file>    <file>images/find.png</file>    <file>images/gotocell.png</file></qresource></RCC>

Create menus and toolbar

Qt simplifies programming on menus and toolbar through the "Action" concept. An action can be added to any number of menus and toolbar images. Steps:

1. Create and set actions 2. Create a menu bar and add actions 3. Create a toolbar and add actions to the toolbar
Void mainwindow: createactions () {newaction = new qaction (TR ("& New"), this ); // implement newaction-> seticon (qicon (":/images/new.png"); newaction-> setshortcut (qkeysequence: New ); newaction-> setstatustip (TR ("Create a new spreadsheet file"); Connect (newaction, signal (triggered (), this, slot (newfile ())); openaction = new qaction (TR ("& open... "), this); // openaction to open a file-> seticon (qicon (":/images/open.png "); openaction-> setshortcut (qkeysequence :: open); openaction-> setstatustip (TR ("open an existing spreadsheet file"); Connect (openaction, signal (triggered (), this, slot (open ()));
.........

Create menu

void MainWindow::createMenus(){    fileMenu = menuBar()->addMenu(tr("&File"));    fileMenu->addAction(newAction);    fileMenu->addAction(openAction);    fileMenu->addAction(saveAction);    fileMenu->addAction(saveAsAction);    separatorAction = fileMenu->addSeparator();    for (int i = 0; i < MaxRecentFiles; ++i)        fileMenu->addAction(recentFileActions[i]);    fileMenu->addSeparator();    fileMenu->addAction(exitAction);    editMenu = menuBar()->addMenu(tr("&Edit"));    editMenu->addAction(cutAction);    editMenu->addAction(copyAction);    editMenu->addAction(pasteAction);    editMenu->addAction(deleteAction);
.............

Set context menu and toolbar

void MainWindow::createContextMenu(){    spreadsheet->addAction(cutAction);    spreadsheet->addAction(copyAction);    spreadsheet->addAction(pasteAction);    spreadsheet->setContextMenuPolicy(Qt::ActionsContextMenu);}void MainWindow::createToolBars(){    fileToolBar = addToolBar(tr("&File"));    fileToolBar->addAction(newAction);    fileToolBar->addAction(openAction);    fileToolBar->addAction(saveAction);    editToolBar = addToolBar(tr("&Edit"));    editToolBar->addAction(cutAction);    editToolBar->addAction(copyAction);    editToolBar->addAction(pasteAction);    editToolBar->addSeparator();    editToolBar->addAction(findAction);    editToolBar->addAction(goToCellAction);}
Set Status Bar
void MainWindow::createStatusBar(){    locationLabel = new QLabel(" W999 ");    locationLabel->setAlignment(Qt::AlignHCenter);    locationLabel->setMinimumSize(locationLabel->sizeHint());    formulaLabel = new QLabel;    formulaLabel->setIndent(3);    statusBar()->addWidget(locationLabel);    statusBar()->addWidget(formulaLabel, 1);    connect(spreadsheet, SIGNAL(currentCellChanged(int, int, int, int)),            this, SLOT(updateStatusBar()));    connect(spreadsheet, SIGNAL(modified()),            this, SLOT(spreadsheetModified()));    updateStatusBar();}

The preceding simple graphic interface program (spreadsheet) is attached)

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.