Qt在菜单项单击时显示模式对话框(.ui)
我想制作一个简单的关于"模式对话框,从帮助->关于应用程序菜单中调用.我用 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
,Dialog名为About
,则uic
创建文件 ui_about.h
,包含一个类 Ui_About
.有不同的方法来设置你的 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);
};
关于Dialog.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()
而不是 显示()
.
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()
.
相关文章