一、控件

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 "", line 1, in

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的类型为,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

跨平台的,Windows、Linux、Mac均可使用

读取docx速度较快

函数名易于记忆,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

跨平台的,Windows、Linux、Mac均可使用

只能读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] [ ...] |

输入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

pyqt在python里是啥_python pyqt相关推荐

  1. python数码时钟代码_Python+Pyqt实现简单GUI电子时钟

    本文实例为大家分享了Python+Pyqt实现简单GUI电子时钟的具体代码,供大家参考,具体内容如下 突发奇想想用GUI做一个简单的电子时钟界面,利用pyqt模块也很方便,代码如下: from PyQ ...

  2. python怎么显示结果_python - pyqt如何显示实时数据

    问 题 我有一个处理example.csv的后台程序,现在想把当前读行数实时显示到GUI界面中去. 就是这下面 能否提供一些思路,谢谢! 解决方案 PyQt的signal-slot机制不就是干这个的吗 ...

  3. python里的拼接_Python拼接字符串的7种方法总结

    前言 忘了在哪看到一位编程大牛调侃,他说程序员每天就做两件事,其中之一就是处理字符串.相信不少同学会有同感. 在Python中,我们经常会遇到字符串的拼接问题,几乎任何一种编程语言,都把字符串列为最基 ...

  4. install在python里什么意思_python setup.py install是什么意思

    python setup.py install是什么意思? python setup.py install 是我们用来安装下载的python包或者自己按照python官方规范开发的扩展包的常用指令. ...

  5. python里怎么输入θ_Python笔记——输入输出

    输出 用print()在括号中加上字符串,就可以向屏幕上输出指定的文字.比如输出'hello, world',用代码实现如下: >>> print('hello, world') p ...

  6. 求根公式在python里怎么表达_python求根公式

    len(x) 击败 x.len(),从内置函数看 Python 的设计思想 内置函数是 Python 的一大特色,用极简的语法实现很多常用的操作. 它们预先定义在内置命名空间中,开箱即用,所见即所得. ...

  7. python里的非_python中逻辑非

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! python逻辑运算的简介以及使用~ 逻辑运算在程序开发中,通常 在判断条件时, ...

  8. python里isalpha函数_Python isalpha函数判断字母

    Python isalpha() 方法检测字符串是否只由字母组成. Case 1: 纯字母 info = 'abcd' print(info.isalpha()) 返回结果是True Case 2: ...

  9. argument在python里什么意思_python add_argument() 的使用方法

    介绍: argparse argparse 是 Python 内置的一个用于命令项选项与参数解析的模块,通过在程序中定义好我们需要的参数,argparse 将会从 sys.argv 中解析出这些参数, ...

最新文章

  1. SUBSTRING函數用法
  2. Saltstack 用户管理
  3. 生信小白7行代码画一个高颜值的世界地图
  4. html月球绕地球转,CSS3地球公转,月球绕地球转
  5. 库克笑了,说要给股东多分红:换了M1后Mac销售额增长70%,iPhone也增长66%
  6. 遍历map几种方式及应用
  7. DF以某一列的元素筛选其中属于某个集合的元素的所有行(2个版本函数)
  8. python pandas空值与缺失值处理
  9. flutter 国际化_Flutter 开发实战资源推荐
  10. linux文件系统 环形结构图,环形缓冲器(转)
  11. vue中使用高德地图 amap--基础使用方法
  12. 荣耀8获吉尼斯世界纪录!18425米高空直播体验
  13. 【李宏毅机器学习】01:机器学习介绍 Introduction
  14. 虐哭无数人的烧脑刑侦科推理题,程序员一秒解
  15. java串口rxtx的若干坑
  16. 求字符串长度的函数的几种实现方法
  17. 【Android】使用MPAndroidChart过程中BarChart的几点心得
  18. mysql archer,archer安装及使用
  19. paper:DeepAR: Probabilistic forecasting with autoregressive recurrent networks DeepAR模型
  20. 查询你的手机或者邮箱注册过那些网站

热门文章

  1. Kubernetes 1.6集群部署
  2. html转成16进制数,16进制转换(十六进制,二进制(包含小数)相互转换)
  3. 威纶通触摸屏上传错误_威纶通触摸屏支持什么系统?EB 8000和EB pro支持的型号有哪些?...
  4. 什么标签用于在表单中构建复选框_目前艾滋病主要的传播方式是(  )。
  5. Cam350导入Allegro的*.rou文件
  6. linux磁盘上机题目,Linux 练习题-3文件与磁盘 问答
  7. 何海涛算法面试题感悟之三:子数组…
  8. CTF-Web入门-get_post
  9. 移动联通电信频段划分
  10. 暴力调参——GridSearchCV、RandomizedSearchCV、贝叶斯优化