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

时间:2023-01-06 19:38:58

I have a main form with menu bar.

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

My Requirement

我的要求

On clicking a particular QAction on menubar, a modal window should open. The model window contains two QLineEdit and a QPushButton. When the button is pushed the value of one of the QLineEdit is added to a comboBox(in the main window) and the other value should be added in the field variable of the mainwindow.

单击菜单栏上的特定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();
}

How should i proceed now

我该怎么办呢

1 个解决方案

#1


1  

You could return a struct with the responde, like:

您可以使用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()));

And the called could receive the returned values and perform the required actions. This way, the dialog does not interacts directly with the mainwindow.

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

#1


1  

You could return a struct with the responde, like:

您可以使用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()));

And the called could receive the returned values and perform the required actions. This way, the dialog does not interacts directly with the mainwindow.

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