直接上代码,我们用到了一个eventfilter的函数功能。这个函数比较厉害和重要,大家务必经常拿出来看看。
void MainWindow::initMenu()
{
QMenu* menuLiXiang = new QMenu;
QAction* actXiangMuZhangCheng = new QAction("项目章程");
menuLiXiang->addAction(actXiangMuZhangCheng);
ui->btnLiXiang->setMenu(menuLiXiang);
ui->btnLiXiang->setArrowType(Qt::RightArrow);
menuLiXiang->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject * obj, QEvent *event)
{
if (event->type() == QEvent::Show && obj == ui->btnLiXiang->menu())
{
QPoint pos = ui->btnLiXiang->mapToGlobal(ui->btnLiXiang->rect().topRight());
ui->btnLiXiang->menu()->move(pos);
return true;
}
return false;
}