문제

창에서 마우스 오른쪽 버튼을 클릭하면 컨텍스트 메뉴를 만들어야합니다. 그러나 나는 그것을 달성하는 방법을 정말로 모른다.

이를위한 위젯이 있습니까, 아니면 처음부터 만들어야합니까?

프로그래밍 언어 : 파이썬
그래픽 LIB : QT (PYQT)

도움이 되었습니까?

해결책

파이썬에 대해서는 말할 수 없지만 C ++에서는 매우 쉽습니다.

먼저 위젯을 만든 후 정책을 설정합니다.

w->setContextMenuPolicy(Qt::CustomContextMenu);

그런 다음 컨텍스트 메뉴 이벤트를 슬롯에 연결합니다.

connect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));

마지막으로 슬롯을 구현합니다.

void A::ctxMenu(const QPoint &pos) {
    QMenu *menu = new QMenu;
    menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
    menu->exec(w->mapToGlobal(pos));
}

그것이 C ++에서 수행하는 방법입니다. Python API에서는 너무 다르지 않아야합니다.

편집하다: Google을 둘러 보면 Python의 예제의 설정 부분이 있습니다.

self.w = QWhatever();
self.w.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)

다른 팁

툴바 및 컨텍스트 메뉴에서 작업을 사용하는 방법을 보여주는 또 다른 예.

class Foo( QtGui.QWidget ):

    def __init__(self):
        QtGui.QWidget.__init__(self, None)
        mainLayout = QtGui.QVBoxLayout()
        self.setLayout(mainLayout)

        # Toolbar
        toolbar = QtGui.QToolBar()
        mainLayout.addWidget(toolbar)

        # Action are added/created using the toolbar.addAction
        # which creates a QAction, and returns a pointer..
        # .. instead of myAct = new QAction().. toolbar.AddAction(myAct)
        # see also menu.addAction and others
        self.actionAdd = toolbar.addAction("New", self.on_action_add)
        self.actionEdit = toolbar.addAction("Edit", self.on_action_edit)
        self.actionDelete = toolbar.addAction("Delete", self.on_action_delete)
        self.actionDelete.setDisabled(True)

        # Tree
        self.tree = QtGui.QTreeView()
        mainLayout.addWidget(self.tree)
        self.tree.setContextMenuPolicy( Qt.CustomContextMenu )
        self.connect(self.tree, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu)

        # Popup Menu is not visible, but we add actions from above
        self.popMenu = QtGui.QMenu( self )
        self.popMenu.addAction( self.actionEdit )
        self.popMenu.addAction( self.actionDelete )
        self.popMenu.addSeparator()
        self.popMenu.addAction( self.actionAdd )

    def on_context_menu(self, point):

         self.popMenu.exec_( self.tree.mapToGlobal(point) )
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top