简体   繁体   English

Qt:从main函数访问Widget并实现退出按钮

[英]Qt: Access Widget from main function and implement exit button

I want to implement an exit button in my application, which has the following setup: I have a main function which looks like this: 我想在我的应用程序中实现一个退出按钮,它具有以下设置:我有一个主要功能,如下所示:

QApplication a(argc, argv);
MainWindow w;

w.show();

return a.exec();

I also have a mainWindow function which has been generated by the QT Creator IDE. 我还有一个由QT Creator IDE生成的mainWindow函数。
I design the GUI with the Qt Designer and when I want a pushbutton to do something when clicked, I use a function like this: 我使用Qt Designer设计GUI,当我想要一个按钮在点击时做某事时,我使用这样的函数:

void on_selection_clicked();

I hope the setup is now sufficiently described. 我希望现在已经充分描述了设置。
Now to my problem: I want to implement a button, which, when clicked, terminates the window and the application. 现在我的问题:我想实现一个按钮,当单击它时,终止窗口和应用程序。 I first tried implementing this in a function like this: 我首先尝试在这样的函数中实现它:

void on_exit_clicked();

But I don't know that to to here. 但我不知道到了这里。
Then I heard of a aproach via QObject::connect , but I have two questions: 然后我通过QObject::connect听说过aproach,但我有两个问题:
1.) Where should I put this? 1.)我应该把它放在哪里? In the main function? 在主要功能?
2.) can I access the object simply via the object name given in the QT Designer? 2.)我可以通过QT Designer中给出的对象名称来访问对象吗?

  1. no you should connect it in the constructor of the MainWindow 不,你应该在MainWindow的构造函数中连接它

     connect(ui->exit,SIGNAL(clicked()),QCoreApplication::instance(), SLOT(exit())); 

    QCoreApplication::instance()->exit() will quit the application QCoreApplication::instance()->exit()将退出应用程序

  2. yes through the ui field in MainWindow see the code above 是的,通过MainWindow中的ui字段查看上面的代码

I don't know which Qt version you use, so I will suppose Qt 5.0 (signal/slot mechanims was updated). 我不知道你使用哪个Qt版本,所以我假设Qt 5.0(信号/插槽机制更新了)。

  • QWidget has slot QWidget::close(). QWidget有插槽QWidget :: close()。

  • QPushButton provides signal QPushButton::clicked(bool checked = false) QPushButton提供信号QPushButton :: clicked(bool checked = false)

So you can connect them in constructor of your MainWindow: 所以你可以在MainWindow的构造函数中连接它们:

QObject::connect(your_button, &QPushButton::clicked, this, &QWidget::close());

Also I suggest to look into the files generated from *.ui files - so you have deeper understanding of what's going on. 此外,我建议查看从* .ui文件生成的文件 - 这样您就可以更深入地了解正在发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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