我使用 Qt creator 中的设计器创建了一个图形视图。
层次结构如下:
当我在图形视图区域中右键单击时,没有任何反应(这是默认行为 afaik)。由于我尝试在右键单击时显示下拉菜单但无法使其正常工作,因此我添加了一个连接和自定义插槽。
这是我的代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
MainWindow:: makePlot();
=
ui->graphView->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->graphView ,SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(on_graphView_customContextMenuRequested(const QPoint &)));
scene = new QGraphicsScene();
ui->graphView->setScene(scene);
...
}
以及被调用来处理菜单的槽函数:
`
void MainWindow::on_graphView_customContextMenuRequested(const QPoint &pos)
{
qDebug() << " custom menuu!!!!!!!!!"<< "##"<< pos.x() << " ; "<< pos.y();
// QMenu menu(this);
// menu.addAction("...1");
// menu.addAction("...2");
// menu.exec(pos);
}
`
问题:
每次右键单击时,我的控制台上都会打印两次 qdebug 字符串,为什么会发生这种情况?它应该只出现一次...
我正在我的场景中绘制 Qgraphicsitems,即使我右键单击绘制的项目而不仅仅是场景中的空白区域,on_graphView_customContextMenuRequested 似乎也被触发,我如何让它仅针对图形视图触发,在顶部没有任何东西的区域(场景上没有项目叠加)。
pos 中的坐标是相对于 graphview 尺寸的,因此当我取消注释上述代码中的 menu.exec
时,菜单显示在错误的位置。如何将我的 pos 转换为相对于整个 Windows 而不仅仅是图形视图的全局坐标。
答案 0 :(得分:2)
它获得 2 次展示,因为 on_graphView_customContextMenuRequested 槽被调用了 2 次,因为有 2 个连接。第一个连接是通过使用 uic 工具使用 .ui 生成 C++ 代码的 QtDesigner 建立的连接,如果插槽名称符合 void on_<object name>_<signal name>(<signal parameters>);
规则,则此连接是自动的(参见 this ),第二个连接是您在代码中显示的连接。有几个选项:
1.1 更改插槽名称。
1.2 删除您显示的连接。
customContextMenuRequested 信号无论是否有项目都会发出,这种情况下的解决方案是过滤是否有项目。
exec() 方法必须使用全局位置,但 customContextMenuRequested 信号传递相对于发出信号的小部件的位置,因此您必须将其转换为全局位置。
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->graphView->setContextMenuPolicy(Qt::CustomContextMenu);
scene = new QGraphicsScene();
ui->graphView->setScene(scene);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_graphView_customContextMenuRequested(const QPoint &pos)
{
if(ui->graphView->itemAt(pos))
return;
QMenu menu(this);
menu.addAction("...1");
menu.addAction("...2");
menu.exec(ui->graphView->mapToGlobal(pos));
}