Qt/PyQt: 如何创建下拉控件,如 QLabel、QTextBrowser 等?

6 投票
1 回答
18066 浏览
提问于 2025-04-17 12:00

我该如何创建一个下拉小部件,比如下拉的 QLabel、下拉的 QTextBrowser 等等?

举个例子,我在一个 QTextBrowser 里记录信息,但我不想让它占用屏幕空间。所以我想点击一个 QToolButton,然后让一个可以滚动的 QTextBrowser 下拉出来。(QComboBox 也可以,但我不能把每个事件都作为单独的选项添加进去——我需要文本能够换行,而不是被截断。因此我需要一个下拉的 QTextBrowser。)

再比如,我想要一个下拉的 QLabel,里面包含一张图片等等……

1 个回答

17

为下拉控件创建一个 QWidgetAction,然后把它添加到工具按钮的 菜单 中:

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_())

撰写回答