質問
ウィンドウを右クリックしてコンテキストメニューを作成する必要があります。しかし、それを達成する方法が本当にわかりません。
そのためのウィジェットはありますか、それとも最初から作成する必要がありますか?
プログラミング言語:パイソン
グラフィカル ライブラリ:Qt (PyQt)
解決
Python については話せませんが、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) )
所属していません StackOverflow