一、控件

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'
'\xe4\xb8\xad\xe6\x96\x87'
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:\Users\admin\Documents'
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:\study\pyqt_project\demo2\dist)
--workpath=WORKPATH Where to put all the temporary work files, .log, .pyz
and etc. (default: D:\study\pyqt_project\demo2\build)
-y, --noconfirm Replace output directory (default:
SPECPATH\dist\SPECNAME) 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

python pyqt的更多相关文章

  1. 搭建python+PyQt+Eric平台

    搭建python+PyQt+Eric平台 预备安装程序: 2.1.下载Python3.2 官方网站:http://www.python.org/ 下载地址:http://www.python.org/ ...

  2. python(pyqt)开发环境搭建

    eric+pyqt 安装(python开发工具) 更多 0 Python python Eric是一个开源的.跨平台的python&ruby集成开发环境,基于python和pyqt运行.eri ...

  3. Python & PyQt学习随笔:PyQt主程序的基本框架

    在完成UI设计将UI通过PyUic转成Py文件后,由于这个生成的文件每次通过PyUic生成时都会被覆盖,因此应用的主程序必须另外单独编写py文件.需要将UI生成的文件import到主程序的py文件中. ...

  4. Python+PyQt 数据库基本操作

    Sqlite: 使用Python的sqlite3: 需要注意下commit方式与qt稍有不同 import sqlite3 class DBManager(): def __init__(self): ...

  5. 人工智能-动物识别专家系统算法Python + Pyqt 实现

    一.基础知识库 有毛发 哺乳动物 - 有奶 哺乳动物 - 有羽毛 鸟 - 会飞 会下蛋 鸟 - 吃肉 食肉动物 - 有犬齿 有爪 眼盯前方 食肉动物 - 哺乳动物 有蹄 有蹄类动物 - 哺乳动物 反刍 ...

  6. python pyqt绘制直方图

    # -*- coding: utf-8 -*- """ In this example we draw two different kinds of histogram. ...

  7. Python——PyQt GUI编程(python programming)

    import sys from math import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidg ...

  8. python pyqt面板切换

  9. [Python[PyQt]] ModuleNotFoundError: No module named 'PyQt5.QtWebEngineWidgets'

    解决办法: pip install PyQtWebEngine

随机推荐

  1. Sqlite数据库添加数据以及查询数据方法

    只是两个添加查询方法而已,怕时间长不用忘了

  2. UX是什么?

    UX(用户体验),操作过安卓手机或者苹果手机的系统吧?那么操作过程的整体体验就叫UX,而操作过程中所看到的界面颜色啦,图案,字体大小啦等等都属于UI设计,而交互设计(Interaction Desig ...

  3. 探究JVM和GC

    1.Java堆中各代分布: 图1:Java堆中各代分布 Young:主要是用来存放新生的对象. Old:主要存放应用程序中生命周期长的内存对象. Permanent:是指内存的永久保存区域,主要存放C ...

  4. 通过修改my.ini配置文件来解决MySQL 5.6 内存占用过高的问题

    打开后台进程发现mysql占用的内存达到400+M. 修改一下my.ini这个配置文件的配置选项是可以限制MySQL5.6内存占用过高这一问题的,具体修改选项如下: performance_schem ...

  5. JAVA课程设计个人博客 学生成绩管理 201521145048 林健

    1. 团队课程设计博客链接 http://www.cnblogs.com/kawajiang/p/7062407.html 2.个人负责模块或任务说明 本人主要负责支持用户登录.验证操作,显示设计界面 ...

  6. 201521123108《Java程序设计》第12周学习总结

    1. 本周学习总结 2. 书面作业 将Student对象(属性:int id, String name,int age,double grade)写入文件student.data.从文件读出显示. Q ...

  7. Java项目生成Jar文件

    打开 Jar 文件向导 Jar 文件向导可用于将项目导出为可运行的 jar 包. 打开向导的步骤为: 在 Package Explorer 中选择你要导出的项目内容.如果你要导出项目中所有的类和资源, ...

  8. linux系统命令<一>----关机重启

    1.shutdown shutdown -h now   立刻关机 shutdown -h 20:00    20:00关机 shutdown -h +10   十分钟后关机 shutdown -r ...

  9. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】

    什么是EL表达式? 表达式语言(Expression Language,EL),EL表达式是用"${}"括起来的脚本,用来更方便的读取对象! EL表达式主要用来读取数据,进行内容的 ...

  10. Python编码_ASCII_Unicode_UTF-8

    获取一个字符的ASCII码值,使用内置函数 ord(),ASCII码占一个字节 ascii不能存中文 >>> # A 和 a 分别的对应的ASCII码值是 >>> ...