PyQt学习笔记(6)——Actions and Key Sequences

来源:互联网 发布:sqlyog修改数据库密码 编辑:程序博客网 时间:2024/05/13 21:31

Qt中,目前我认为做的最好的两种机制就是:SIGNAL and SLOTSActions and Key Sequences

Actions and Key Sequence我对他的理解就是各种动作带来的核心一致反应。举个例子:

比如我们在应用程序中常见的“新建文件”这一功能,他的实现可以通过下面几种方式:

1 点击菜单:File->New菜单项

2 点击工具栏:new的图标

3 键盘快捷方式:如Ctrl+N

上面的这三种actions,其实带来的结果(Sequence)是一样的,就是新建文件,那么在程序中如何做到三者的统一和同步,Qt给了很好的解决方法。在PyQt中,它把类似上面的actions封装(encapsulates)到一个Qactionclass中,下面举个例子:(windows环境下)

#!/usr/bin/env python

#coding=utf-8

 

import sys

from PyQt4.QtCore import *

from PyQt4.QtGui import *                    

 

class MainWindow(QMainWindow):

    def __init__(self,parent=None):

        super(MainWindow,self).__init__(parent)

 

        fileNewAction=QAction(QIcon("./images/filenew.png"),"&New",self)

        fileNewAction.setShortcut(QKeySequence.New)

        helpText = "Create a new file"

        fileNewAction.setToolTip(helpText)

        fileNewAction.setStatusTip(helpText)

        self.connect(fileNewAction,SIGNAL("triggered()"),self.fileNew)

 

        self.fileMenu = self.menuBar().addMenu("&File")

        self.fileMenu.addAction(fileNewAction)

 

        filetoolbar = self.addToolBar("File")

        filetoolbar.addAction(fileNewAction)

            

        self.status = self.statusBar()

        self.status.showMessage("This is StatusBar",5000)

        self.setWindowTitle("PyQt MianWindow")

      

    def fileNew(self):

        self.status.showMessage("You have created a new file!",9000)

def main():

    app = QApplication(sys.argv)

    app.setApplicationName("PyQt MianWindow")

    app.setWindowIcon(QIcon("./images/icon.png"))

    form = MainWindow()

    form.show()

    app.exec_()

 

main()

上面程序的目的就是:要让点击菜单newCtrl+N,点击工具栏new按钮三种action都执行一个命令fileNew()。

其中红色部分就是Qaction部分,其中的QKeySequence.New 就是基本多平台都统一使用的新建的响应快捷键Ctrl+N,如果我们需要的快捷键没有,那么我们可以自己设置,就是填写快捷键的名称比如:fileNewAction.setShortcut(Ctrl+N)。把这个action都给了菜单new和工具栏,通过connect绑定,他们都执行同一响应。

从上面可以看到,每次创建一个QAction都需要五六行,如果在一个应用程序中都这么创建会很费时间的,所以我们可以写一个函数来封装这一功能:
     def createAction(self,text,slot=None,shortcut=None, icon=None,

               tip=None,checkable=False,signal="triggered()"):

        action = QAction(text, self)

        if icon is not None:

            action.setIcon(QIcon("./images/%s.png" % icon))

        if shortcut is not None:

            action.setShortcut(shortcut)

        if tip is not None:

            action.setToolTip(tip)

            action.setStatusTip(tip)

        if slot is not None:

            self.connect(action, SIGNAL(signal), slot)

        if checkable:

            action.setCheckable(True)

        return action

有了这个函数以后,我们可以定义上面的fileNewAction了:

fileNewAction = self.createAction("&New...", self.fileNew,

                QKeySequence.New, "filenew", "Create an image file")

一句话搞定。QKeySequence.New也可以用Ctrl+n代替

原创粉丝点击