QT生成右键菜单栏
ui.lineEdit->setContextMenuPolicy(Qt::CustomContextMenu);
setContextMenuPolicy方法用来设置widget菜单项的显示方法,而CustomContextMenu是唯一与右键菜单有关的参数,因此这里我们将菜单显示方法设置为该类型。如果widget设置为CustomContextMenu时,当在数据上点击右键时就会发送customContextMenuRequested ( const QPoint & pos )信号,该信号还会捕捉到点击右键的位置,并用pos参数来存储。
connect(ui.lineEdit,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(ShowLineEditMenu(QPoint)));
我们首先将菜单选项action添加到右键弹出菜单popMenu中,再通过exec方法在pos()位置显示该右键菜单,pos()返回的位置即为点击鼠标的位置。
m_Act1 = new QAction(tr("From0KV"), this);
m_Act2 = new QAction(tr("From 30KV"), this);
connect(m_Act1,SIGNAL(triggered()),this, SLOT(on_btnAct1_clicked()));
connect(m_Act2,SIGNAL(triggered()),this, SLOT(on_btnAct2_clicked()));
void Widget::ShowLineEditMenu(const QPoint &pos)
{
// 定义一个右键弹出菜单
QMenu*menu = new QMenu();
menu->addSeparator();
menu->addSeparator();
// 往菜单内添加QAction
menu->addAction(Act1);
menu->addSeparator();
menu->addSeparator();
menu->addAction(Act2);
menu->addSeparator();
menu->addSeparator();
//set menustyle
menu->setStyleSheet(getStyleSheet("Menu.qss"));
// 弹出右键菜单,菜单位置为光标位置
menu->exec(QCursor::pos());
delete menu;
}
void Widget::on_btnAct1_clicked()
{
m_Value= 0;
m_Act1->setEnabled(false);
m_Act2->setEnabled(true);
}
void Widget::on_btnAct2_clicked()
{
m_Value= 1;
m_Act1->setEnabled(true);
m_Act2->setEnabled(false);
}