最近要用Qt写个小工具,其中需要实现Qt对话框上的菜单效果:
网上相关的例子不少,不过基本上都是通过代码来实现的,基本步骤是:
- 先new一堆的QAction
- 再new一堆的QMenu并按照菜单的层次组织好
- 最后还要写一堆的connect,将action和响应函数关联好
看看我这里的这么多菜单项,如果全用代码来实现,这不要累死个人吗?于是想到了用Qt Creator来解决问题。
不幸的是,基于QDialog的ui是无法配置菜单的,只有基于QMainWindow的ui才能配置菜单:
不知道为什么Qt Creator的组件工具箱中也没有菜单这个组件。那该怎么玩?好在Qt的ui说到底不过就是一个xml文件,我直接用Qt Creator搞不定的,我还不能直接编辑xml文件吗?
那就来试一试吧,先创建一个基于QMainWindow的ui,然后在这里组织和编辑各个菜单项,工具自动的生成了相应的action,这很不错。
然后保存。打开ui文本,将其中和菜单、action相关的xml拷贝出来:
<span style="color:#FF0000;"> <widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>23</height>
</rect>
</property></span>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>File</string>
</property>
<widget class="QMenu" name="menuFaults">
<property name="title">
<string>Faults</string>
</property>
<addaction name="actionThreePhaseFaultAtBus"/>
。。。
</widget>
<widget class="QMenu" name="menuNetwork">
<property name="title">
<string>Network</string>
</property>
<addaction name="actionAddAdmittance"/>
。。。
</widget>
<widget class="QMenu" name="menuGenerator">
<property name="title">
<string>Generator</string>
</property>
<addaction name="actionDisconnectGenerator"/>
。。。
</widget>
<widget class="QMenu" name="menuLoad">
<property name="title">
<string>Load</string>
</property>
<addaction name="actionShedLoad"/>
<addaction name="actionRestoreLoad"/>
</widget>
<widget class="QMenu" name="menuSimulation">
<property name="title">
<string>Simulation</string>
</property>
<addaction name="actionAtTime"/>
。。。
<addaction name="actionAfter"/>
</widget>
<addaction name="menuFaults"/>
。。。
</widget>
<addaction name="menuFile"/>
</widget>
<span style="color:#FF0000;"><widget class="QStatusBar" name="statusbar"/></span>
<action name="actionThreePhaseFaultAtBus">
<property name="text">
<string>ThreePhaseFaultAtBus</string>
</property>
</action>
。。。
<span style="color:#FF0000;"> </widget></span>
红色的部分是menubar和statusbar的描述,不用拷贝。
打开基于QDialog的ui,把这部分黏贴过去:
<widget class="QDialog" name="MainDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>499</width>
<height>397</height>
</rect>
</property>
<property name="windowTitle">
<string>MainDialog</string>
</property>
<span style="color:#3333FF;"><widget class="QMenu" name="menuFile"></span>
就直接放在QDialog下面吧,然后保存,编译:
此时我们看到这些action也可以直接基于QDialog的ui中显示了,这基本上也没啥悬念吧,Qt Creator不就是干这个的嘛。
然后在这些action上右键配置信号槽:
相应的代码就可以自动生成了。
尽管还是有些多,不过总比一点点人工敲代码要方便多了吧。
最后为按钮也加上槽函数,实现这几个相关的函数并测试:
void MainDialog::on_pushButton_clicked()
{
ui->menuFile->exec(QCursor::pos());
}
void MainDialog::on_actionThreePhaseFaultAtBus_triggered()
{
QMessageBox::warning(this, tr("warning"), tr("on_actionThreePhaseFaultAtBus_triggered"));
}
void MainDialog::on_actionThreePhaseFaultOnLine_triggered()
{
QMessageBox::warning(this, tr("warning"), tr("on_actionThreePhaseFaultOnLine_triggered"));
}
这就实现了最开始的界面效果,还真是简单啊。