通过Qt的菜单选项调用另外一个子窗口,有两种方法:
VS 2008 +Qt4.7
项目文件:
MainWindow.ui
MainWindow.h
MainWindow.cpp
1、手动调用窗口
a)、在MainWindow.h中声明两个函数,在MainWindow.cpp中定义该两个函数。
void MainWindow::createActions() { newAction = new QAction(tr("&New"), this); newAction->setIcon(QIcon(":/images/new.png")); newAction->setShortcut(QKeySequence::New); newAction->setStatusTip(tr("Create a new spreadsheet file")); connect(newAction, SIGNAL(triggered()), this, SLOT(newForm())); //绑定了该菜单选项打开窗口事件 }
//打开新窗口槽函数 void MainWindow::newForm() { examinationForm = new ExaminationForm(); examinationForm->show(); } //examinationForm 在MainWindow.h里已经声明为成员变量。
b)、在MainWindow.cpp 类的构造器中调用creatActions()即可打开菜单选项对应的窗口
2、可以利用Qt自身的机制
在MainWindow.ui生成的临时文件ui_MainWindow.h文件中,有句:
根据Qt自身的机制,我们只需要在MainWindow.h和MainWindow.cpp中写一个槽函数即可,但必须以一下固定格式
void on_<object name>_<signal name>(<signal parameters>);
//MainWindow.h private slots: //打开新界面 void on_newFormAction_triggered();
//Maindow.cpp //打开界面 void MainWindow::on_newFormAction_triggered() { newForm = new NewForm (); newForm ->show(); }
明显第二种比较方便,也比较类似MFC。