创建一个向主窗体返回值的模态窗口

creating a modal window that returns a value to the main form

本文关键字:返回值 窗体 模态 窗口 一个 创建      更新时间:2023-10-16

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

<<p> 我的要求/strong>

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

What I have Done

// 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();
}

我现在该怎么做

您可以返回带有响应的结构体,如:

// 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()));

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