简体   繁体   中英

Call method in QMainWindow from QDialog

I am running this to show a dialog window from main:

void SQLWindow::on_action_4_triggered()
{ 
   HeaderList window; 
   window.show(); 
   window.exec(); 
}

Here I am trying to connect a saveButtonClicked() to the SLOT in the Main Window:

HeaderList::HeaderList(QWidget *parent) : QDialog(parent), ui(new Ui::HeaderList) 
{ 
   connect(this, SIGNAL(saveButtonClicked()), SQLWindow, SLOT(hideColumns())); 

   ui->setupUi(this); 
}

but getting an error: "expected primary-expression before ',' token" which points at "SQLWindow". I am doing this wrong, obviously. Any ideas how to call a method in Main Window from Dialog?

The third parameter in connect(...) needs to be a pointer to an instance. Just change the signature of your HeaderList's constructor and add the SQLWindow as parameter (+ use the newer connect method call as TheDarkKnight mentioned):

HeaderList::HeaderList(SQLWindow *parent) : QDialog(parent), ui(new Ui::HeaderList)
{
    connect(this, &HeaderList::saveButtonClicked, parent, &SQLWindow::hideColumns);

    ui->setupUi(this);
}

In the header file, it would be a good idea to make the HeaderList constructor explicit and not overload parent with nullptr:

class HeaderList
{
public:
    explicit HeaderList(SQLWindow *parent);

    //...
};

Pass the SQLWindow to your HeaderList (and omit show() as thuga mentioned):

void SQLWindow::on_action_4_triggered()
{
    HeaderList window(this);
    window.exec();
}

connect the signal other way round like this:

class HeaderList
{
public:
    explicit HeaderList(QWidget *parent);

signals:
    void saveButtonClicked();
};

now in SQLWindow

void SQLWindow::on_action_4_triggered()
{ 
   HeaderList window; 
   connect(&window, SIGNAL(saveButtonClicked()), this, SLOT(hideColumns()));
   window.exec(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM