How to get sender widget with a signal/slot mechanism?

柔情痞子 提交于 2019-12-17 22:34:50

问题


It's possible to bind more than one signal to one slot (isn't?). So, is there a way to understand which widget sends the signal? I'm looking for something like sender argument of events in .NET


回答1:


QObject::sender() will do the job.




回答2:


Use QObject::sender() in the slot, like in the following Example:

void MainWindow::someSetupFunction( void )
{
   ...
   connect( _foobarButton, SIGNAL(clicked()), this, SLOT(buttonPressedSlot()) );
}

void MainWindow::buttonPressedSlot()
{
   // e.g. check with member variable _foobarButton
   QObject* obj = sender();
   if( obj == _foobarButton )
   { 
      ...
   }

   // e.g. casting to the class you know its connected with
   QPushButton* button = qobject_cast<QPushButton*>(sender());
   if( button != NULL ) 
   { 
      ...
   }

}



回答3:


Yes, you can connect multiple signals to one slot. In this case you would use QSignalMapper to differentiate the sources of the signals. This solution is limited to parameterless signals. You can see an example here.



来源:https://stackoverflow.com/questions/4046839/how-to-get-sender-widget-with-a-signal-slot-mechanism

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