Python PyQt菜单的动态填充

Python (225) 2023-04-16 02:23:30

为了继续开发示例应用程序,假设您需要在_文件_下创建_打开最近的_子菜单,并动态填写最近打开的文件或文档。因此,需要操作以下步骤:

1、在_File_下创建_Open最近的_子菜单。

2、编写动态生成操作,填写菜单的定制插槽。

3、连接.aboutToShow()菜单信号和自定义插槽。

实例

fromfunctoolsimportpartial
#Snip...

classWindow(QMainWindow):
#Snip...
defpopulateOpenRecent(self):
#Step1.Removetheoldoptionsfromthemenu
self.openRecentMenu.clear()
#Step2.Dynamicallycreatetheactions
actions=[]
filenames=[f"File-{n}"forninrange(5)]
forfilenameinfilenames:
action=QAction(filename,self)
action.triggered.connect(partial(self.openRecentFile,filename))
actions.append(action)
#Step3.Addtheactionstothemenu
self.openRecentMenu.addActions(actions)

以上就是Python PyQt菜单的动态填充的方法,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复