精华内容
下载资源
问答
  • Qt Dialog

    千次阅读 2013-07-17 23:33:56
    一、Dialog的父类和子类 1、父类:QWidget 2、子类:  QAbstractPrintDialog, QColorDialog, QErrorMessage, QFileDialog, QFontDialog, QInputDialog, QMessageBox, QPageSetupDialog, ...

    一、Dialog的父类和子类
    1、父类:QWidget
    2、子类:
     QAbstractPrintDialog,
    QColorDialog,
    QErrorMessage,
    QFileDialog,
    QFontDialog,
    QInputDialog,
    QMessageBox,
    QPageSetupDialog,
    QPrintPreviewDialog,
    QProgressDialog,
    and QWizard.

    3、继承的均为标准对话框。
    包括用于打印的QAbstractPrintDialog,用于设置颜色的QColorDialog,用于报错的QErrorMessage,用于打开、保存的QFileDialog, 用于设置
    字体的QFontDialog,用于输入数据的QInputDialog等等,这里就不再一一介绍了。
    二、我们来看看QInputDialog的成员变量和成员函数

    公有成员(Public Types)
    enum InputDialogOption { NoButtons,UseListViewForComboBoxItems }
    flags InputDialogOptions
    enum InputMode { TextInput, IntInput, DoubleInput}

    受保护成员(Properties)
    cancelButtonText : QString
    comboBoxEditable : bool
    comboBoxItems : QStringList
    doubleDecimals : int
    doubleMaximum : double
    doubleMinimum : double
    doubleValue : int
    inputMode : InputMode
    intMaximum : int
    intMinimum : int
    intStep : int
    intValue : int
    labelText : QString
    okButtonText : QString
    options : InputDialogOptions
    textEchoMode : QLineEdit::EchoMode
    textValue : QString
    注:
    2 properties inherited from QDialog
    58 properties inherited from QWidget
    1 property inherited from QObject

    公有成员函数(Public Functions)
    QInputDialog ( QWidget * parent = 0, Qt::WindowFlags flags = 0)
    ~QInputDialog ()
    QString cancelButtonText () const
    QStringList comboBoxItems () const
    int doubleDecimals () const
    double doubleMaximum () const
    double doubleMinimum () const
    double doubleValue () const
    InputMode inputMode () const
    int intMaximum () const
    int intMinimum () const
    int intStep () const
    int intValue () const
    bool isComboBoxEditable () const
    QString labelText () const
    QString okButtonText () const
    void open ( QObject * receiver, const char *member )
    InputDialogOptions options () const
    void setCancelButtonText ( const QString& text )
    void setComboBoxEditable ( bool editable )
    void setComboBoxItems ( const QStringList& items )
    void setDoubleDecimals ( int decimals )
    void setDoubleMaximum ( double max )
    void setDoubleMinimum ( double min )
    void setDoubleRange ( double min, double max)
    void setDoubleValue ( double value )
    void setInputMode ( InputMode mode )
    void setIntMaximum ( int max )
    void setIntMinimum ( int min )
    void setIntRange ( int min, int max )
    void setIntStep ( int step )
    void setIntValue ( int value )
    void setLabelText ( const QString& text )
    void setOkButtonText ( const QString& text )
    void setOption ( InputDialogOption option, bool on= true )
    void setOptions ( InputDialogOptions options)
    void setTextEchoMode ( QLineEdit::EchoMode mode)
    void setTextValue ( const QString& text )
    bool testOption ( InputDialogOption option )const
    QLineEdit::EchoMode textEchoMode () const
    QString textValue () const

    重用的公有成员函数(Reimplemented Public Functions)
    virtual void done ( int result )
    virtual QSize minimumSizeHint () const
    virtual void setVisible ( bool visible )
    virtual QSize sizeHint () const
    注:
    8 public functions inherited from QDialog
    217 public functions inherited from QWidget
    29 public functions inherited from QObject
    13 public functions inherited from QPaintDevice

    私有信号函数(Signals)
    void doubleValueChanged ( double value )
    void doubleValueSelected ( double value )
    void intValueChanged ( int value )
    void intValueSelected ( int value )
    void textValueChanged ( const QString& text )
    void textValueSelected ( const QString& text )
    注:
    3 signals inherited from QDialog
    1 signal inherited from QWidget
    1 signal inherited from QObject

    静态公有成员函数(Static Public Members)
    double getDouble ( QWidget * parent, const QString& title, const QString & label,double value = 0, double min = -2147483647, double max =2147483647, int decimals = 1, bool * ok = 0, Qt::WindowFlags flags= 0 )
    int getInt ( QWidget * parent, const QString& title, const QString & label, intvalue = 0, int min = -2147483647, int max = 2147483647, int step =1, bool * ok = 0, Qt::WindowFlags flags = 0 )
    QString getItem ( QWidget * parent, const QString& title, const QString & label,const QStringList & items, int current = 0, booleditable = true, bool * ok = 0, Qt::WindowFlags flags = 0 )
    QString getText ( QWidget * parent, const QString& title, const QString & label,QLineEdit::EchoMode mode = QLineEdit::Normal, const QString& text = QString(), bool * ok = 0, Qt::WindowFlagsflags = 0 )
    注:
    4 static public members inherited from QWidget
    5 static public members inherited from QObject

    示例1:为了更好的知道部分设置函数,我们编写了一个空工程,只有main.cpp文件的工程,其中mian函数里是这样的:
    #include <QApplication>
    #include <QDialog>
    #include <QCursor>
    #include <QTextCodec>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QDialog*dialog = new QDialog;
       dialog->setCursor(Qt::PointingHandCursor);
       dialog->setWindowTitle("liuhong");

       //dialog->resize(200,300);
       dialog->setMinimumSize(100,50);
       dialog->setFixedSize(200,100);
       dialog->setMaximumSize(400,300);

       dialog->show();
        return app.exec();
     }

    其中设置了Dialog的光标,窗口标题,最大最小和出现时的窗口大小。
    三、我们来看看Dialog的子类
    1、标准对话框之QInputDialog

    示例2:获得QInputDialog的文本信息。
    #include <QApplication>
    #include <QDir>
    #include <QInputDialog>
    #include <QTextCodec>
    #include <QDebug>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QInputDialog*dialog = new QInputDialog;
        boolok;
        QString text= QInputDialog::getText(dialog,QObject::tr("QInputDialog::getText()"),
                                            QObject::tr("User name:"), QLineEdit::Normal,
                                                QDir::home().dirName(), &ok);
        if (ok&&!text.isEmpty()) qDebug()<<text;
        deletedialog;
        returnapp.exec();
     }

    使用时:
        bool ok;
        QString text = QInputDialog::getText(this,tr("QInputDialog::getText()"),
                                             tr("User name:"), QLineEdit::Normal,
                                             QDir::home().dirName(), &ok);

        if (ok && !text.isEmpty())
            textLabel->setText(text);


    其他三个就不一一示例,列举它们的用法了。
    给出它们使用时:

    获得item:
    QStringList items;
        items << tr("Spring")<< tr("Summer")<< tr("Fall")<< tr("Winter");

        bool ok;
        QString item = QInputDialog::getItem(this,tr("QInputDialog::getItem()"),
                                             tr("Season:"), items, 0, false, &ok);
        if (ok && !item.isEmpty())
            itemLabel->setText(item);

    获得int值:
    bool ok;
        int i = QInputDialog::getInt(this,tr("QInputDialog::getInteger()"),
                                     tr("Percentage:"), 25, 0, 100, 1, &ok);
        if (ok)
            integerLabel->setText(tr("%1%").arg(i));

    获得double值:
     bool ok;
        double d = QInputDialog::getDouble(this,tr("QInputDialog::getDouble()"),
                                           tr("Amount:"), 37.56, -10000, 10000, 2, &ok);
        if (ok)
            doubleLabel->setText(QString("$%1").arg(d));

    如果是我们要单独研究的话,我们可以:
    示例3:
    #include <QApplication>
    #include <QDir>
    #include <QInputDialog>
    #include <QTextCodec>
    #include <QDebug>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QInputDialog*dialog = new QInputDialog;
       dialog->setInputMode(QInputDialog::DoubleInput);
       dialog->setDoubleValue(90.00);
       dialog->setDoubleRange(10,100);
       
       dialog->show();
        returnapp.exec();
     }

    2、标准对话框之QFileDialog
    示例4:打开文件夹,返回文件夹的dir(目录)。
    #include <QApplication>
    #include <QDir>
    #include <QTextCodec>
    #include <QDebug>
    #include <QFileDialog>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QFileDialog*dialog = new QFileDialog;
        QString dir= QFileDialog::getExistingDirectory(dialog, QObject::tr("OpenDirectory"),
                                                        "/home",
                                                        QFileDialog::ShowDirsOnly
                                                        | QFileDialog::DontResolveSymlinks);
       
       qDebug()<<dir;
        returnapp.exec();
     }

    这里getExistingDirectory函数有四个参数,第一个是窗体指针对象,第二个是窗体title,第三个是dir(目录),第四个是options(或是option)。

    看了这个示例之后我们来看看它的成员:
    公有成员(Public Types)
    enum AcceptMode { AcceptOpen, AcceptSave }
    enum DialogLabel { LookIn, FileName, FileType,Accept, Reject }
    enum FileMode { AnyFile, ExistingFile, Directory,ExistingFiles, DirectoryOnly }
    typedef Mode
    enum Option { ShowDirsOnly, DontResolveSymlinks,DontConfirmOverwrite, DontUseNativeDialog, ..., DontUseSheet}
    flags Options
    enum ViewMode { Detail, List }

    私有成员(Properties)
    acceptMode : AcceptMode
    defaultSuffix : QString
    fileMode : FileMode
    options : Options
    viewMode : ViewMode
    注:
    2 properties inherited from QDialog
    58 properties inherited from QWidget
    1 property inherited from QObject

    公共成员函数(Public Functions)
    QFileDialog ( QWidget * parent, Qt::WindowFlags flags )
    QFileDialog ( QWidget * parent = 0, const QString &caption = QString(), const QString & directory =QString(), const QString & filter = QString())
    ~QFileDialog ()
    AcceptMode acceptMode () const
    bool confirmOverwrite () const
    QString defaultSuffix () const
    QDir directory () const
    FileMode fileMode () const
    QDir::Filters filter () const
    QStringList history () const
    QFileIconProvider * iconProvider () const
    bool isNameFilterDetailsVisible () const
    bool isReadOnly () const
    QAbstractItemDelegate * itemDelegate ()const
    QString labelText ( DialogLabel label )const
    QStringList nameFilters () const
    void open ( QObject * receiver, const char *member )
    Options options () const
    QAbstractProxyModel * proxyModel () const
    bool resolveSymlinks () const
    bool restoreState ( const QByteArray& state )
    QByteArray saveState () const
    void selectFile ( const QString &filename )
    void selectNameFilter ( const QString& filter )
    QStringList selectedFiles () const
    QString selectedNameFilter () const
    void setAcceptMode ( AcceptMode mode )
    void setConfirmOverwrite ( bool enabled )
    void setDefaultSuffix ( const QString& suffix )
    void setDirectory ( const QString& directory )
    void setDirectory ( const QDir &directory )
    void setFileMode ( FileMode mode )
    void setFilter ( QDir::Filters filters )
    void setHistory ( const QStringList& paths )
    void setIconProvider ( QFileIconProvider *provider )
    void setItemDelegate ( QAbstractItemDelegate *delegate )
    void setLabelText ( DialogLabel label, constQString & text )
    void setNameFilter ( const QString& filter )
    void setNameFilterDetailsVisible ( bool enabled)
    void setNameFilters ( const QStringList& filters )
    void setOption ( Option option, bool on = true)
    void setOptions ( Options options )
    void setProxyModel ( QAbstractProxyModel *proxyModel )
    void setReadOnly ( bool enabled )
    void setResolveSymlinks ( bool enabled )
    void setSidebarUrls ( constQList<QUrl> & urls)
    void setViewMode ( ViewMode mode )
    QList<QUrl> sidebarUrls() const
    bool testOption ( Option option ) const
    ViewMode viewMode () const
    Reimplemented Public Functions
    virtual void setVisible ( bool visible )
    注:
    8 public functions inherited from QDialog
    217 public functions inherited from QWidget
    29 public functions inherited from QObject
    13 public functions inherited from QPaintDevice

    信号函数(Signals)
    void currentChanged ( const QString& path )
    void directoryEntered ( const QString& directory )
    void fileSelected ( const QString& file )
    void filesSelected ( const QStringList& selected )
    void filterSelected ( const QString& filter )
    注:
    3 signals inherited from QDialog
    1 signal inherited from QWidget
    1 signal inherited from QObject

    静态公有成员函数(Static Public Members)
    QString getExistingDirectory ( QWidget * parent =0, const QString & caption = QString(), constQString & dir = QString(), Options options =ShowDirsOnly )
    QString getOpenFileName ( QWidget * parent = 0,const QString & caption = QString(), const QString& dir = QString(), const QString &filter = QString(), QString * selectedFilter = 0, Options options =0 )
    QStringList getOpenFileNames ( QWidget * parent =0, const QString & caption = QString(), constQString & dir = QString(), const QString& filter = QString(), QString * selectedFilter = 0,Options options = 0 )
    QString getSaveFileName ( QWidget * parent = 0,const QString & caption = QString(), const QString& dir = QString(), const QString &filter = QString(), QString * selectedFilter = 0, Options options =0 )
    注:
    4 static public members inherited from QWidget
    5 static public members inherited from QObject

    重用保护成员函数(Reimplemented Protected Functions)
    virtual void accept ()
    virtual void changeEvent ( QEvent * e )
    virtual void done ( int result )
    注:
    7 protected functions inherited from QDialog
    37 protected functions inherited from QWidget
    7 protected functions inherited from QObject
    1 protected function inherited from QPaintDevice

    我们可以看到option和options
    enum Option { ShowDirsOnly, DontResolveSymlinks,DontConfirmOverwrite, DontUseNativeDialog, ReadOnly,HideNameFilterDetails,DontUseSheet }
    flags Options
    看它的英文组成,我们应该就能知道它们分别有什么用处了。

    示例5:打开文件,返回文件dir(目录)
    #include <QApplication>
    #include <QDir>
    #include <QTextCodec>
    #include <QDebug>
    #include <QFileDialog>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QFileDialog*dialog = new QFileDialog;
       QFileDialog::Options options;
       options|=QFileDialog::DontUseNativeDialog;
        QStringselectedFilter;
        QStringfileName = QFileDialog::getOpenFileName(dialog,
                                                       QObject::tr("QFileDialog::getSaveFileName()"),
                                       "",
                                       QObject::tr("All Files (*);;Text Files (*.txt)"),
                                       &selectedFilter,
                                       options);
       qDebug()<<fileName;
       dialog->show();
        returnapp.exec();
     }
    注:
    这里多了两个参数filter和selectedFilter。
    这个函数的后两个参数可以不用设置(即只需四个参数)。
    filter(过滤器)
    设置方式有两种:
    QObject::tr("Image Files (*.png *.jpg *.bmp)");//设置一个过滤器
    QObject::tr("Images (*.png *.xpm *.jpg);;Text files (*.txt);;XMLfiles (*.xml)");//设置多个过滤器

    打开多个文件夹就不示例了(函数getOpenFileNames)
    只是返回的是QStringList。

    示例6:保存文件
    #include <QApplication>
    #include <QDir>
    #include <QTextCodec>
    #include <QDebug>
    #include <QFileDialog>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QFileDialog*dialog = new QFileDialog;
       QFileDialog::Options options;
       options|=QFileDialog::DontUseNativeDialog;
        QStringselectedFilter;
        QStringfileName = QFileDialog::getSaveFileName(dialog,
                                                       QObject::tr("QFileDialog::getSaveFileName()"),
                                       "",
                                       QObject::tr("All Files (*);;Text Files (*.txt)"),
                                       &selectedFilter,
                                       options);
       qDebug()<<fileName;
       dialog->show();
        returnapp.exec();
     }


    3、标准对话框之QColorDialog
    示例7:设置lable颜色
    void Dialog::setColor()
    {
        QColorcolor;
        if(native->isChecked())
           color = QColorDialog::getColor(Qt::green, this);
        else
           color = QColorDialog::getColor(Qt::green, this, "Select Color",QColorDialog::DontUseNativeDialog);

        if(color.isValid()) {
           colorLabel->setText(color.name());
           colorLabel->setPalette(QPalette(color));
           colorLabel->setAutoFillBackground(true);
        }
    }
    注:这是Qt Domo中的一个范例。
    示例8:自己给出的设置颜色的程序。
    #include <QApplication>
    #include <QColor>
    #include <QTextCodec>
    #include <QDebug>
    #include <QColorDialog>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QColorDialog*dialog = new QColorDialog;
        QColorcolor;
        color =QColorDialog::getColor(Qt::green, dialog, "Select Color",QColorDialog::DontUseNativeDialog);
       dialog->setPalette(QPalette(color));
       dialog->show();
        returnapp.exec();
     }

    4、标准对话框之QFontDialog
    示例9:字体对话框
    #include <QApplication>
    #include <QColor>
    #include <QTextCodec>
    #include <QDebug>
    #include <QFontDialog>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
        QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QFontDialog*dialog = new QFontDialog;
        boolok;
        QFont font =QFontDialog::getFont(&ok, QFont("Times", 12),
                                         dialog);

       dialog->setFont(font);
       qDebug()<<font.key();

       dialog->show();
        returnapp.exec();
     }


    5、标准对话框之QMessageBox
    示例10:警告对话框
    #define MESSAGE \
       QObject::tr("<p>Message boxes have acaption, a text, " \
                  "and any number of buttons, each with standard or custom texts."\
                  "<p>Click a button to close themessage box. Pressing the Esc button " \
                  "will activate the detected escape button (if any).")
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QMessageBox>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
        QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QMessageBoxdialog;
       QMessageBox::StandardButton reply;
        reply =QMessageBox::critical(&dialog,QObject::tr("QMessageBox::critical()"),
                                           MESSAGE,
                                           QMessageBox::Abort | QMessageBox::Retry |QMessageBox::Ignore);
           if (reply == QMessageBox::Abort)
               qDebug()<<"Abort";
           else if (reply == QMessageBox::Retry)
               qDebug()<<"Retry";
           else
               qDebug()<<"Ignore";
        returnapp.exec();
     }

    示例11:信息对话框
    #define MESSAGE \
       QObject::tr("<p>Message boxes have acaption, a text, " \
                  "and any number of buttons, each with standard or custom texts."\
                  "<p>Click a button to close themessage box. Pressing the Esc button " \
                  "will activate the detected escape button (if any).")
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QMessageBox>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QMessageBoxdialog;
       QMessageBox::StandardButton reply;
        reply =QMessageBox::information(&dialog,QObject::tr("QMessageBox::critical()"),
                                           MESSAGE);
        if (reply ==QMessageBox::OK)
              qDebug()<<"OK";
        else
              qDebug()<<"Escape"
        returnapp.exec();
     }

    示例12:询问对话框
    #define MESSAGE \
       QObject::tr("<p>Message boxes have acaption, a text, " \
                  "and any number of buttons, each with standard or custom texts."\
                  "<p>Click a button to close themessage box. Pressing the Esc button " \
                  "will activate the detected escape button (if any).")
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QMessageBox>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QMessageBoxdialog;
       QMessageBox::StandardButton reply;
        reply =QMessageBox::question(&dialog,QObject::tr("QMessageBox::critical()"),
                                           MESSAGE,QMessageBox::Yes | QMessageBox::No |QMessageBox::Cancel);
        if (reply ==QMessageBox::Yes)
                  qDebug()<<"Yes";
        elseif(reply == QMessageBox::No)
                  qDebug()<<"No";
        else
                  qDebug()<<"Cancel";
        returnapp.exec();
     }
    示例13:一般警告对话框
    #define MESSAGE \
       QObject::tr("<p>Message boxes have acaption, a text, " \
                  "and any number of buttons, each with standard or custom texts."\
                  "<p>Click a button to close themessage box. Pressing the Esc button " \
                  "will activate the detected escape button (if any).")
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QMessageBox>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QMessageBoxdialog;
        QMessageBoxmsgBox(QMessageBox::Warning,QObject::tr("QMessageBox::warning()"),
                              MESSAGE, 0, &dialog);
       msgBox.addButton(QObject::tr("Save &Again"),QMessageBox::AcceptRole);
       msgBox.addButton(QObject::tr("&Continue"),QMessageBox::RejectRole);
           if (msgBox.exec() == QMessageBox::AcceptRole)
               qDebug()<<"Save Again";
           else
               qDebug()<<"Continue";
        returnapp.exec();
     }

    示例14:关于对话框
    #define MESSAGE \
       QObject::tr("<p>Message boxes have acaption, a text, " \
                  "and any number of buttons, each with standard or custom texts."\
                  "<p>Click a button to close themessage box. Pressing the Esc button " \
                  "will activate the detected escape button (if any).")
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QMessageBox>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QMessageBoxdialog;
       QMessageBox::about(&dialog,"liuhong",
               QObject::tr("This dialog shows and remembers error messages."
                      "If the checkbox is checked (as it is by default), "
                      "the shown message will be shown again, "
                      "but if the user unchecks the box the message "
                      "will not appear again if QErrorMessage::showMessage() "
                      "is called with the same message."));
        returnapp.exec();
     }

    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QMessageBox>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QMessageBoxdialog;
       QMessageBox::aboutQt(&dialog,"About Qt");
        returnapp.exec();
     }

    6、标准对话框之QErrorMessage
    示例15:错误对话框(取消选中项,则不会再显示。)
    #define MESSAGE \
       QObject::tr("<p>Message boxes have acaption, a text, " \
                  "and any number of buttons, each with standard or custom texts."\
                  "<p>Click a button to close themessage box. Pressing the Esc button " \
                  "will activate the detected escape button (if any).")
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QErrorMessage>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
       QErrorMessage *errorMessageDialog = new QErrorMessage;
       errorMessageDialog->showMessage(
               QObject::tr("This dialog shows and remembers error messages."
                      "If the checkbox is checked (as it is by default), "
                      "the shown message will be shown again, "
                      "but if the user unchecks the box the message "
                      "will not appear again if QErrorMessage::showMessage() "
                      "is called with the same message."));
        returnapp.exec();
     }

    7、标准对话框之QProgressDialog
    示例16:用对话框表示复制文件个数及其进度
    #include <QApplication>
    #include <QTextCodec>
    #include <QDebug>
    #include <QProgressDialog>
    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
       QProgressDialog dialog;
        intnumFiles=25;
       QProgressDialog progress("Copying files...", "Abort Copy", 0,numFiles, &dialog);
            progress.setWindowModality(Qt::WindowModal);

            for (int i = 0; i < numFiles; i++) {
                progress.setValue(i);

                if (progress.wasCanceled())
                    break;

                //... copy one file
            }
            progress.setValue(numFiles);
       progress.show();
        returnapp.exec();
     }
    8、标准对话框之QProgressDialog(页面设置对话框)
       这个对话框适用于文本设置,返回一些页面属性。这里 就不再赘述它是怎样使用的,他用的比较少。
    9、QPrintPreviewDialog和QAbstractPrintDialog
    这两个涉及QPrinter类,这里也不再赘述!
    10、标准对话框之QWizard(向导对话框)
    这里我们会在后面详细介绍,这里也就一笔带过!

    四、可扩展对话框
    暂时不能给出合适的写入代码方式,恕原谅!

    五、多页对话框
    多页对话框有两种形式,一种是通过QListWidget,QComboBox等可以改变值的控件来实现翻页;
    另一种则是单纯的标签页。
    ㈠我们先来看看第一种形式
    示例17:config程序
    【1】新建一个空工程,命名为config,向工程中添加main.cpp,pages.h,pages.cpp三个文件,接着添加一个类,类名config,Baseclass填QDialog,Type information处选择Inherits QObject。
    【2】向pages.h中添加代码后如下:
    #ifndef PAGES_H
    #define PAGES_H

    #include <QWidget>

    class ConfigurationPage : public QWidget
    {
    public:
       ConfigurationPage(QWidget *parent = 0);
    };

    class QueryPage : public QWidget
    {
    public:
       QueryPage(QWidget *parent = 0);
    };

    class UpdatePage : public QWidget
    {
    public:
       UpdatePage(QWidget *parent = 0);
    };

    #endif
    这里我们声明了三个窗口部件类,待会会用在
    【3】接着在pages.cpp中添加代码,添加代码后:
    #include <QtGui>

    #include "pages.h"

    ConfigurationPage::ConfigurationPage(QWidget *parent)
        :QWidget(parent)
    {
        QGroupBox*configGroup = new QGroupBox(tr("Server configuration"));

        QLabel*serverLabel = new QLabel(tr("Server:"));
        QComboBox*serverCombo = new QComboBox;
       serverCombo->addItem(tr("Qt (Australia)"));
       serverCombo->addItem(tr("Qt (Germany)"));
       serverCombo->addItem(tr("Qt (Norway)"));
       serverCombo->addItem(tr("Qt (People's Republic ofChina)"));
       serverCombo->addItem(tr("Qt (USA)"));

       QHBoxLayout *serverLayout = new QHBoxLayout;
       serverLayout->addWidget(serverLabel);
       serverLayout->addWidget(serverCombo);

       QVBoxLayout *configLayout = new QVBoxLayout;
       configLayout->addLayout(serverLayout);
       configGroup->setLayout(configLayout);

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(configGroup);
       mainLayout->addStretch(1);
       setLayout(mainLayout);
    }

    UpdatePage::UpdatePage(QWidget *parent)
        :QWidget(parent)
    {
        QGroupBox*updateGroup = new QGroupBox(tr("Package selection"));
        QCheckBox*systemCheckBox = new QCheckBox(tr("Update system"));
        QCheckBox*appsCheckBox = new QCheckBox(tr("Update applications"));
        QCheckBox*docsCheckBox = new QCheckBox(tr("Update documentation"));

        QGroupBox*packageGroup = new QGroupBox(tr("Existing packages"));

       QListWidget *packageList = new QListWidget;
       QListWidgetItem *qtItem = new QListWidgetItem(packageList);
       qtItem->setText(tr("Qt"));
       QListWidgetItem *qsaItem = new QListWidgetItem(packageList);
       qsaItem->setText(tr("QSA"));
       QListWidgetItem *teamBuilderItem = newQListWidgetItem(packageList);
       teamBuilderItem->setText(tr("Teambuilder"));

       QPushButton *startUpdateButton = new QPushButton(tr("Startupdate"));

       QVBoxLayout *updateLayout = new QVBoxLayout;
       updateLayout->addWidget(systemCheckBox);
       updateLayout->addWidget(appsCheckBox);
       updateLayout->addWidget(docsCheckBox);
       updateGroup->setLayout(updateLayout);

       QVBoxLayout *packageLayout = new QVBoxLayout;
       packageLayout->addWidget(packageList);
       packageGroup->setLayout(packageLayout);

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(updateGroup);
       mainLayout->addWidget(packageGroup);
       mainLayout->addSpacing(12);
       mainLayout->addWidget(startUpdateButton);
       mainLayout->addStretch(1);
       setLayout(mainLayout);
    }

    QueryPage::QueryPage(QWidget *parent)
        :QWidget(parent)
    {
        QGroupBox*packagesGroup = new QGroupBox(tr("Look for packages"));

        QLabel*nameLabel = new QLabel(tr("Name:"));
        QLineEdit*nameEdit = new QLineEdit;

        QLabel*dateLabel = new QLabel(tr("Released after:"));
       QDateTimeEdit *dateEdit = newQDateTimeEdit(QDate::currentDate());

        QCheckBox*releasesCheckBox = new QCheckBox(tr("Releases"));
        QCheckBox*upgradesCheckBox = new QCheckBox(tr("Upgrades"));

        QSpinBox*hitsSpinBox = new QSpinBox;
       hitsSpinBox->setPrefix(tr("Return up to "));
       hitsSpinBox->setSuffix(tr(" results"));
       hitsSpinBox->setSpecialValueText(tr("Return only thefirst result"));
       hitsSpinBox->setMinimum(1);
       hitsSpinBox->setMaximum(100);
       hitsSpinBox->setSingleStep(10);

       QPushButton *startQueryButton = new QPushButton(tr("Startquery"));

       QGridLayout *packagesLayout = new QGridLayout;
       packagesLayout->addWidget(nameLabel, 0, 0);
       packagesLayout->addWidget(nameEdit, 0, 1);
       packagesLayout->addWidget(dateLabel, 1, 0);
       packagesLayout->addWidget(dateEdit, 1, 1);
       packagesLayout->addWidget(releasesCheckBox, 2,0);
       packagesLayout->addWidget(upgradesCheckBox, 3,0);
       packagesLayout->addWidget(hitsSpinBox, 4, 0, 1,2);
       packagesGroup->setLayout(packagesLayout);

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(packagesGroup);
       mainLayout->addSpacing(12);
       mainLayout->addWidget(startQueryButton);
       mainLayout->addStretch(1);
       setLayout(mainLayout);
    }

    这里定义了这三个窗口部件。
    【4】我们在config的头文件中,添加公有槽函数
    void changePage(QListWidgetItem *current, QListWidgetItem*previous);
    添加“画图标”的私有函数
    void createIcons();
    声明一个列表窗口部件,一个多页窗口部件,均声明为私有成员变量。
        QListWidget*contentsWidget;
       QStackedWidget *pagesWidget;
    记得添加头文件和类声明:
    QT_BEGIN_NAMESPACE
    class QListWidget;
    class QListWidgetItem;
    class QStackedWidget;
    QT_END_NAMESPACE

    【5】我们在config的cpp文件中,添加构造函数代码:
       contentsWidget = new QListWidget;
       contentsWidget->setViewMode(QListView::IconMode);
       contentsWidget->setIconSize(QSize(96, 84));
       contentsWidget->setMovement(QListView::Static);
       contentsWidget->setMaximumWidth(128);
       contentsWidget->setSpacing(12);

       pagesWidget = new QStackedWidget;
       pagesWidget->addWidget(new ConfigurationPage);
       pagesWidget->addWidget(new UpdatePage);
       pagesWidget->addWidget(new QueryPage);

       QPushButton *closeButton = new QPushButton(tr("Close"));

       createIcons();
       contentsWidget->setCurrentRow(0);

       connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));

       QHBoxLayout *horizontalLayout = new QHBoxLayout;
       horizontalLayout->addWidget(contentsWidget);
       horizontalLayout->addWidget(pagesWidget, 1);

       QHBoxLayout *buttonsLayout = new QHBoxLayout;
       buttonsLayout->addStretch(1);
       buttonsLayout->addWidget(closeButton);

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addLayout(horizontalLayout);
       mainLayout->addStretch(1);
       mainLayout->addSpacing(12);
       mainLayout->addLayout(buttonsLayout);
       setLayout(mainLayout);

       setWindowTitle(tr("Config Dialog"));
    添加creatIcons函数代码:
    void config::createIcons()
    {
    QListWidgetItem *configButton = newQListWidgetItem(contentsWidget);
       configButton->setIcon(QIcon(":/images/config.png"));
       configButton->setText(tr("Configuration"));
       configButton->setTextAlignment(Qt::AlignHCenter);
       configButton->setFlags(Qt::ItemIsSelectable |Qt::ItemIsEnabled);

       QListWidgetItem *updateButton = newQListWidgetItem(contentsWidget);
       updateButton->setIcon(QIcon(":/images/update.png"));
       updateButton->setText(tr("Update"));
       updateButton->setTextAlignment(Qt::AlignHCenter);
       updateButton->setFlags(Qt::ItemIsSelectable |Qt::ItemIsEnabled);

       QListWidgetItem *queryButton = newQListWidgetItem(contentsWidget);
       queryButton->setIcon(QIcon(":/images/query.png"));
       queryButton->setText(tr("Query"));
       queryButton->setTextAlignment(Qt::AlignHCenter);
       queryButton->setFlags(Qt::ItemIsSelectable |Qt::ItemIsEnabled);

       connect(contentsWidget,
               SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
               this, SLOT(changePage(QListWidgetItem*,QListWidgetItem*)));
    }
    在定义完,三个QListWidgetItem项之后,我们要声明信号槽连接。

    添加槽函数代码后为:
    void config::changePage(QListWidgetItem *current, QListWidgetItem*previous)
    {
        if(!current)
           current = previous;

       pagesWidget->setCurrentIndex(contentsWidget->row(current));
    }
    【6】添加资源
    在工程文件夹下,新建images文件夹,向其中添加三个png图片文件:config.png,query.png,update.png。
    新建一个资源文件,命名为images,单击add组合框,选择Add Prefix,将Prefix项命名为“/”即可。
    再次单击add组合框,选择Add Files,添加图标文件。
    示例18:接下来,我们用一个简单的程序,实现同样的翻页。
    #include <QApplication>
    #include <QTextCodec>
    #include <QDialog>
    #include <QStackedWidget>
    #include <QWidget>
    #include <QVBoxLayout>
    #include <QComboBox>
    #include <QLabel>

    int main(int argc, char *argv[])
     {
       QApplication  app(argc, argv);
       QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
        QDialogdialog;

        QLabel*label1 = new QLabel(&dialog);
        QLabel*label2 = new QLabel(&dialog);
        QLabel*label3 = new QLabel(&dialog);

        QWidget *firstPageWidget = new QWidget;
        QWidget *secondPageWidget = new QWidget;
        QWidget *thirdPageWidget = new QWidget;

        label1->setText("page 1");
        label2->setText("page 2");
        label3->setText("page 3");

        QVBoxLayout *vboxlayout1 = new QVBoxLayout;
        QVBoxLayout *vboxlayout2 = new QVBoxLayout;
        QVBoxLayout *vboxlayout3 = new QVBoxLayout;

        vboxlayout1->addWidget(label1);
        vboxlayout2->addWidget(label2);
        vboxlayout3->addWidget(label3);

       firstPageWidget->setLayout(vboxlayout1);
       secondPageWidget->setLayout(vboxlayout2);
       thirdPageWidget->setLayout(vboxlayout3);

        QStackedWidget *stackedWidget = new QStackedWidget;
        stackedWidget->addWidget(firstPageWidget);
        stackedWidget->addWidget(secondPageWidget);
        stackedWidget->addWidget(thirdPageWidget);

        QComboBox *pageComboBox = new QComboBox;
        pageComboBox->addItem(QObject::tr("Page 1"));
        pageComboBox->addItem(QObject::tr("Page 2"));
        pageComboBox->addItem(QObject::tr("Page 3"));

        QObject::connect(pageComboBox, SIGNAL(activated(int)),
                     stackedWidget, SLOT(setCurrentIndex(int)));

        QVBoxLayout *layout = new QVBoxLayout;
        layout->addWidget(stackedWidget);
        layout->addStretch(1);
        layout->addWidget(pageComboBox);

        dialog.setLayout(layout);
        dialog.setWindowTitle(QObject::tr("示例18"));
        dialog.show();
        return app.exec();
      }
    这里我们要养成一个好的习惯,在窗口部件定义之后,立即给出它的信号槽连接。
    这里我们用到了三个QLabel和三个QComboBox。通过改变QComboBox的值改变页码。
    ㈡tab标签页

    tab标签页,就像计算机"系统属性"对话框一样,有五个标签,每个标签页又是单独的窗口部件。(“计算机”“硬件”“高级”“系统保护”“远程”五个标签页)

    我们先来看看,Qt Demo 给出的这个例子:
    通过这个例子,我们还可以学习一个类:QFileInfo类
    示例19:文件属性
    【1】新建一个空工程,命名为tabdialog,添加一个mian.cpp文件,添加一个类,命名为TabDialog,Baseclass填QDialog,Type information处选择Inherits QWidget。
    【2】在tabdialog.h文件中:
    添加三个类声明:
    class GeneralTab : public QWidget
    {
        Q_OBJECT

    public:
       GeneralTab(const QFileInfo &fileInfo, QWidget*parent = 0);
    };

    class PermissionsTab : public QWidget
    {
        Q_OBJECT

    public:
       PermissionsTab(const QFileInfo &fileInfo, QWidget*parent = 0);
    };


    class ApplicationsTab : public QWidget
    {
        Q_OBJECT

    public:
       ApplicationsTab(const QFileInfo &fileInfo, QWidget*parent = 0);
    };

    接着添加构造函数:
        explicitTabDialog(const QString &fileName , QWidget *parent= 0);
    最后添加两个私有变量:
        QTabWidget*tabWidget;
       QDialogButtonBox *buttonBox;
    记得添加在头文件处类声明:
    QT_BEGIN_NAMESPACE
    class QDialogButtonBox;
    class QFileInfo;
    class QTabWidget;
    QT_END_NAMESPACE
    【3】添加三个标签页窗口部件的定义部分:
    GeneralTab::GeneralTab(const QFileInfo &fileInfo,QWidget *parent)
        :QWidget(parent)
    {
        QLabel*fileNameLabel = new QLabel(tr("File Name:"));
        QLineEdit*fileNameEdit = new QLineEdit(fileInfo.fileName());

        QLabel*pathLabel = new QLabel(tr("Path:"));
        QLabel*pathValueLabel = new QLabel(fileInfo.absoluteFilePath());
       pathValueLabel->setFrameStyle(QFrame::Panel |QFrame::Sunken);

        QLabel*sizeLabel = new QLabel(tr("Size:"));
        qlonglongsize = fileInfo.size()/1024;
        QLabel*sizeValueLabel = new QLabel(tr("%1 K").arg(size));
       sizeValueLabel->setFrameStyle(QFrame::Panel |QFrame::Sunken);

        QLabel*lastReadLabel = new QLabel(tr("Last Read:"));
        QLabel*lastReadValueLabel = newQLabel(fileInfo.lastRead().toString());
       lastReadValueLabel->setFrameStyle(QFrame::Panel |QFrame::Sunken);

        QLabel*lastModLabel = new QLabel(tr("Last Modified:"));
        QLabel*lastModValueLabel = newQLabel(fileInfo.lastModified().toString());
       lastModValueLabel->setFrameStyle(QFrame::Panel |QFrame::Sunken);

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(fileNameLabel);
       mainLayout->addWidget(fileNameEdit);
       mainLayout->addWidget(pathLabel);
       mainLayout->addWidget(pathValueLabel);
       mainLayout->addWidget(sizeLabel);
       mainLayout->addWidget(sizeValueLabel);
       mainLayout->addWidget(lastReadLabel);
       mainLayout->addWidget(lastReadValueLabel);
       mainLayout->addWidget(lastModLabel);
       mainLayout->addWidget(lastModValueLabel);
       mainLayout->addStretch(1);
       setLayout(mainLayout);
    }

    PermissionsTab::PermissionsTab(const QFileInfo&fileInfo, QWidget *parent)
        :QWidget(parent)
    {
        QGroupBox*permissionsGroup = new QGroupBox(tr("Permissions"));

        QCheckBox*readable = new QCheckBox(tr("Readable"));
        if(fileInfo.isReadable())
           readable->setChecked(true);

        QCheckBox*writable = new QCheckBox(tr("Writable"));
        if (fileInfo.isWritable() )
           writable->setChecked(true);

        QCheckBox*executable = new QCheckBox(tr("Executable"));
        if (fileInfo.isExecutable() )
           executable->setChecked(true);

        QGroupBox*ownerGroup = new QGroupBox(tr("Ownership"));

        QLabel*ownerLabel = new QLabel(tr("Owner"));
        QLabel*ownerValueLabel = new QLabel(fileInfo.owner());
       ownerValueLabel->setFrameStyle(QFrame::Panel |QFrame::Sunken);

        QLabel*groupLabel = new QLabel(tr("Group"));
        QLabel*groupValueLabel = new QLabel(fileInfo.group());
       groupValueLabel->setFrameStyle(QFrame::Panel |QFrame::Sunken);

       QVBoxLayout *permissionsLayout = new QVBoxLayout;
       permissionsLayout->addWidget(readable);
       permissionsLayout->addWidget(writable);
       permissionsLayout->addWidget(executable);
       permissionsGroup->setLayout(permissionsLayout);

       QVBoxLayout *ownerLayout = new QVBoxLayout;
       ownerLayout->addWidget(ownerLabel);
       ownerLayout->addWidget(ownerValueLabel);
       ownerLayout->addWidget(groupLabel);
       ownerLayout->addWidget(groupValueLabel);
       ownerGroup->setLayout(ownerLayout);

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(permissionsGroup);
       mainLayout->addWidget(ownerGroup);
       mainLayout->addStretch(1);
       setLayout(mainLayout);
    }

    ApplicationsTab::ApplicationsTab(const QFileInfo&fileInfo, QWidget *parent)
        :QWidget(parent)
    {
        QLabel*topLabel = new QLabel(tr("Open with:"));

       QListWidget *applicationsListBox = new QListWidget;
        QStringListapplications;

        for (inti = 1; i <= 30; ++i)
           applications.append(tr("Application %1").arg(i));
       applicationsListBox->insertItems(0,applications);

        QCheckBox*alwaysCheckBox;

        if(fileInfo.suffix().isEmpty())
           alwaysCheckBox = new QCheckBox(tr("Always use this application to"
               "open this type of file"));
        else
           alwaysCheckBox = new QCheckBox(tr("Always use this application to"
               "open files with the extension '%1'").arg(fileInfo.suffix()));

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(topLabel);
       layout->addWidget(applicationsListBox);
       layout->addWidget(alwaysCheckBox);
       setLayout(layout);
    }
    【4】添加构造函数代码:
        QFileInfofileInfo(fileName);

        tabWidget= new QTabWidget;
       tabWidget->addTab(new GeneralTab(fileInfo),tr("General"));
       tabWidget->addTab(new PermissionsTab(fileInfo),tr("Permissions"));
       tabWidget->addTab(new ApplicationsTab(fileInfo),tr("Applications"));

        buttonBox= new QDialogButtonBox(QDialogButtonBox::Ok |QDialogButtonBox::Cancel);
       connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
       connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(tabWidget);
       mainLayout->addWidget(buttonBox);
       setLayout(mainLayout);

       setWindowTitle(tr("Tab Dialog"));

    记得添加头文件:
    #include <QtGui>
    或者一些详细的类清单。

    【5】写入main函数到mian.cpp文件中:
    #include <QApplication>

    #include "tabdialog.h"

    int main(int argc, char *argv[])
    {
        QApplicationapp(argc, argv);
        QStringfileName;

        if (argc>= 2)
           fileName = argv[1];
        else
           fileName = ".";

        TabDialogtabdialog(fileName);
        returntabdialog.exec();
    }

    示例20:
    我们用一个单独的小程序来研究一下,tab标签页。
    #include <QApplication>

    #include <QTableWidget>
    #include <QDialog>
    #include <QLabel>
    #include <QVBoxLayout>
    #include <QDialogButtonBox>
    #include <QWidget>

    int main(int argc, char *argv[])
    {
        QApplicationapp(argc, argv);

        QDialogtabdialog;

        QLabel*label1 = new QLabel(&tabdialog);
        QLabel*label2 = new QLabel(&tabdialog);
        QLabel*label3 = new QLabel(&tabdialog);

        QWidget*firstTabWidget = new QWidget;
        QWidget*secondTabWidget = new QWidget;
        QWidget*thirdTabWidget = new QWidget;

        label1->setText("page 1");
        label2->setText("page 2");
        label3->setText("page 3");

        QVBoxLayout *vboxlayout1 = new QVBoxLayout;
        QVBoxLayout *vboxlayout2 = new QVBoxLayout;
        QVBoxLayout *vboxlayout3 = new QVBoxLayout;

        vboxlayout1->addWidget(label1);
        vboxlayout2->addWidget(label2);
        vboxlayout3->addWidget(label3);

        firstTabWidget->setLayout(vboxlayout1);
        secondTabWidget->setLayout(vboxlayout2);
        thirdTabWidget->setLayout(vboxlayout3);


        QTabWidget*tabWidget = new QTabWidget;
       tabWidget->addTab(firstTabWidget,QObject::tr("General"));
       tabWidget->addTab(secondTabWidget,QObject::tr("Permissions"));
       tabWidget->addTab(thirdTabWidget,QObject::tr("Applications"));
       //tabWidget->setTabPosition(QTabWidget::West);
       tabWidget->setTabShape(QTabWidget::Triangular);

       QDialogButtonBox *buttonBox = newQDialogButtonBox(QDialogButtonBox::Ok|    QDialogButtonBox::Cancel);
       QObject::connect(buttonBox, SIGNAL(accepted()),&tabdialog, SLOT(accept()));
       QObject::connect(buttonBox, SIGNAL(rejected()),&tabdialog, SLOT(reject()));

     

       QVBoxLayout *mainLayout = new QVBoxLayout;
       mainLayout->addWidget(tabWidget);
       mainLayout->addWidget(buttonBox);
       tabdialog.setLayout(mainLayout);

       tabdialog.setWindowTitle(QObject::tr("Tab Dialog"));
       tabdialog.setCursor(Qt::PointingHandCursor);

        returntabdialog.exec();
    }

    至此我们学习了两个多页窗口部件,每一个我都给出了两个示例,以表示我很重视。
    一个QStackedWidget类,一个QTabWidget类,使我们学习的重点,以后设计程序会经常用到这两个。

    六、find对话框
    暂不能给出代码,恕原谅!

    七、QWizard(向导对话框)
    ㈠QWizard类
    1、分类
    线性向导对话框(The Linear Wizard)
    复杂向导对话框(The Non-Linear Wizard)
    2、向导框风格(WizardStyle)
    一共四种风格:ClassicStyle, ModernStyle, MacStyle, AeroStyle;
    3、每个WizardPage或Wizard都有的三个属性
    A title.标题
    A subTitle.副标题
    A set of pixmaps, which may or may not be honored, depending on thewizard's style:
     WatermarkPixmap (used by ClassicStyle andModernStyle)(水印)
     BannerPixmap (used by ModernStyle)(横幅)
     LogoPixmap (used by ClassicStyle andModernStyle)(徽标)
     BackgroundPixmap (used by MacStyle)(背景)
    我们可以看出ModernStyle的图标最多!
    ClassicStyle的图标次之;
    MacStyle的图标再次之;
    AeroStyle则没有图标。
    这些图标的详细位置,请参见Qt Help。

    Window 7缺省值(Default)为AeroStyle。
    4、对话框风格
    Constant Value Description
    QWizard::IndependentPages 0x00000001 Thepages are independent of each other (i.e., they don't derive valuesfrom each other).
    QWizard::IgnoreSubTitles 0x00000002 Don'tshow any subtitles, even if they are set.
    QWizard::ExtendedWatermarkPixmap 0x00000004 Extendany WatermarkPixmap all the way down to the window's edge.
    QWizard::NoDefaultButton 0x00000008 Don'tmake the Next or Finish button the dialog's default button.
    QWizard::NoBackButtonOnStartPage 0x00000010 Don'tshow the Back button on the start page.
    QWizard::NoBackButtonOnLastPage 0x00000020 Don'tshow the Back button on the last page.
    QWizard::DisabledBackButtonOnLastPage 0x00000040 Disablethe Back button on the last page.
    QWizard::HaveNextButtonOnLastPage 0x00000080 Showthe (disabled) Next button on the last page.
    QWizard::HaveFinishButtonOnEarlyPages 0x00000100 Showthe (disabled) Finish button on non-final pages.
    QWizard::NoCancelButton 0x00000200 Don'tshow the Cancel button.
    QWizard::CancelButtonOnLeft 0x00000400 Putthe Cancel button on the left of Back (rather than on the right ofFinish or Next).
    QWizard::HaveHelpButton 0x00000800 Showthe Help button.
    QWizard::HelpButtonOnRight 0x00001000 Putthe Help button on the far right of the button layout (rather thanon the far left).
    QWizard::HaveCustomButton1 0x00002000 Showthe first user-defined button (CustomButton1).
    QWizard::HaveCustomButton2 0x00004000 Showthe second user-defined button (CustomButton2).
    QWizard::HaveCustomButton3 0x00008000 Showthe third user-defined button (CustomButton3).
    一共十六个除缺省值以外的对话框风格。
    ㈡简单例子
    示例21: a  trivial  wizard
    #include <QtGui>
    #include <QTranslator>
    #include <QLocale>
    #include <QLibraryInfo>

    QWizardPage *createIntroPage()
    {
        QWizardPage*page = new QWizardPage;
       page->setTitle("Introduction");

        QLabel*label = new QLabel("This wizard will help you register your copy"
                                  "of Super Product Two.");
       label->setWordWrap(true);

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(label);
       page->setLayout(layout);

        returnpage;
    }

    QWizardPage *createRegistrationPage()
    {
        QWizardPage*page = new QWizardPage;
       page->setTitle("Registration");
       page->setSubTitle("Please fill both fields.");

        QLabel*nameLabel = new QLabel("Name:");
        QLineEdit*nameLineEdit = new QLineEdit;

        QLabel*emailLabel = new QLabel("Email address:");
        QLineEdit*emailLineEdit = new QLineEdit;

       QGridLayout *layout = new QGridLayout;
       layout->addWidget(nameLabel, 0, 0);
       layout->addWidget(nameLineEdit, 0, 1);
       layout->addWidget(emailLabel, 1, 0);
       layout->addWidget(emailLineEdit, 1, 1);
       page->setLayout(layout);

        returnpage;
    }

    QWizardPage *createConclusionPage()
    {

       QWizardPage *page = new QWizardPage;
       page->setTitle("Conclusion");

        QLabel*label = new QLabel("You are now successfully registered. Have a"
                                  "nice day!");
       label->setWordWrap(true);

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(label);
       page->setLayout(layout);

        returnpage;
    }

    int main(int argc, char *argv[])
    {
        QApplicationapp(argc, argv);

        QStringtranslatorFileName = QLatin1String("qt_");
       translatorFileName += QLocale::system().name();
        QTranslator*translator = new QTranslator(&app);
        if(translator->load(translatorFileName,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
           app.installTranslator(translator);


        QWizardwizard;
       wizard.addPage(createIntroPage());
       wizard.addPage(createRegistrationPage());
       wizard.addPage(createConclusionPage());

       wizard.setWindowTitle("Trivial Wizard");
       wizard.show();

        returnapp.exec();
    }
    ㈢创建线性向导对话框(The Linear Wizard)
    示例22:Class Wizard
    本示例是生成一个类,并产生对应的头文件和CPP文件。
    【1】创建一个空工程,添加main.cpp文件,添加一个类ClassWizard,基类QWizard,构造函数内容选QWidget。
    【2】在classwizard.h文件中,添加代码:
    添加私有函数:
    void accept();
    添加四个QWizerdPage类:
    class ClassInfoPage : public QWizardPage
    {
        Q_OBJECT

    public:
       ClassInfoPage(QWidget *parent = 0);

    private:
        QLabel*classNameLabel;
        QLabel*baseClassLabel;
        QLineEdit*classNameLineEdit;
        QLineEdit*baseClassLineEdit;
        QCheckBox*qobjectMacroCheckBox;
        QGroupBox*groupBox;
        QRadioButton*qobjectCtorRadioButton;
        QRadioButton*qwidgetCtorRadioButton;
        QRadioButton*defaultCtorRadioButton;
        QCheckBox*copyCtorCheckBox;
    };

    class CodeStylePage : public QWizardPage
    {
        Q_OBJECT

    public:
       CodeStylePage(QWidget *parent = 0);

    protected:
        voidinitializePage();

    private:
        QCheckBox*commentCheckBox;
        QCheckBox*protectCheckBox;
        QCheckBox*includeBaseCheckBox;
        QLabel*macroNameLabel;
        QLabel*baseIncludeLabel;
        QLineEdit*macroNameLineEdit;
        QLineEdit*baseIncludeLineEdit;
    };


    class OutputFilesPage : public QWizardPage
    {
        Q_OBJECT

    public:
       OutputFilesPage(QWidget *parent = 0);

    protected:
        voidinitializePage();

    private:
        QLabel*outputDirLabel;
        QLabel*headerLabel;
        QLabel*implementationLabel;
        QLineEdit*outputDirLineEdit;
        QLineEdit*headerLineEdit;
        QLineEdit*implementationLineEdit;
    };

    class ConclusionPage : public QWizardPage
    {
        Q_OBJECT

    public:
       ConclusionPage(QWidget *parent = 0);

    protected:
        voidinitializePage();

    private:
        QLabel*label;
    };

    #endif // CLASSWIZARD_H

    【3】在classwizard.cpp文件中添加代码:
    添加构造函数代码:
        addPage(newIntroPage);
        addPage(newClassInfoPage);
        addPage(newCodeStylePage);
        addPage(newOutputFilesPage);
        addPage(newConclusionPage);

       setPixmap(QWizard::BannerPixmap,QPixmap(":/images/banner.png"));
       //setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/background.png"));
       //setWizardStyle(QWizard::ModernStyle);
       setWizardStyle(QWizard::ClassicStyle);
       setWindowTitle(tr("Class Wizard"));
    添加私有函数void accept();代码后:
    void ClassWizard::accept()
    {
        QByteArrayclassName = field("className").toByteArray();
        QByteArraybaseClass = field("baseClass").toByteArray();
        QByteArraymacroName = field("macroName").toByteArray();
        QByteArraybaseInclude = field("baseInclude").toByteArray();

        QStringoutputDir = field("outputDir").toString();
        QStringheader = field("header").toString();
        QStringimplementation = field("implementation").toString();


        QByteArrayblock;

        if(field("comment").toBool()) {
           block += "\n";
           block += "\n";
        }
        if(field("protect").toBool()) {
           block += "#ifndef " + macroName + "\n";
           block += "#define " + macroName + "\n";
           block += "\n";
        }
        if(field("includeBase").toBool()) {
           block += "#include " + baseInclude + "\n";
           block += "\n";
        }

        block +="class " + className;
        if(!baseClass.isEmpty())
           block += " : public " + baseClass;
        block +="\n";
        block +="{\n";

       

        if(field("qobjectMacro").toBool()) {
           block += "   Q_OBJECT\n";
           block += "\n";
        }
        block +="public:\n";

        if(field("qobjectCtor").toBool()) {
           block += "    "+ className + "(QObject *parent = 0);\n";
        } else if(field("qwidgetCtor").toBool()) {
           block += "    "+ className + "(QWidget *parent = 0);\n";
        } else if(field("defaultCtor").toBool()) {
           block += "    "+ className + "();\n";
           if (field("copyCtor").toBool()) {
               block += "    "+ className + "(const " + className + "&other);\n";
               block += "\n";
               block += "    "+ className + " &operator=" + "(const " +className
                        + " &other);\n";
           }
        }
        block +="};\n";

        if(field("protect").toBool()) {
           block += "\n";
           block += "#endif\n";
        }

        QFileheaderFile(outputDir + "/" + header);
        if(!headerFile.open(QFile::WriteOnly | QFile::Text)) {
           QMessageBox::warning(0, QObject::tr("Simple Wizard"),
                                QObject::tr("Cannot write file %1:\n%2")
                                .arg(headerFile.fileName())
                                .arg(headerFile.errorString()));
           return;
        }
       headerFile.write(block);

       block.clear();

        if(field("comment").toBool()) {
           block += "\n";
           block += "\n";
        }
        block +="#include "" + header.toAscii() + ""\n";
        block +="\n";

        if(field("qobjectCtor").toBool()) {
           block += className + "::" + className + "(QObject*parent)\n";
           block += "    :" + baseClass + "(parent)\n";
           block += "{\n";
           block += "}\n";
        } else if(field("qwidgetCtor").toBool()) {
           block += className + "::" + className + "(QWidget*parent)\n";
           block += "    :" + baseClass + "(parent)\n";
           block += "{\n";
           block += "}\n";
        } else if(field("defaultCtor").toBool()) {
           block += className + "::" + className + "()\n";
           block += "{\n";
           block += "    //missing code\n";
           block += "}\n";

           if (field("copyCtor").toBool()) {
               block += "\n";
               block += className + "::" + className + "(const " + className
                        + " &other)\n";
               block += "{\n";
               block += "   *this = other;\n";
               block += "}\n";
               block += "\n";
               block += className + " &" + className +"::operator=(const "
                        + className + " &other)\n";
               block += "{\n";
               if (!baseClass.isEmpty())
                   block += "    "+ baseClass + "::operator=(other);\n";
               block += "    //missing code\n";
               block += "   return *this;\n";
               block += "}\n";
           }
        }

        QFileimplementationFile(outputDir + "/" + implementation);
        if(!implementationFile.open(QFile::WriteOnly | QFile::Text)) {
           QMessageBox::warning(0, QObject::tr("Simple Wizard"),
                                QObject::tr("Cannot write file %1:\n%2")
                                .arg(implementationFile.fileName())
                                .arg(implementationFile.errorString()));
           return;
        }
       implementationFile.write(block);


       QDialog::accept();

    }

    这个函数就是读取数据,写入数据到文件中。
    添加四个类的先关函数代码:
    IntroPage::IntroPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Introduction"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/background.png"));;

        label =new QLabel(tr("This wizard will generate a skeleton C++ class"
                             "definition, including a few functions. You simply "
                             "need to specify the class name and set a few "
                             "options to produce a header file and an "
                             "implementation file for your new C++ class."));
       label->setWordWrap(true);

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(label);
       setLayout(layout);
    }

    ClassInfoPage::ClassInfoPage(QWidget *parent)
        :QWizardPage(parent)
    {

       setTitle(tr("Class Information"));
       setSubTitle(tr("Specify basic information about the class for whichyou "
                      "want to generate skeleton source code files."));
       setPixmap(QWizard::LogoPixmap,QPixmap(":/images/logo1.png"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/watermark1.png"));

       classNameLabel = new QLabel(tr("&Classname:"));
       classNameLineEdit = new QLineEdit;
       classNameLabel->setBuddy(classNameLineEdit);

       baseClassLabel = new QLabel(tr("B&aseclass:"));
       baseClassLineEdit = new QLineEdit;
       baseClassLabel->setBuddy(baseClassLineEdit);

       qobjectMacroCheckBox = new QCheckBox(tr("Generate Q_OBJECT&macro"));


        groupBox =new QGroupBox(tr("C&onstructor"));


       qobjectCtorRadioButton = newQRadioButton(tr("&QObject-styleconstructor"));
       qwidgetCtorRadioButton = newQRadioButton(tr("Q&Widget-styleconstructor"));
       defaultCtorRadioButton = newQRadioButton(tr("&Default constructor"));
       copyCtorCheckBox = new QCheckBox(tr("&Generate copyconstructor and "
                                           "operator="));

       defaultCtorRadioButton->setChecked(true);

       connect(defaultCtorRadioButton, SIGNAL(toggled(bool)),
               copyCtorCheckBox, SLOT(setEnabled(bool)));

       registerField("className*", classNameLineEdit);
       registerField("baseClass", baseClassLineEdit);
       registerField("qobjectMacro", qobjectMacroCheckBox);

       registerField("qobjectCtor", qobjectCtorRadioButton);
       registerField("qwidgetCtor", qwidgetCtorRadioButton);
       registerField("defaultCtor", defaultCtorRadioButton);
       registerField("copyCtor", copyCtorCheckBox);

       QVBoxLayout *groupBoxLayout = new QVBoxLayout;

       groupBoxLayout->addWidget(qobjectCtorRadioButton);
       groupBoxLayout->addWidget(qwidgetCtorRadioButton);
       groupBoxLayout->addWidget(defaultCtorRadioButton);
       groupBoxLayout->addWidget(copyCtorCheckBox);
       groupBox->setLayout(groupBoxLayout);

       QGridLayout *layout = new QGridLayout;
       layout->addWidget(classNameLabel, 0, 0);
       layout->addWidget(classNameLineEdit, 0, 1);
       layout->addWidget(baseClassLabel, 1, 0);
       layout->addWidget(baseClassLineEdit, 1, 1);
       layout->addWidget(qobjectMacroCheckBox, 2, 0, 1,2);
       layout->addWidget(groupBox, 3, 0, 1, 2);
       setLayout(layout);

    }

    CodeStylePage::CodeStylePage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Code Style Options"));
       setSubTitle(tr("Choose the formatting of the generatedcode."));
       setPixmap(QWizard::LogoPixmap,QPixmap(":/images/logo2.png"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/watermark1.png"));
       commentCheckBox = new QCheckBox(tr("&Startgenerated files with a "

                                          "comment"));
       commentCheckBox->setChecked(true);

       protectCheckBox = new QCheckBox(tr("&Protect headerfile against multiple "
                                          "inclusions"));
       protectCheckBox->setChecked(true);

       macroNameLabel = new QLabel(tr("&Macroname:"));
       macroNameLineEdit = new QLineEdit;
       macroNameLabel->setBuddy(macroNameLineEdit);

       includeBaseCheckBox = new QCheckBox(tr("&Includebase class definition"));
       baseIncludeLabel = new QLabel(tr("Base class include:"));
       baseIncludeLineEdit = new QLineEdit;
       baseIncludeLabel->setBuddy(baseIncludeLineEdit);

       connect(protectCheckBox, SIGNAL(toggled(bool)),
               macroNameLabel, SLOT(setEnabled(bool)));
       connect(protectCheckBox, SIGNAL(toggled(bool)),
               macroNameLineEdit, SLOT(setEnabled(bool)));
       connect(includeBaseCheckBox, SIGNAL(toggled(bool)),
               baseIncludeLabel, SLOT(setEnabled(bool)));
       connect(includeBaseCheckBox, SIGNAL(toggled(bool)),
               baseIncludeLineEdit, SLOT(setEnabled(bool)));

       registerField("comment", commentCheckBox);
       registerField("protect", protectCheckBox);
       registerField("macroName", macroNameLineEdit);
       registerField("includeBase", includeBaseCheckBox);
       registerField("baseInclude", baseIncludeLineEdit);

       QGridLayout *layout = new QGridLayout;
       layout->setColumnMinimumWidth(0, 20);
       layout->addWidget(commentCheckBox, 0, 0, 1,3);
       layout->addWidget(protectCheckBox, 1, 0, 1,3);
       layout->addWidget(macroNameLabel, 2, 1);
       layout->addWidget(macroNameLineEdit, 2, 2);
       layout->addWidget(includeBaseCheckBox, 3, 0, 1,3);
       layout->addWidget(baseIncludeLabel, 4, 1);
       layout->addWidget(baseIncludeLineEdit, 4, 2);

       setLayout(layout);
    }

     

    void CodeStylePage::initializePage()
    {
        QStringclassName = field("className").toString();
       macroNameLineEdit->setText(className.toUpper() +"_H");

        QStringbaseClass = field("baseClass").toString();

       includeBaseCheckBox->setChecked(!baseClass.isEmpty());
       includeBaseCheckBox->setEnabled(!baseClass.isEmpty());
       baseIncludeLabel->setEnabled(!baseClass.isEmpty());
       baseIncludeLineEdit->setEnabled(!baseClass.isEmpty());

        if(baseClass.isEmpty()) {
           baseIncludeLineEdit->clear();
        } else if(QRegExp("Q[A-Z].*").exactMatch(baseClass)) {
           baseIncludeLineEdit->setText("<" +baseClass + ">");
        } else{
           baseIncludeLineEdit->setText(""" +baseClass.toLower() + ".h"");
        }
    }


    OutputFilesPage::OutputFilesPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Output Files"));
       setSubTitle(tr("Specify where you want the wizard to put thegenerated "
                      "skeleton code."));
       setPixmap(QWizard::LogoPixmap,QPixmap(":/images/logo3.png"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/watermark1.png"));
       outputDirLabel = new QLabel(tr("&Outputdirectory:"));
       outputDirLineEdit = new QLineEdit;
       outputDirLabel->setBuddy(outputDirLineEdit);

       headerLabel = new QLabel(tr("&Header filename:"));
       headerLineEdit = new QLineEdit;
       headerLabel->setBuddy(headerLineEdit);

       implementationLabel = newQLabel(tr("&Implementation file name:"));
       implementationLineEdit = new QLineEdit;
       implementationLabel->setBuddy(implementationLineEdit);

       registerField("outputDir*", outputDirLineEdit);
       registerField("header*", headerLineEdit);
       registerField("implementation*", implementationLineEdit);

       QGridLayout *layout = new QGridLayout;
       layout->addWidget(outputDirLabel, 0, 0);
       layout->addWidget(outputDirLineEdit, 0, 1);
       layout->addWidget(headerLabel, 1, 0);
       layout->addWidget(headerLineEdit, 1, 1);
       layout->addWidget(implementationLabel, 2, 0);
       layout->addWidget(implementationLineEdit, 2,1);
       setLayout(layout);
    }


    void OutputFilesPage::initializePage()
    {
        QStringclassName = field("className").toString();
       headerLineEdit->setText(className.toLower() +".h");
       implementationLineEdit->setText(className.toLower()+ ".cpp");
       outputDirLineEdit->setText(QDir::convertSeparators(QDir::tempPath()));
    }


    ConclusionPage::ConclusionPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Conclusion"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/watermark2.png"));

        label =new QLabel;
       label->setWordWrap(true);

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(label);
       setLayout(layout);
    }

    void ConclusionPage::initializePage()
    {
        QStringfinishText =wizard()->buttonText(QWizard::FinishButton);
       finishText.remove('&');
       label->setText(tr("Click %1 to generate the classskeleton.")
                      .arg(finishText));
    }
    这里用到一个非常有用的函数:
    void QWizardPage::registerField ( const QString &name, QWidget * widget, const char * property = 0, const char *changedSignal = 0 ) [protected]
    各参数限制:
    Widget  Property  ChangeNotification Signal
    QAbstractButton boolchecked toggled()
    QAbstractSlider intvalue  valueChanged()
    QComboBox intcurrentIndex currentIndexChanged()
    QDateTimeEdit QDateTimedateTime dateTimeChanged()
    QLineEdit  QStringtext textChanged()
    QListWidget intcurrentRow currentRowChanged()
    QSpinBox  intvalue  valueChanged()
    通过这个函数注册字段,可以在后面的QWizardPage中用到!
    【4】添加资源,命名为images,单击add选中add Prefix,prefix重命名为"",单击add选中addFile,选中我们之前放到文件中的图形文件。
    这样就OK了!
    ㈣创建复杂向导对话框(The Non-Linear Wizard)
    这里我们提前讲一下:
    复杂对话框,使用一个IDs,这个IDs通过一个枚举类型,进行了定义;
    例如:
    class LicenseWizard : public QWizard
     {
        ...
        enum { Page_Intro, Page_Evaluate, Page_Register,Page_Details,
               Page_Conclusion };
        ...
     };
    这里我们用setPagesetPage(int ID,QWizardPage *page);函数来注册QWizardPage;
    例如:
    LicenseWizard::LicenseWizard(QWidget *parent)
        : QWizard(parent)
     {
        setPage(Page_Intro, new IntroPage);
        setPage(Page_Evaluate, new EvaluatePage);
        setPage(Page_Register, new RegisterPage);
        setPage(Page_Details, new DetailsPage);
        setPage(Page_Conclusion, new ConclusionPage);
        ...
     }
    再用QWizardPage::nextId()函数,进行设置后继QWizardPage;
    例如:
    int IntroPage::nextId() const
     {
        if (evaluateRadioButton->isChecked()) {
            return LicenseWizard::Page_Evaluate;
        } else {
            return LicenseWizard::Page_Register;
        }
     }

     int EvaluatePage::nextId() const
     {
        return LicenseWizard::Page_Conclusion;
     }

     int RegisterPage::nextId() const
     {
        if (upgradeKeyLineEdit->text().isEmpty()) {
            return LicenseWizard::Page_Details;
        } else {
            return LicenseWizard::Page_Conclusion;
        }
     }

     int DetailsPage::nextId() const
     {
        return LicenseWizard::Page_Conclusion;
     }

     int ConclusionPage::nextId() const
     {
        return -1;
     }
    设置后继QWizardPage也可以直接在QWizard类中定义;
    例如:
    int LicenseWizard::nextId() const
     {
        switch (currentId()) {
        case Page_Intro:
            if (field("intro.evaluate").toBool()) {
                return Page_Evaluate;
            } else {
                return Page_Register;
            }
        case Page_Evaluate:
            return Page_Conclusion;
        case Page_Register:
            if (field("register.upgradeKey").toString().isEmpty()) {
                return Page_Details;
            } else {
                return Page_Conclusion;
            }
        case Page_Details:
            return Page_Conclusion;
        case Page_Conclusion:
        default:
            return -1;
        }
     }
    有时文本内容,需要根据被访问对话框的不同来设置文本。
    例如:
    void ConclusionPage::initializePage()
     {
        QString licenseText;

        if(wizard()->hasVisitedPage(LicenseWizard::Page_Evaluate)){
            licenseText = tr("<u>EvaluationLicense Agreement:</u> "
                             "You can use this software for 30 days and make one "
                             "backup, but you are not allowed to distribute it.");
        } else if(wizard()->hasVisitedPage(LicenseWizard::Page_Details)){
            licenseText = tr("<u>First-TimeLicense Agreement:</u> "
                             "You can use this software subject to the license "
                             "you will receive by email.");
        } else {
            licenseText = tr("<u>Upgrade LicenseAgreement:</u> "
                             "This software is licensed under the terms of your "
                             "current license.");
        }
        bottomLabel->setText(licenseText);
     }

    好了,啰嗦这么多,接下来,我们来看看示例吧!
    示例23:a license wizard
    【1】创建一个空工程,添加main.cpp文件,添加一个类LicenseWizard,基类QWizard,构造函数内容选QWidget。
    【2】在licensewizard.h文件中,添加代码:
    添加公有成员变量:
     enum { Page_Intro, Page_Evaluate, Page_Register,Page_Details,
              Page_Conclusion };
    添加私有槽函数:
    void showHelp();

    添加五个QWizardPage类:
    class IntroPage : public QWizardPage
    {
        Q_OBJECT

    public:
       IntroPage(QWidget *parent = 0);

        intnextId() const;

    private:
        QLabel*topLabel;
        QRadioButton*registerRadioButton;
        QRadioButton*evaluateRadioButton;
    };

     

    class EvaluatePage : public QWizardPage
    {
        Q_OBJECT

    public:
       EvaluatePage(QWidget *parent = 0);

        intnextId() const;

    private:
        QLabel*nameLabel;
        QLabel*emailLabel;
        QLineEdit*nameLineEdit;
        QLineEdit*emailLineEdit;
    };
    

    class RegisterPage : public QWizardPage
    {
        Q_OBJECT

    public:
       RegisterPage(QWidget *parent = 0);

        intnextId() const;

    private:
        QLabel*nameLabel;
        QLabel*upgradeKeyLabel;
        QLineEdit*nameLineEdit;
        QLineEdit*upgradeKeyLineEdit;
    };

    class DetailsPage : public QWizardPage
    {
        Q_OBJECT

    public:
       DetailsPage(QWidget *parent = 0);

        intnextId() const;

    private:
        QLabel*companyLabel;
        QLabel*emailLabel;
        QLabel*postalLabel;
        QLineEdit*companyLineEdit;
        QLineEdit*emailLineEdit;
        QLineEdit*postalLineEdit;
    };

    
    class ConclusionPage : public QWizardPage
    {
        Q_OBJECT

    public:
       ConclusionPage(QWidget *parent = 0);

        voidinitializePage();
        int nextId()const;
        voidsetVisible(bool visible);

    private slots:
        voidprintButtonClicked();

    private:
        QLabel*bottomLabel;
        QCheckBox*agreeCheckBox;
    };
    记得添加类声明:
    QT_BEGIN_NAMESPACE
    class QCheckBox;
    class QLabel;
    class QLineEdit;
    class QRadioButton;
    QT_END_NAMESPACE

    【3】在lecensewizard.cpp文件中添加代码:
    在构造函数里添加:
       setPage(Page_Intro, new IntroPage);
       setPage(Page_Evaluate, new EvaluatePage);
       setPage(Page_Register, new RegisterPage);
       setPage(Page_Details, new DetailsPage);
       setPage(Page_Conclusion, new ConclusionPage);
       setStartId(Page_Intro);
       setWizardStyle(ModernStyle);

       setOption(HaveHelpButton, true);
       setPixmap(QWizard::LogoPixmap, QPixmap(":/images/logo.png"));
       connect(this, SIGNAL(helpRequested()), this,SLOT(showHelp()));
       setWindowTitle(tr("License Wizard"));

    添加showHelp();槽函数:
    void LicenseWizard::showHelp()
    {
        staticQString lastHelpMessage;

        QStringmessage;

        switch(currentId()) {
        casePage_Intro:
           message = tr("The decision you make here will affect which page you"
                        "get to see next.");
           break;
        casePage_Evaluate:
           message = tr("Make sure to provide a valid email address, such as"
                        "toni.buddenbrook@example.de.");
           break;
        casePage_Register:
           message = tr("If you don't provide an upgrade key, you will be"
                        "asked to fill in your details.");
           break;
        casePage_Details:
           message = tr("Make sure to provide a valid email address, such as"
                        "thomas.gradgrind@example.co.uk.");
           break;
        casePage_Conclusion:
           message = tr("You must accept the terms and conditions of the"
                        "license to proceed.");
           break;
       default:
           message = tr("This help is likely not to be of any help.");
        }

        if(lastHelpMessage == message)
           message = tr("Sorry, I already gave what help I could. "
                        "Maybe you should try asking a human?");

       QMessageBox::information(this, tr("License Wizard Help"),message);

       lastHelpMessage = message;
    }
    添加其它几个类的代码:
    IntroPage::IntroPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Introduction"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/watermark.png"));

        topLabel= new QLabel(tr("This wizard will help you register your copy of"
                                "<i>Super ProductOne</i>&trade; orstart "
                                "evaluating the product."));
       topLabel->setWordWrap(true);

       registerRadioButton = newQRadioButton(tr("&Register your copy"));
       evaluateRadioButton = newQRadioButton(tr("&Evaluate the product for 30"
                                                 "days"));
       registerRadioButton->setChecked(true);

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(topLabel);
       layout->addWidget(registerRadioButton);
       layout->addWidget(evaluateRadioButton);
       setLayout(layout);
    }
    int IntroPage::nextId() const
    {
        if(evaluateRadioButton->isChecked()) {
           return LicenseWizard::Page_Evaluate;
        } else{
           return LicenseWizard::Page_Register;
        }
    }
    EvaluatePage::EvaluatePage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Evaluate <i>SuperProductOne</i>&trade;"));
       setSubTitle(tr("Please fill both fields. Make sure to provide avalid "
                      "email address (e.g., john.smith@example.com)."));

        nameLabel= new QLabel(tr("N&ame:"));
        nameLineEdit= new QLineEdit;
       nameLabel->setBuddy(nameLineEdit);

       emailLabel = new QLabel(tr("&Emailaddress:"));
       emailLineEdit = new QLineEdit;
       emailLineEdit->setValidator(newQRegExpValidator(QRegExp(".*@.*"), this));
       emailLabel->setBuddy(emailLineEdit);

       registerField("evaluate.name*", nameLineEdit);
       registerField("evaluate.email*", emailLineEdit);

       QGridLayout *layout = new QGridLayout;
       layout->addWidget(nameLabel, 0, 0);
       layout->addWidget(nameLineEdit, 0, 1);
       layout->addWidget(emailLabel, 1, 0);
       layout->addWidget(emailLineEdit, 1, 1);
       setLayout(layout);
    }
    int EvaluatePage::nextId() const
    {
        returnLicenseWizard::Page_Conclusion;
    }

    RegisterPage::RegisterPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Register Your Copy of<i>Super ProductOne</i>&trade;"));
       setSubTitle(tr("If you have an upgrade key, please fill in "
                      "the appropriate field."));

        nameLabel= new QLabel(tr("N&ame:"));
        nameLineEdit= new QLineEdit;
       nameLabel->setBuddy(nameLineEdit);

       upgradeKeyLabel = new QLabel(tr("&Upgradekey:"));
       upgradeKeyLineEdit = new QLineEdit;
       upgradeKeyLabel->setBuddy(upgradeKeyLineEdit);

       registerField("register.name*", nameLineEdit);
       registerField("register.upgradeKey", upgradeKeyLineEdit);

       QGridLayout *layout = new QGridLayout;
       layout->addWidget(nameLabel, 0, 0);
       layout->addWidget(nameLineEdit, 0, 1);
       layout->addWidget(upgradeKeyLabel, 1, 0);
       layout->addWidget(upgradeKeyLineEdit, 1, 1);
       setLayout(layout);
    }

    int RegisterPage::nextId() const
    {
        if(upgradeKeyLineEdit->text().isEmpty()) {
           return LicenseWizard::Page_Details;
        } else{
           return LicenseWizard::Page_Conclusion;
        }
    }

    DetailsPage::DetailsPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Fill In Your Details"));
       setSubTitle(tr("Please fill all three fields. Make sure to providea valid "
                      "email address (e.g., tanaka.aya@example.co.jp)."));

       companyLabel = new QLabel(tr("&Companyname:"));
       companyLineEdit = new QLineEdit;
       companyLabel->setBuddy(companyLineEdit);

       emailLabel = new QLabel(tr("&Emailaddress:"));
       emailLineEdit = new QLineEdit;
       emailLineEdit->setValidator(newQRegExpValidator(QRegExp(".*@.*"), this));
       emailLabel->setBuddy(emailLineEdit);

       postalLabel = new QLabel(tr("&Postaladdress:"));
       postalLineEdit = new QLineEdit;
       postalLabel->setBuddy(postalLineEdit);

       registerField("details.company*", companyLineEdit);
       registerField("details.email*", emailLineEdit);
       registerField("details.postal*", postalLineEdit);

       QGridLayout *layout = new QGridLayout;
       layout->addWidget(companyLabel, 0, 0);
       layout->addWidget(companyLineEdit, 0, 1);
       layout->addWidget(emailLabel, 1, 0);
       layout->addWidget(emailLineEdit, 1, 1);
       layout->addWidget(postalLabel, 2, 0);
       layout->addWidget(postalLineEdit, 2, 1);
       setLayout(layout);
    }

    int DetailsPage::nextId() const
    {
        returnLicenseWizard::Page_Conclusion;
    }

    ConclusionPage::ConclusionPage(QWidget *parent)
        :QWizardPage(parent)
    {
       setTitle(tr("Complete Your Registration"));
       setPixmap(QWizard::WatermarkPixmap,QPixmap(":/images/watermark.png"));

       bottomLabel = new QLabel;
       bottomLabel->setWordWrap(true);

       agreeCheckBox = new QCheckBox(tr("I agree to the terms of thelicense"));

       registerField("conclusion.agree*", agreeCheckBox);

       QVBoxLayout *layout = new QVBoxLayout;
       layout->addWidget(bottomLabel);
       layout->addWidget(agreeCheckBox);
       setLayout(layout);
    }

    int ConclusionPage::nextId() const
    {
        return-1;
    }
    void ConclusionPage::initializePage()
    {
        QStringlicenseText;

        if(wizard()->hasVisitedPage(LicenseWizard::Page_Evaluate)){
           licenseText = tr("<u>EvaluationLicense Agreement:</u> "
                            "You can use this software for 30 days and make one "
                            "backup, but you are not allowed to distribute it.");
        } else if(wizard()->hasVisitedPage(LicenseWizard::Page_Details)){
           licenseText = tr("<u>First-TimeLicense Agreement:</u> "
                            "You can use this software subject to the license "
                            "you will receive by email.");
        } else{
           licenseText = tr("<u>Upgrade LicenseAgreement:</u> "
                            "This software is licensed under the terms of your "
                            "current license.");
        }
       bottomLabel->setText(licenseText);
    }
    
    void ConclusionPage::setVisible(bool visible)
    {
       QWizardPage::setVisible(visible);

        if(visible) {
           wizard()->setButtonText(QWizard::CustomButton1,tr("&Print"));
           wizard()->setOption(QWizard::HaveCustomButton1,true);
           connect(wizard(), SIGNAL(customButtonClicked(int)),
                   this, SLOT(printButtonClicked()));
        } else{
           wizard()->setOption(QWizard::HaveCustomButton1,false);
           disconnect(wizard(), SIGNAL(customButtonClicked(int)),
                      this, SLOT(printButtonClicked()));
        }
    }

    void ConclusionPage::printButtonClicked()
    {
        QPrinterprinter;
        QPrintDialogdialog(&printer, this);
        if(dialog.exec())
           QMessageBox::warning(this, tr("Print License"),
                                tr("As an environmentally friendly measure, the "
                                   "license text will not actually be printed."));
    }
    【4】添加mian函数:
    #include <QApplication>
    #include <QTranslator>
    #include <QLocale>
    #include <QLibraryInfo>

    #include "licensewizard.h"

    int main(int argc, char *argv[])
    {
       Q_INIT_RESOURCE(licensewizard);

       QApplication app(argc, argv);

     

       QStringtranslatorFileName = QLatin1String("qt_");
       translatorFileName += QLocale::system().name();
        QTranslator*translator = new QTranslator(&app);
        if(translator->load(translatorFileName,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
           app.installTranslator(translator);
       
       LicenseWizard wizard;
       wizard.show();
        returnapp.exec();
    }

    展开全文
  • QTdialog类文档

    2015-09-06 23:27:40
    QTdialog类文档 入门文档 简易QTdialog实现
  • The minimal QT dialog

    2020-12-31 14:31:37
    <div><p>The dialog class takes full advantage of features of the Qt framework and the matplotlib plotting widgets. The first dialog is one used in the sct_propseg command. <h2>Test the python module ...
  • Qt dialog 对话框

    2017-06-09 14:40:03
    常用的对话框: QFileDialog,QColorDialog,QFontDialog,QInputDialog,QMessageDialog以及自定义...这次使用了ui设计界面设计的Dialog,没有使用纯代码。所以只写相应的槽函数即可 源文件: view

    常用的对话框:

    QFileDialog,QColorDialog,QFontDialog,QInputDialog,QMessageDialog以及自定义对话框。


    这里只做了输入对话框的,其他类似。




    这次使用了ui设计界面设计的Dialog,没有使用纯代码。所以只写相应的槽函数即可

    源文件:

    1. #include "dialog.h"   
    2. #include "ui_dialog.h"   
    3. #include <QInputDialog>   
    4. #include <QStringList>   
    5. #include <QString>   
    6. Dialog::Dialog(QWidget *parent) :  
    7.     QDialog(parent),  
    8.     ui(new Ui::Dialog)  
    9. {  
    10.     ui->setupUi(this);  
    11. }  
    12.   
    13. Dialog::~Dialog()  
    14. {  
    15.     delete ui;  
    16. }  
    17.   
    18. void Dialog::on_nameBtn_clicked()  
    19. {  
    20.     bool ok;  
    21.     QString name=QInputDialog::getText(this,tr("标准输入对话框"),tr("请输入姓名:"),  
    22.                                        QLineEdit::Normal,ui->name->text(),&ok);  
    23.     if(ok&&!name.isEmpty())  
    24.         ui->name->setText(name);  
    25. }  
    26.   
    27. void Dialog::on_sexBtn_clicked()  
    28. {  
    29.     QStringList SexList;  
    30. //    SexList<<tr("男")<<tr("女");   
    31.     bool ok;  
    32.     QString SexItem=QInputDialog::getItem(this,tr("标准条目选择对话框"),tr("请选择性别:"),  
    33.                                           SexList,0,false,&ok);  
    34.     if(ok&&!SexItem.isEmpty())  
    35.         ui->sex->setText(SexItem);  
    36. }  
    37.   
    38. void Dialog::on_ageBtn_clicked()  
    39. {  
    40.     bool ok;  
    41.     int ageInt=QInputDialog::getInt(this,tr("标准整数输入对话框"),tr("请输入年龄:"),  
    42.                                  ui->age->text().toInt(&ok),1,200,1,&ok);  
    43.     if(ok)  
    44.         ui->age->setText(QString(tr("%1")).arg(ageInt));  
    45. }  
    46.   
    47. void Dialog::on_gradeBtn_clicked()  
    48. {  
    49.     bool ok;  
    50.     double score=QInputDialog::getDouble(this,tr("标准浮点数输入对话框"),tr("请输入成绩:"),  
    51.                                  ui->grade->text().toDouble(&ok),1,100,1,&ok);  
    52.     if(ok)  
    53.         ui->grade->setText(QString(tr("%1")).arg(score));  
    54. }  
    [cpp] view plain copy
    1. #include "dialog.h"  
    2. #include "ui_dialog.h"  
    3. #include <QInputDialog>  
    4. #include <QStringList>  
    5. #include <QString>  
    6. Dialog::Dialog(QWidget *parent) :  
    7.     QDialog(parent),  
    8.     ui(new Ui::Dialog)  
    9. {  
    10.     ui->setupUi(this);  
    11. }  
    12.   
    13. Dialog::~Dialog()  
    14. {  
    15.     delete ui;  
    16. }  
    17.   
    18. void Dialog::on_nameBtn_clicked()  
    19. {  
    20.     bool ok;  
    21.     QString name=QInputDialog::getText(this,tr("标准输入对话框"),tr("请输入姓名:"),  
    22.                                        QLineEdit::Normal,ui->name->text(),&ok);  
    23.     if(ok&&!name.isEmpty())  
    24.         ui->name->setText(name);  
    25. }  
    26.   
    27. void Dialog::on_sexBtn_clicked()  
    28. {  
    29.     QStringList SexList;  
    30. //    SexList<<tr("男")<<tr("女");  
    31.     bool ok;  
    32.     QString SexItem=QInputDialog::getItem(this,tr("标准条目选择对话框"),tr("请选择性别:"),  
    33.                                           SexList,0,false,&ok);  
    34.     if(ok&&!SexItem.isEmpty())  
    35.         ui->sex->setText(SexItem);  
    36. }  
    37.   
    38. void Dialog::on_ageBtn_clicked()  
    39. {  
    40.     bool ok;  
    41.     int ageInt=QInputDialog::getInt(this,tr("标准整数输入对话框"),tr("请输入年龄:"),  
    42.                                  ui->age->text().toInt(&ok),1,200,1,&ok);  
    43.     if(ok)  
    44.         ui->age->setText(QString(tr("%1")).arg(ageInt));  
    45. }  
    46.   
    47. void Dialog::on_gradeBtn_clicked()  
    48. {  
    49.     bool ok;  
    50.     double score=QInputDialog::getDouble(this,tr("标准浮点数输入对话框"),tr("请输入成绩:"),  
    51.                                  ui->grade->text().toDouble(&ok),1,100,1,&ok);  
    52.     if(ok)  
    53.         ui->grade->setText(QString(tr("%1")).arg(score));  
    54. }  

    展开全文
  • Qt调用Dialog窗口的exec崩溃问题处理 问题描述:做的界面Qt程序在调用dialog.exec()的地方崩溃,不清楚原因。 我的代码定义 class DialogFindTrainNo : public QDialog { Q_OBJECT public: explicit ...

    Qt调用Dialog窗口的exec崩溃问题处理

    • 问题描述:做的界面Qt程序在调用dialog.exec()的地方崩溃,不清楚原因。
    • 我的代码定义
    	class DialogFindTrainNo : public QDialog
    {
        Q_OBJECT
    
    public:
        explicit DialogFindTrainNo(QWidget *parent = 0);
        ~DialogFindTrainNo();
    public:
        bool m_bEnter;
        QString m_QstrTrainNo;
    
    
        void SetText(QString strText);
    
    private slots:
        void on_pushButton_2_clicked();
    
        void on_pushButton_clicked();
    private:
        Ui::DialogFindTrainNo *ui;
    };
    

    Dialog类的调用部分代码

        DialogFindTrainNo *m_GetTrainDlg;
        m_GetTrainDlg = new DialogFindTrainNo(parent);
        m_GetTrainDlg->SetText("");
         m_GetTrainDlg->hide();
        m_GetTrainDlg->setGeometry(0,100,520,210);
        m_GetTrainDlg->exec();
    	QString QstrGet = m_GetTrainDlg->m_QstrTrainNo;
    
    • 我需要把Dialog里面的变量m_QstrTrainNo取出来,进行查询。测试结果就是会崩溃在exec()的位置。

    • 经过长时间的查找,并不是崩溃在exec()位置,而且崩溃在QstrGet赋值的语句。从Dialog里面取Qstring就大概率崩溃,取m_bEnter却不会有问题。

    • **问题解决:**定义一个全局变量QString把Dialog的输入存储为全局变量。

    • 但是为什么这样取字符串会有问题,和QString的定义就有关系了,也许exec之后,内部的QString就被释放了。

    展开全文
  • QT dialog 模态

    2017-07-18 17:15:35
    DialogWindow->setWindowTitle("A TSET WINDOW"); //建一个窗口 QPushButton *buttonshow = new QPushButton; //show()非模态(非阻塞) QPushButton *buttonexec = new QPushButton; //exec() 模态(阻塞) ...

    对话框分为两种:1模态对话框 2非模态对话框

    模态对话框就是阻塞对话框,就是你不解决掉这个对话框,谁没办法点这个对话框以外的操作的  (就平时点外面 “噔噔噔” 不让点那种样子的)

    非模态就是自己弹出的对话框,我们可以不管他,继续进行当前窗口的任务。



    其中模态对话框包含 应用程序级别和窗口级别  对应阻塞程度顾名思义了。

    show()函数是非模态非阻塞性质的  show()的话要建立在堆上

    exec()函数是模态阻塞性质的    exec()建立在堆栈上都可以 ,因为会阻塞,阻塞不会立刻在堆上释放掉




    #include <QApplication>
    #include <QPushButton>
    #include <QDebug>
    #include<QDialog>
    #include<QMainWindow>
    #include<QTime>
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        QMainWindow *DialogWindow= new QMainWindow ;
        DialogWindow->setWindowTitle("A TSET WINDOW");      //建一个窗口
    
        QPushButton *buttonshow = new QPushButton;                    //show()非模态(非阻塞)
        QPushButton *buttonexec = new QPushButton;                    //exec() 模态(阻塞)
        QPushButton *buttonshowinstack = new QPushButton;            //show() 建立在栈上 (会自动被释放)
    
        buttonshow->setText("show");
        buttonexec->setText("exec");
        buttonshowinstack->setText("showinstack");
    
        buttonshow->setGeometry(10,10,30,30);
        buttonexec->setGeometry(50,10,30,30);
        buttonshowinstack->setGeometry(10,50,80,30);
    
      buttonshow->setParent(DialogWindow);
      buttonexec->setParent(DialogWindow);
      buttonshowinstack->setParent(DialogWindow);
    
    
        QObject::connect(buttonshow, &QPushButton::clicked, [&](bool) {      //lambda 
            QDialog *m=new QDialog;
            m->setWindowTitle("堆开辟 非阻塞");
            m->setAttribute(Qt::WA_DeleteOnClose);          //当点击关闭对话框是 自动释放掉m对象
            m->setGeometry(330,330,200,100);                //可以开很多Dialog 这样写重叠在一起了 
            m->show();
            qDebug() << "buttonshow!";
        });
        QObject::connect(buttonshowinstack, &QPushButton::clicked, [&](bool) {
    
            QDialog m;
            m.setWindowTitle("栈开辟 非阻塞");
            m.setGeometry(330,330,200,100);
            m.show();
      QTime reach = QTime::currentTime().addMSecs(600);
      while(QTime::currentTime()<reach)
        QCoreApplication::processEvents(QEventLoop::AllEvents,100);    //这三行用于延时 QT 貌似没有windows.h的Sleep函数
    
            qDebug() << "buttonshowinstack!";
        });
    
    
        QObject::connect(buttonexec, &QPushButton::clicked, [&](bool) {
            QDialog *m=new QDialog;
            m->setWindowTitle(" 阻塞");
             m->setGeometry(330,330,200,100);       
            m->setAttribute(Qt::WA_DeleteOnClose);            //当点击关闭对话框是 自动释放掉m对象
            m->exec();
            qDebug() << "buttonexec!";
        });
    
    
    
    
        DialogWindow->show();
        buttonshow->show();
        buttonexec->show();
        buttonshowinstack->show();
    
        return app.exec();
    }



    点击show 就会出现非阻塞对话框  exec就会出现阻塞对话框  showinstack 一闪而过(延时了 不然看不到) 说明不能再栈上建立非阻塞对话框


    展开全文
  • 嵌入式 QTDialog界面上文本问题

    千次阅读 2013-12-02 14:39:01
    如果想在QTDialog窗体上进行放置一些文本,而且想不让文本遮住主窗体的背景那么就添加Label标签 #include #include "logindlg.h" #include "ui_logindlg.h" loginDlg::loginDlg(QWidget *parent) :   QDialog...
  • Qt Dialog窗体属性设置

    2020-11-05 17:21:19
    ~Qt::WindowContextHelpButtonHint); 窗体各种标志使用如下所示: setWindowFlags ( Qt::WindowFlags type ) Qt::FrameWindowHint:没有边框的窗口 Qt::WindowStaysOnTopHint://总在最上面的窗口 Qt::...
  • Qt dialog 的geometry()

    2019-10-06 19:21:49
    Note that QDialog (an any other widget that has type Qt::Dialog) uses the parent widget slightly differently from other classes in Qt. A dialog is always a top-level widget, but if it has a paren...
  • QT Dialog右上角问号

    千次阅读 2018-11-16 22:23:12
    Qt::WindowFlags flags=Qt::Dialog;flags |=Qt::WindowCloseButtonHint; setWindowFlags(flags);  
  • 问题:使用dialog中的输入框编辑,发现软键盘虽然弹出,但是按键无反应。(不止键盘,别的部件也会有此问题) 原因:dialog使用了exec(),... msg.setWindowModality(Qt::WindowModal); if(msg.exec() == BaseDial
  • this->setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
  • 源码: #include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog() { delete ui; } void Dialog::on_...
  • 最近做的项目中,由于重写界面标题栏,需要自己实现鼠标拖动界面放大缩小的功能,所以就需要捕获鼠标移动事件。 在网上查了一些资料,很多都说通过setMouseTracking(true);...setAttribute(Qt::WA_Hover,...
  • QT Dialog增加最大最小按钮

    千次阅读 2017-04-01 10:57:59
    QT 添加最大最小化,关闭选项。
  • 运行效果如下图: ...setWindowFlags(Qt::CustomizeWindowHint|Qt::FramelessWindowHint); //将主窗体设置为这样的样式 uTitleBar = new UTitleBar(this); uTitleBar->setAutoFillBackgr...
  • QT dialog一种使用方法

    2015-04-08 23:05:02
    // 导出视频片段 void extractTrajectoryWidget::exportAviSegment() { //设计一个弹出widget,包括... QDialog* dialog = new QDialog(this); dialog->window()->setWindowTitle(QStringLiteral("导出配置")); QLine
  • setWindowFlags(Qt::Dialog|Qt::WindowStaysOnTopHint|Qt::WindowTitleHint| Qt::CustomizeWindowHint);其中CustomizeWindowHint,
  • qt dialog最小化 后 没有在任务栏显示,在哪里配置 显示出来,像这样: [img=https://img-bbs.csdn.net/upload/201705/02/1493719176_993516.png][/img]
  • 类A:class A: public QMainWindow {private: B} 类B:class B: public QWidget {private: C} 类C:class C: public QDialog {private: QProgressBar} 在类A中创建类B实例, 调用类B函数B::CallC,使C.show();...
  • QT Dialog 显示最大化最小化按钮

    千次阅读 2012-10-27 23:48:50
    setWindowFlags(Qt::WindowMinimizeButtonHint);
  • Qt对话框Dialog

    2017-08-16 15:45:49
    Qt对话框建立
  • 注意,使用lamda表达式的时候,需要在pro下面加入下面的东西,才能...QtDialog.pro #------------------------------------------------- # # Project created by QtCreator 2019-09-18T02:49:41 # #-------------...
  • QTDialog显示最大化最小化按钮

    千次阅读 2013-12-05 10:24:19
    QT中Dialog显示最大化最小化按钮 ...qtdialog测试 转载自http://hi.baidu.com/xp2107/blog/item/3de67ddb8040be1d622798ed.html 今天经过多番测试总结出对于继承自QDialog的类窗

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,406
精华内容 1,362
关键字:

qtdialog