python pyqt

一、控件

1.单行文本框QLineText

clear() 清除文本框中的内容
contextMenuEvent() 右键菜单事件
copy() 复制文本框中的内容
cut() 剪切文本框中的内容
paste() 向文本框中粘贴内容
redo() 重做
selectAll() 全选
selectedText() 获得选中的文本
setAlignment() 设置文本对齐方式
setEchoMode() 设置文本框类型
->setEchoMode(QtGui.QLineEdit.Password) 将其设置为密码框
setMaxLength() 设置文本框中最大字符数
setText() 设置文本框中的文字
text() 获取文本框中的文字
undo() 撤销

2.多行文本框QTextEdit

append() 向文本框中追加内容
clear() 清除文本框中的内容
contextMenuEvent() 右键菜单事件
copy() 复制文本框中的内容
cut() 剪切文本框中的内容
find() 查找文本
paste() 向文本框中粘贴内容
redo() 重做
selectAll() 全选
selectedText() 获得选中的文本
setAlignment() 设置文本对齐方式
setText() 设置文本框中的文字
toPlainText() 获取文本框中的文字
undo() 撤销

3.文本浏览器QTextBrowser

多行文本框textBrowser,从QTextEdit中继承而来,方法可共用。

append(my_str) 文本的添加
toPlainText() 文本的获取
clear() 文本的清除

4.单选Radio Button

4.1互斥:

可以使用Group Box进行分组,组内进行互斥。

4.2检测是否被按下:

radioButton.isChecked()

4.3设置default值:

选择控件的属性编辑器,勾选其中的checked.

4.4多个Radio Button联动:

radioButton.setChecked(True)

5.手轮控件Dial

5.1槽函数为on_dial_valueChanged()

5.2最大值、最小值、步进的设置:

控件属性中可设置

6.数码管ledNumber

6.2显示数字:

ledNumber.display(value)

7.水平拖动条Horizontal Slider

7.1槽函数:on_horizontalScrollBar_valueChanged()

7.2最大值、最小值、步进的设置:

控件属性中可设置

8.垂直拖动条Vertical Slider

8.1槽函数:

9.对话框

9.1通知对话框QMessageBox.information('information',u'这是一个通知对话框')

9.2提问对话框QMessageBox.question('question',u'是否需要保存','OK','NO')

9.3警告对话框QMessageBox.warning()    #参数同上

9.4严重警告对话框QMessageBox.critical() #参数同上

9.5关于对话框QMessageBox.about()       #参数同上

9.6关于QT QMessageBox.aboutQt(u'关于QT') 

10.输入框

10.1获取整数QInputDialog.getInteger(u'标题',u'提示信息',default,mix,max)

10.2获取字符串QInputDialog.getText(u'标题',u'提示信息',QLineEdit.Normal, u'默认字符串')

10.3获取浮点型QInputDialog.getDouble(u'标题',u'提示信息',default,mix,max) 

10.4获取列表QInputDialog.getItem(u'标题',u'提示信息',my_list)

使用list之前请先定义:

my_list = QStringList()
my_list.append('apple')
my_list.append('orange')
my_list.append('banana')

如上四个方法均返回两个参数:my_choice,return_code

  

11.自定义输入对话框

用到的几个控件:label,lineEdit,comboBox,pushButton

用到控件函数:

10.1 lineEdit.text()

10.2 comboBox.currentText()

12.程序启动界面

程序启动前使用函数:

splash = QSplashScreen(QPixmap("图片路径"))

splash.show()

主窗口调用

splash.finish()

二、字符编码问题

集中编码介绍:

1、ASCII(一个字节)

2、GBK(两个字节)

GB2312 可表示6K个字

GB18030 表示的字超过20K

3、Unicode(两个字节)

1.多行文本框获取其中文文本时,提示如下错误:

"ascii" codec can`t encode characters in positon 0-10:ordina not in range(128)

这个错误是很常见的字符编码错误,可以手动复制到:

import sys
print sys.getdefaultencoding()

reload(sys)
sys.setdefaultencoding('utf8')
print sys.getdefaultencoding()

str(r'中文')

运行结果:

’ascii'
'utf8'
'xe4xb8xadxe6x96x87'
reload(sys)
sys.setdefaultencoding('ascii')
str(r'中文')

运行结果:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordin
al not in range(128)

所以中文字符串使用print语句打印的时候,需要转换为Unicode

方法一:

unicode(lineEdit.text())

方法二:

u'%s' %(lineEdit.text())  

方法三:

代码前面加上

import sys

reload(sys)

sys.setdefaultencoding('utf8')

写爬虫程序时,原代码使用哪种编码,解码时需使用同样的编码方式!!!  

三、添加菜单栏  

1. “Qt设计师”中右击“添加菜单栏”,依次添加文件、编辑、帮助;然后依次添加其子菜单。

2. ico图标的添加

 “Qt设计师” -> “资源浏览器” -> 添加ico资源

3. 先选择子菜单(如“文件”中“打开”) -> “属性编辑器” -> “ico”中选择图标

4.Eric4中添加资源(之前添加过就不需要再次添加),右击选择编译。

5."Forms"中编译

6.添加槽函数on_action_triggered()  

四、打开文件并读取数据

注:我们的操作系统一般是中文的,字符串采用'gbk‘进行编码;中英文混合时采用’utf8'编码。

Python控制台默认使用ascii编码。

QT使用unicode编码,文本框、按钮标题有中文时需要print时,需要用unicode(str)

使用时需要进行相应解码!!!

4.1 文件打开对话框QtGui.QFileDialog.getOpenFileName()

原型:

QString QFileDialog.getOpenFileName (QWidget parent = None, QString caption = QString(), QString directory = QString(), QString filter = QString(), Options options = 0)

Eg:

my_file_path = QtGui.QFileDialog.getOpenFileName(self, u'打开一个文件', './')
print unicode(my_file_path)
fp = open(unicode(my_file_path))
my_file_data = fp.read()
fp.close()
self.textBrowser.append(my_file_data.decode('gbk'))

注:my_file_path的类型为<class 'PyQt4.QtCore.QString'>,QString为Eric4返回的字符串,Python无法直接使用,所以如上代码需要通过unicode函数进行转换,这点需要注意。

4.2 文件保存对话框QtGui.QFileDialog.getSaveFileName()

原型:

QString QFileDialog.getSaveFileName (QWidget parent = None, QString caption = QString(), QString directory = QString(), QString filter = QString(), Options options = 0)

Eg:

my_file_path = QtGui.QFileDialog.getSaveFileName(self, u'保存文件', './')
print unicode(my_file_path)
fp = open(unicode(my_file_path), 'w')
my_data = self.textBrowser.toPlainText()
fp.write(unicode(my_data).encode('utf8'))
fp.close()

4.3 常见错误说明:

4.3.1 如上第5行代码改为fp.write(my_data.encode('utf8')) 错误如下:

 

4.3.2 如上第5行代码改为fp.write(my_data) 保存的文件中(实际字符串为PyQt4学习)将出现乱码:

 4.4 文件夹选择对话框QtGui.QFileDialog.getExistingDirectory

原型:

QString QFileDialog.getExistingDirectory (QWidget parent = None, QString caption = QString(), QString directory = QString(), Options options = QFileDialog.ShowDirsOnly)

Eg:

from PyQt4.QtGui import *

my_dir = QtGui.QFileDialog.getExistingDirectory(self,u'选择文件夹','./')
print unicode(my_dir)

注意:如上Dialog的代码均在Eric4中实验,非Python的idle

文件夹选择之后就需要遍历文件夹,如下代码请参考:

#coding:utf-8
import os
import os.path
rootdir = r'C:UsersadminDocuments'
for parent,dirnames,filenames in os.walk(rootdir):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
    for dirname in  dirnames:                         #输出文件夹信息
        print "parent is:" + parent
        print  "dirname is:" + dirname

    for filename in filenames:                        #输出文件信息
        print "parent is:" + parent
        print "filename is:" + filename
        print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息

五、Python读取word文档  

5.1 Win32扩展包(只对Windows有效)

from win32com import client as wc

my_file_path = r'D:/study/pyqt_project/demo2/www.docx'
word = wc.Dispatch('Word.Application')
word.Visible = 0
word.DisplayAlerts = 0
my_word_doc = word.Documents.Open(unicode(my_file_path).replace(u'/', u'\'))
my_word_count = my_word_doc.Paragraphs.Count
for each in range(my_word_count):
    my_word_context = my_word_doc.Paragraphs[each].Range
    print my_word_context.text
word.Quit()

使用win32com打开word速度实在太慢了,建议大家使用python-docx 

5.2 python-docx

  1. 跨平台的,Windows、Linux、Mac均可使用
  2. 读取docx速度较快
  3. 函数名易于记忆,win32com.client的方法、实例变量用起来很别扭
import docx

doc = docx.Document(r'D:\study\pyqt_project\demo2\www.docx')
for each_para in doc.paragraphs:
    print each_para.text

运行结果:

News.realsil.com.cn
瑞晟微电子有限公司

 5.3 xlrd

  1. 跨平台的,Windows、Linux、Mac均可使用
  2. 只能读excel,不能写,速度很快
from xlrd import open_workbook

print 'open excel and exec'
wb = open_workbook(r'D:\study\pyqt_project\demo2\test.xlsx')
for each_sheet in wb.sheets():
    for each_row in range(each_sheet.nrows):
        for each_col in range(each_sheet.ncols):
            print each_sheet.cell(each_row, each_col).value    

 六、打包pyqt程序

6.1 py2exe

  • 只能在Windows平台打包
  • 不能打包为单个文件,为一个文件夹,包含各种dll和资源

6.2 pyinstaller 

  • windows平台下运行,依赖pywin32扩展包。另外这个工具是跨平台的,Linux、ios同样可以运行
  • 可打包为单个文件,或者一个文件夹
  • 可指定二进制文件的图标
  • gui程序打包后运行无dos窗口

注:打包为单个文件,运行时会创建_MExxxx临时文件夹(隐藏的),有bootloader复制文件,运行结束后自动删除。意外关闭,临时文件无法删除。

所以这种方式运行速度变慢,但看来简洁一些。

6.2.1 安装

建议安装版本PyInstaller-2.1

6.2.2 运行

用法: pyinstaller-script.py [opts] <scriptname> [ <scriptname> ...] | <specfile>

输入pyinstaller --help可查看帮助文档

Options:
  -h, --help            show this help message and exit
  -v, --version         Show program version info and exit.
  --distpath=DIR        Where to put the bundled app (default:
                        D:studypyqt_projectdemo2dist)
  --workpath=WORKPATH   Where to put all the temporary work files, .log, .pyz
                        and etc. (default: D:studypyqt_projectdemo2uild)
  -y, --noconfirm       Replace output directory (default:
                        SPECPATHdistSPECNAME) without asking for
                        confirmation
  --upx-dir=UPX_DIR     Path to UPX utility (default: search the execution
                        path)
  -a, --ascii           Do not include unicode encoding support (default:
                        included if available)
  --clean               Clean PyInstaller cache and remove temporary files
                        before building.
  --log-level=LOGLEVEL  Amount of detail in build-time console messages
                        (default: INFO, choose one of DEBUG, INFO, WARN,
                        ERROR, CRITICAL)

  What to generate:
    -F, --onefile       Create a one-file bundled executable.
    -D, --onedir        Create a one-folder bundle containing an executable
                        (default)
    --specpath=DIR      Folder to store the generated spec file (default:
                        current directory)
    -n NAME, --name=NAME
                        Name to assign to the bundled app and spec file
                        (default: first script's basename)

  What to bundle, where to search:
    -p DIR, --paths=DIR
                        A path to search for imports (like using PYTHONPATH).
                        Multiple paths are allowed, separated by ';', or use
                        this option multiple times
    --hidden-import=MODULENAME
                        Name an import not visible in the code of the
                        script(s). This option can be used multiple times.
    --additional-hooks-dir=HOOKSPATH
                        An additional path to search for hooks. This option
                        can be used multiple times.
    --runtime-hook=RUNTIME_HOOKS
                        Path to a custom runtime hook file. A runtime hook is
                        code that is bundled with the executable and is
                        executed before any other code or module to set up
                        special features of the runtime environment. This
                        option can be used multiple times.

  How to generate:
    -d, --debug         Tell the bootloader to issue progress messages while
                        initializing and starting the bundled app. Used to
                        diagnose problems with missing imports.
    -s, --strip         Apply a symbol-table strip to the executable and
                        shared libs (not recommended for Windows)
    --noupx             Do not use UPX even if it is available (works
                        differently between Windows and *nix)

  Windows and Mac OS X specific options:
    -c, --console, --nowindowed
                        Open a console window for standard i/o (default)
    -w, --windowed, --noconsole
                        Windows and Mac OS X: do not provide a console window
                        for standard i/o. On Mac OS X this also triggers
                        building an OS X .app bundle.This option is ignored in
                        *NIX systems.
    -i FILE.ico or FILE.exe,ID or FILE.icns, --icon=FILE.ico or FILE.exe,ID or FILE.icns
                        FILE.ico: apply that icon to a Windows executable.
                        FILE.exe,ID, extract the icon with ID from an exe.
                        FILE.icns: apply the icon to the .app bundle on Mac OS
                        X

  Windows specific options:
    --version-file=FILE
                        add a version resource from FILE to the exe
    -m FILE or XML, --manifest=FILE or XML
                        add manifest FILE or XML to the exe
    -r FILE[,TYPE[,NAME[,LANGUAGE]]], --resource=FILE[,TYPE[,NAME[,LANGUAGE]]]
                        Add or update a resource of the given type, name and
                        language from FILE to a Windows executable. FILE can
                        be a data file or an exe/dll. For data files, at least
                        TYPE and NAME must be specified. LANGUAGE defaults to
                        0 or may be specified as wildcard * to update all
                        resources of the given TYPE and NAME. For exe/dll
                        files, all resources from FILE will be added/updated
                        to the final executable if TYPE, NAME and LANGUAGE are
                        omitted or specified as wildcard *.This option can be
                        used multiple times.

  Obsolete options (not used anymore):
    -X, -K, -C, -o, --upx, --tk, --configfile, --skip-configure, --out, --buildpath
                        These options do not exist anymore.

 先来一个简单的:

pyinstaller script.py

 打包为单个文件:

pyinstall script.py -F

 打包为单个文件,无控制台黑框:

pyinstall script.py -F -w
原文地址:https://www.cnblogs.com/hester/p/5450134.html