创建一个模式窗口,返回一个值到主窗体

时间:2014-07-26 19:40:52

标签: c++ qt

我有一个带菜单栏的主表单。

我的要求

单击菜单栏上的特定QAction时,应打开模态窗口。模型窗口包含两个QLineEdit和一个QPushButton。按下按钮时,其中一个QLineEdit的值将添加到组合框(在主窗口中),另一个值应添加到主窗口的字段变量中。

我做了什么

// Defines Action
addrecord = new QAction("Add Record", this);
recordaction->addAction(addrecord);

// COnnect it to the addRecord
connect(addrecord, SIGNAL(triggered()), &dialog1, SLOT(addRecord()));

//dialog class is derived from QDialog....should i change it??

void dialog::addRecord(){
    this->setWindowTitle("Add Server");
    QLineEdit *edit1 = new QLineEdit(this);
    QLineEdit *edit2 = new QLineEdit(this);
    QPushButton *ok = new QPushButton("Ok",this);

    edit1->move(120, 50);
    edit2->move(120, 100);

    ok->move(135,150);

    this->setMinimumSize(300,200);
    this->setWindowFlags(Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    this->setModal(true);

    this->show();
}

我现在该怎么办

1 个答案:

答案 0 :(得分:1)

您可以使用responde返回结构,例如:

// on your dialog
Response addRecord()
{
    ...
    this->exec(); // will block until you close the dialog
    ...
    Response r;
    r.a = edit1->text();
    r.b = edit2->text();
   return r;
}

// on mainwindow. doAddRecord() must be declared as a slot on mainwindow.h!
void doAddRecord()
{
    Response r = dialog->addRecord();
    // use the response r   
}

connect(addrecord, SIGNAL(triggered()), this, SLOT(doAddRecord()));

被调用者可以接收返回的值并执行所需的操作。 这样,对话框不会直接与主窗口交互。