在PyQt5中,可以通过使用QToolBar
和QToolButton
来创建工具栏和工具栏按钮。要在点击工具栏按钮时显示下拉菜单,你可以将QToolButton
的下拉菜单设置为QMenu
。下面是一个简单的示例代码:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolBar, QAction, QMenu, QToolButton,
QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建工具栏
toolbar = self.addToolBar("Toolbar")
# 创建工具栏按钮
tool_button = QToolButton()
tool_button.setText("菜单")
tool_button.setPopupMode(QToolButton.MenuButtonPopup)
# 创建下拉菜单
menu = QMenu(self)
menu.addAction("选项1")
menu.addAction("选项2")
menu.addAction("选项3")
menu.addAction("选项4")
# 设置工具栏按钮的下拉菜单
tool_button.setMenu(menu)
# 将工具栏按钮添加到工具栏
toolbar.addWidget(tool_button)
# 设置主窗口的中心部件
label = QLabel("主窗口")
self.setCentralWidget(label)
self.setWindowTitle("下拉菜单示例")
self.setGeometry(300, 300, 300, 200)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
在这个示例中,我们首先创建了一个QToolBar
作为主窗口的工具栏。然后,我们创建了一个QToolButton
并将其添加到工具栏中。通过调用setPopupMode(QToolButton.MenuButtonPopup)
,我们告诉QToolButton
在点击时显示下拉菜单。接下来,我们创建了一个QMenu
作为下拉菜单,并使用addAction()
方法添加了一些选项。最后,我们将下拉菜单设置为工具栏按钮的菜单,通过调用setMenu()
方法。