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'
'\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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM