【发布时间】:2015-09-12 03:40:49
【问题描述】:
我正在尝试创建一个 MDI 文档程序。我有一个关于创建子窗口的问题。
这是我的主窗口构造函数:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(tr("MDI"));
workspace = new QMdiArea;
setCentralWidget(workspace);
//fileNew();
createActions();
createMenus();
createToolbars();
statusBar()->showMessage(tr("Done"));
enableActions();
}
有趣的一点是fileNew(); 函数。它实际上是一个私有插槽函数,我想在触发“新文件”按钮时调用它。这里是私有槽fileNew()函数:
void MainWindow::fileNew()
{
DocumentWindows* document = new DocumentWindows;
workspace->addSubWindow(document);
}
当我从主窗口构造函数调用时,这个函数可以完美运行。但是,当我从使用信号槽机制的createActions(); 函数调用它时,会出现问题。
这是我的createActions()
void MainWindow::createActions()
{
newAction = new QAction(QIcon(":/Image/NewFile.png"),tr("&New"),this);
newAction->setShortcut(tr("Ctrl+N"));
newAction->setToolTip(tr("Open new document"));
connect(newAction, SIGNAL(triggered(bool)), this, SLOT(fileNew()));
}
即使触发了 SLOT,也不会创建子窗口。随后,我发现如果我添加document->show();,一切正常。
void MainWindow::fileNew()
{
DocumentWindows* document = new DocumentWindows;
workspace->addSubWindow(document);
document->show();
}
我的问题是:为什么 SLOT 中需要 show() 函数,而构造函数中不需要?
PS。 DocumentWindows 只是一个继承QTextEdit 的类。
【问题讨论】: