PDA

View Full Version : How can I call a function on another Form?



binary001
17th October 2015, 09:45
Hi,

I've a two Forms (Form1 and Form2) in a program. When program starts two forms are run.

I have several codes on Form1 eg. many Key_Events

if (event->key() == Qt::Key_M) {
.......
}
else if (event->key() == Qt::Key_Y) {
.........
}
else if (event->key() == Qt::Key_G) {
.....
..........
}

On Form2, I add several pushbuttons.

When I pressed a button, I want to run (eg. Key_M Event of Form1).
When I pressed another, do another event.

I want to get sample code or example project.

Thanks

anda_skoa
17th October 2015, 10:54
Maybe you can clarify:
- do you want to call a function on the other object
or
- do you want to send events to the other object

Cheers,
_

binary001
17th October 2015, 12:49
Thanks for your reply

When I click playButton on PlayerForm, I want to fire Key_P Event on MainWindow Form.

eg.

At Form2 (PlayerForm)



void PlayerForm::on_playButton_clicked()
{
//fire the event Key_P on Form1 and want to run playSong(); ........
}

void PlayerForm::on_muteButton_clicked()
{
//fire the event Key_M on Form1 and want to run muteSong();
}

void PlayerForm::on_stopButton_clicked()
{
//fire the event Key_S on Form1 and want to run stopSong();
}


at Form1 (MainWindow)



if (event->key() == Qt::Key_P) {
playSong();
showVisualization();
setVolumeNormalization();
}
else if (event->key() == Qt::Key_M) {
muteSong();
}
else if (event->key() == Qt::Key_S) {
stopSong();
}

anda_skoa
17th October 2015, 14:27
Calling a function is easy, since you either call the function directly or make it a slot and let form2 emit a signal.

If you need to send an event, see QCoreApplication::postEvent().

Cheers,
_

d_stranz
17th October 2015, 21:44
When I click playButton on PlayerForm, I want to fire Key_P Event on MainWindow Form.

A better design would be something like this:

- On PlayerForm, you implement a "play()" signal.
- On MainWindow, you implement a "onPlay()" slot.
- When you construct your PlayerForm instance, you connect PlayerForm:: play() to MainWindow:: onPlay()
- When the user clicks the play button on PlayerForm, PlayerForm emits the "play()" signal
- MainWindow receives the signal in its onPlay() slot, and you do whatever it is you want to do.

The problem with posting events like you propose is that if you post them to the MainWindow's event loop, it will be the same as if the user had clicked the P key in the MainWindow. So the user can click P in either PlayerForm or MainWindow, and the same thing will happen. If you want to use PlayerForm to show the status of the song or whatever, but the user clicks P in MainWindow, PlayerForm won't know about it, so the two will not be synchronized any more.