QScintilla:如何将用户上下文菜单添加到textEdit? (C ++)

时间:2018-12-23 16:04:38

标签: c++ qt5 qscintilla

我正在努力告诉QScitilla textEdit(它是MainWindow应用程序的主要小部件)接受右键单击鼠标显示个性化上下文菜单。

如果我使用标准的Qt5 textEdit可以正常工作,如果与QScintilla替代方法一起使用会失败。我尝试通过一些操作来定义用户菜单:

void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);
    menu.addAction(cutAct);
    menu.addAction(copyAct);
    menu.addAction(pasteAct);
    menu.exec(event->globalPos());
}
#endif // QT_NO_CONTEXTMENU

对QContextMenuEvent起作用,但是仅当我右键单击MainWindow的元素而不是QScintilla textEdit时,菜单才会显示。当我在textEdit中进行操作时,仅显示标准的剪切/复制/粘贴菜单。

如何为QScintilla textEdit实现该功能?

1 个答案:

答案 0 :(得分:1)

有两种方法:

方法1:为QScintilla文本编辑的上下文菜单策略设置class ViewController: UIViewController { var myView: UIView! override func viewDidLoad() { super.viewDidLoad() myView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 200)) myView.center = self.view.center myView.isUserInteractionEnabled = true myView.backgroundColor = UIColor.red self.view.addSubview(myView) } func pToA (_ t:UITouch) -> CGFloat { let loc = t.location(in: myView) let c = myView.convert(myView.center, from:myView.superview!) return atan2(loc.y - c.y, loc.x - c.x) } var initialAngle = CGFloat(0) var angle = CGFloat(0) override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.initialAngle = pToA(touches.first!) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let ang = pToA(touches.first!) - self.initialAngle let absoluteAngle = self.angle + ang myView.transform = myView.transform.rotated(by: ang) self.angle = absoluteAngle } }

Qt::CustomContextMenu

方法2:定义QScintilla的子类,然后重新定义覆盖函数contextMenuEvent:

    textEdit->setContextMenuPolicy( Qt::CustomContextMenu );
    connect(textEdit, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(ShowContextMenu(const QPoint &)));

}

void MainWindow::ShowContextMenu(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);

    QAction action1("Action 1", this);
    connect(&action1, &QAction::triggered, this, []{
        qDebug() << "On action 1 click !!!";
    });

    contextMenu.addAction(&action1);
    contextMenu.exec(mapToGlobal(pos));
}