2011-01-27 29 views
8

Uygulamam için Qt Designer'da bir GUI oluşturdum ve python (2.6) koduna dönüştürdüm.QPushButton bağlamında contextMenu öğesini sağ tıklayın

QPushButton'un bazılarında (tasarımcıyla birlikte oluşturulur) Sağ tıklama bağlamı menüsü eklemek istiyorum. Menü seçenekleri uygulama durumuna göre değişir.

Böyle bir bağlam menüsü nasıl uygulanır?

cevap

14

Aşağıdaki örneklerin sizin için çalışıp çalışmadığını kontrol edin. En önemli şey CustomContextMenu için widget için set context menu policy etmektir ve küçük aracının customContextMenuRequested sinyale bağlanmaya: Cevabınız için

import sys 
from PyQt4 import QtGui, QtCore 

class MainForm(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
     super(MainForm, self).__init__(parent) 

     # create button 
     self.button = QtGui.QPushButton("test button", self)  
     self.button.resize(100, 30) 

     # set button context menu policy 
     self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 
     self.button.customContextMenuRequested.connect(self.on_context_menu) 

     # create context menu 
     self.popMenu = QtGui.QMenu(self) 
     self.popMenu.addAction(QtGui.QAction('test0', self)) 
     self.popMenu.addAction(QtGui.QAction('test1', self)) 
     self.popMenu.addSeparator() 
     self.popMenu.addAction(QtGui.QAction('test2', self))   

    def on_context_menu(self, point): 
     # show context menu 
     self.popMenu.exec_(self.button.mapToGlobal(point))   

def main(): 
    app = QtGui.QApplication(sys.argv) 
    form = MainForm() 
    form.show() 
    app.exec_() 

if __name__ == '__main__': 
    main() 
+0

Merhaba Serge, teşekkürler. Sorunumu sote görünüyor. Arthur. Sorununuzu çözerse – ArtDijk

+0

, pls, sorunuzun cevabını işaretleyin. –