Qt/PyQt: How do I create a drop down widget, such as a QLabel, QTextBrowser, etc.?


Question

How do I create a drop-down widget, such as a drop-down QLabel, drop-down QTextBrowser, etc.?

For example, I log information in a QTextBrowser, but I don't want it taking up space on the screen. So I want to be able to click a QToolbutton and have a scrollable QTextBrowser drop-down. (A QComboBox would work too, but I can't just add each event as a separate item - I need the text to wrap, not be elided. Thus a drop-down QTextBrowser.)

Or, for example, I want a drop-down QLabel containing a picture, etc...

1
5
4/12/2014 4:52:54 AM

Accepted Answer

Create a QWidgetAction for the drop-down widget, and add it to the tool-button's 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_())
15
1/10/2017 2:43:31 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon