单击菜单项上的Qt显示模式对话框(.ui) [英] Qt show modal dialog (.ui) on menu item click
问题描述
我想创建一个简单的关于"模式对话框,从帮助"->关于应用程序"菜单中调用.我已经使用QT Creator(.ui文件)创建了一个模态对话框窗口.
I want to make a simple 'About' modal dialog, called from Help->About application menu. I've created a modal dialog window with QT Creator (.ui file).
关于"菜单中应该包含什么代码?
What code should be in menu 'About' slot?
现在我有了这段代码,但是它显示了一个新的模式对话框(不是基于我的about.ui):
Now I have this code, but it shows up a new modal dialog (not based on my about.ui):
void MainWindow::on_actionAbout_triggered()
{
about = new QDialog(0,0);
about->show();
}
谢谢!
推荐答案
您需要使用.ui
文件中的UI设置对话框. Qt uic
编译器从您的.ui
文件生成一个头文件,您需要将该头文件包含在代码中.假设您的.ui
文件名为about.ui
,并且对话框名为About
,则uic
创建包含类Ui_About
的文件ui_about.h
.设置UI的方法有多种,最简单的方法就是
You need to setup the dialog with the UI you from your .ui
file. The Qt uic
compiler generates a header file from your .ui
file which you need to include in your code. Assumed that your .ui
file is called about.ui
, and the Dialog is named About
, then uic
creates the file ui_about.h
, containing a class Ui_About
. There are different approaches to setup your UI, at simplest you can do
#include "ui_about.h"
...
void MainWindow::on_actionAbout_triggered()
{
about = new QDialog(0,0);
Ui_About aboutUi;
aboutUi.setupUi(about);
about->show();
}
更好的方法是使用继承,因为它更好地封装了对话框,因此您可以在子类中实现特定于特定对话框的任何功能:
A better approach is to use inheritance, since it encapsulates your dialogs better, so that you can implement any functionality specific to the particular dialog within the sub class:
AboutDialog.h:
#include <QDialog>
#include "ui_about.h"
class AboutDialog : public QDialog, public Ui::About {
Q_OBJECT
public:
AboutDialog( QWidget * parent = 0);
};
AboutDialog.cpp:
AboutDialog::AboutDialog( QWidget * parent) : QDialog(parent) {
setupUi(this);
// perform additional setup here ...
}
用法:
#include "AboutDialog.h"
...
void MainWindow::on_actionAbout_triggered() {
about = new AboutDialog(this);
about->show();
}
无论如何,重要的代码是调用setupUi()
方法.
In any case, the important code is to call the setupUi()
method.
顺便说一句::以上代码中的对话框是非模式的.要显示模式对话框,请将对话框的windowModality
标志设置为Qt::ApplicationModal
或使用exec()
而不是show()
.
BTW: Your dialog in the code above is non-modal. To show a modal dialog, either set the windowModality
flag of your dialog to Qt::ApplicationModal
or use exec()
instead of show()
.
这篇关于单击菜单项上的Qt显示模式对话框(.ui)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!