How to pass data from a QDialog?

安稳与你 提交于 2019-12-21 11:29:57

问题


In Qt, what is the most elegant way to pass data from a QDialog subclass to the component that started the dialog in the cases where you need to pass down something more complex than a boolean or an integer return code?

I'm thinking emit a custom signal from the accept() slot but is there something else?


回答1:


QDialog has its own message loop and since it stops your application workflow, I usually use the following scheme:

MyQDialog dialog(this);
dialog.setFoo("blah blah blah");
if(dialog.exec() == QDialog::Accepted){
  // You can access everything you need in dialog object
  QString bar = dialog.getFoo();
}



回答2:


In the general case, if the data is fairly simple I like to create one or more custom signals and emit those as necessary. Simple or complex data, I will generally provide accessors for the data. In the complex case, then, I would connect a slot to the accepted signal, and get the desired information in that slot. The drawback to this is that you generally need to rely on storing a pointer to the dialog, or using the sender() hack to figure out which object triggered the slot.

void Foo::showDialog()
{
    if ( !m_dlg )
    {
        m_dlg = new Dialog( this );
        connect( m_dlg, SIGNAL( accepted() ), SLOT( onDialogAccepted() ) );
    }
    m_dlg->Setup( m_bar, m_bat, m_baz );
    m_dlg->show();
}

void Foo::onDialogAccepted()
{
    m_bar = m_dlg->bar();
    m_bat = m_dlg->bat();
    m_baz = m_dlg->baz();
    // optionally destroy m_dlg here.
}


来源:https://stackoverflow.com/questions/3585774/how-to-pass-data-from-a-qdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!