如何在QMessageBox中包含QLineEdit以获取搜索表单

时间:2012-02-19 17:29:17

标签: c++ qt

我需要实现一个搜索表单(我已经有了这个函数),但我不知道如何将QlineEdit和QPushButton附加到QMessageBox上。

2 个答案:

答案 0 :(得分:2)

您可以将QDialog子类化并将其用作消息框

searchdialog.h:

#ifndef SEARCHDIALOG_H
#define SEARCHDIALOG_H

#include <QDialog>
#include <QLineEdit>

class SearchDialog : public QDialog
{
    Q_OBJECT
public:
    explicit SearchDialog(QWidget *parent = 0);

    QString searchString() const;

private:
    QLineEdit *m_lineEdit;
};

#endif // SEARCHDIALOG_H

searchdialog.cpp

#include "searchdialog.h"

#include <QVBoxLayout>
#include <QPushButton>
#include <QDialogButtonBox>

SearchDialog::SearchDialog(QWidget *parent) :
    QDialog(parent)
{
    m_lineEdit = new QLineEdit(this);

    QPushButton *searchButton = new QPushButton(tr("Search"));
    searchButton->setDefault(true);

    QPushButton *cancelButton = new QPushButton(tr("Cancel"));

    QDialogButtonBox *buttonBox = new QDialogButtonBox(Qt::Horizontal);
    buttonBox->addButton(searchButton, QDialogButtonBox::AcceptRole);
    buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);

    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    QVBoxLayout *lt = new QVBoxLayout;
    lt->addWidget(m_lineEdit);
    lt->addWidget(buttonBox);

    setLayout(lt);
}

QString SearchDialog::searchString() const
{
    return m_lineEdit->text();
}

的main.cpp

#include <QtGui/QApplication>
#include <QtGui/QMessageBox>

#include <QLabel>

#include "searchdialog.h"

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

    QLabel lbl;
    SearchDialog *dialog = new SearchDialog(&lbl);
    lbl.show();

    QString searchString;

    if (dialog->exec()) {
        searchString = dialog->searchString();
        lbl.setText(searchString);
    }

    return a.exec();
}

答案 1 :(得分:1)

尝试使用其布局:

#include <QApplication>
#include  <QMessageBox>
#include  <QLineEdit>
#include  <QPushButton>
#include  <QLayout>

  int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        QMessageBox mb;
        QLineEdit le;
        QPushButton bt;

        mb.layout()->addWidget(&bt);
        mb.layout()->addWidget(&le);

        mb.show();
        return app.exec();
    }