2012-01-31 5 views
5

Come si crea un widget a discesa, ad esempio una QLabel a discesa, un QTextBrowser a discesa, ecc.?Qt/PyQt: Come posso creare un widget a discesa, come QLabel, QTextBrowser, ecc.?

Ad esempio, registro le informazioni in un QTextBrowser, ma non voglio che occupi spazio sullo schermo. Quindi voglio essere in grado di fare clic su un QToolbutton e avere un menu a discesa scorrevole QTextBrowser. (Potrebbe funzionare anche un QComboBox, ma non posso semplicemente aggiungere ogni evento come elemento separato: ho bisogno che il testo sia avvolto, non elidato. Quindi un QTextBrowser a discesa.)

Oppure, ad esempio, I vogliono un menu a discesa QLabel contenente una foto, ecc ...

risposta

14

Creare un QWidgetAction per il widget a discesa, e aggiungerlo al di la-pulsante dello strumento menu:

from PyQt4 import QtGui, QtCore 

class Window(QtGui.QWidget): 
    def __init__(self): 
     QtGui.QWidget.__init__(self) 
     layout = QtGui.QHBoxLayout(self) 
     self.button = QtGui.QToolButton(self) 
     self.button.setPopupMode(QtGui.QToolButton.MenuButtonPopup) 
     self.button.setMenu(QtGui.QMenu(self.button)) 
     self.textBox = QtGui.QTextBrowser(self) 
     action = QtGui.QWidgetAction(self.button) 
     action.setDefaultWidget(self.textBox) 
     self.button.menu().addAction(action) 
     layout.addWidget(self.button) 

if __name__ == '__main__': 

    import sys 
    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.resize(100, 60) 
    window.show() 
    sys.exit(app.exec_())