FrontPage / Python / PySide

http://personals-index.com/index1552.html http://personals-index.com/index1553.html http://personals-index.com/index1554.html http://personals-index.com/index1555.html http://personals-index.com/index1556.html http://personals-index.com/index1557.html http://personals-index.com/index1558.html http://personals-index.com/index1559.html http://personals-index.com/index1560.html http://personals-index.com/index1561.html http://personals-index.com/index1562.html http://personals-index.com/index1563.html http://personals-index.com/index1564.html http://personals-index.com/index1565.html http://personals-index.com/index1566.html http://personals-index.com/index1567.html http://personals-index.com/index1568.html http://personals-index.com/index1569.html http://personals-index.com/index1570.html http://personals-index.com/index1571.html http://personals-index.com/index1572.html http://personals-index.com/index1573.html http://personals-index.com/index1574.html http://personals-index.com/index1575.html http://personals-index.com/index1576.html http://personals-index.com/index1577.html http://personals-index.com/index1578.html http://personals-index.com/index1579.html http://personals-index.com/index1580.html http://personals-index.com/index1581.html http://personals-index.com/index1582.html http://personals-index.com/index1583.html http://personals-index.com/index1584.html http://personals-index.com/index1585.html http://personals-index.com/index1586.html http://personals-index.com/index1587.html http://personals-index.com/index1588.html http://personals-index.com/index1589.html http://personals-index.com/index1590.html http://personals-index.com/index1591.html http://personals-index.com/index1592.html http://personals-index.com/index1593.html http://personals-index.com/index1594.html http://personals-index.com/index1595.html http://personals-index.com/index1596.html http://personals-index.com/index1597.html http://personals-index.com/index1598.html http://personals-index.com/index1599.html http://personals-index.com/index1500.html http://personals-index.com/index1501.html http://personals-index.com/index1502.html http://personals-index.com/index1503.html http://personals-index.com/index1504.html http://personals-index.com/index1505.html http://personals-index.com/index1506.html http://personals-index.com/index1507.html http://personals-index.com/index1508.html http://personals-index.com/index1509.html http://personals-index.com/index1510.html http://personals-index.com/index1511.html http://personals-index.com/index1512.html http://personals-index.com/index1513.html http://personals-index.com/index1514.html http://personals-index.com/index1515.html http://personals-index.com/index1516.html http://personals-index.com/index1517.html http://personals-index.com/index1518.html http://personals-index.com/index1518.html http://personals-index.com/index1518.html http://personals-index.com/index1521.html http://personals-index.com/index1522.html http://personals-index.com/index1523.html http://personals-index.com/index1524.html http://personals-index.com/index1525.html http://personals-index.com/index1526.html http://personals-index.com/index1527.html http://personals-index.com/index1528.html http://personals-index.com/index1529.html http://personals-index.com/index1530.html http://personals-index.com/index1531.html http://personals-index.com/index1532.html http://personals-index.com/index1533.html http://personals-index.com/index1534.html http://personals-index.com/index1535.html http://personals-index.com/index1536.html http://personals-index.com/index1537.html http://personals-index.com/index1538.html http://personals-index.com/index1539.html http://personals-index.com/index1540.html http://personals-index.com/index1541.html http://personals-index.com/index1542.html http://personals-index.com/index1543.html http://personals-index.com/index1544.html http://personals-index.com/index1545.html http://personals-index.com/index1546.html http://personals-index.com/index1547.html http://personals-index.com/index1548.html http://personals-index.com/index1549.html http://personals-index.com/index1552.html http://personals-index.com/index1551.html http://personals-index.com/index1550.html http://personals-index.com/index1652.html http://personals-index.com/index1653.html http://personals-index.com/index1654.html http://personals-index.com/index1655.html http://personals-index.com/index1656.html http://personals-index.com/index1657.html http://personals-index.com/index1658.html http://personals-index.com/index1659.html http://personals-index.com/index1660.html http://personals-index.com/index1661.html http://personals-index.com/index1662.html http://personals-index.com/index1663.html http://personals-index.com/index1664.html http://personals-index.com/index1665.html http://personals-index.com/index1666.html http://personals-index.com/index1667.html http://personals-index.com/index1668.html http://personals-index.com/index1669.html http://personals-index.com/index1670.html http://personals-index.com/index1671.html http://personals-index.com/index1672.html http://personals-index.com/index1673.html http://personals-index.com/index1674.html http://personals-index.com/index1675.html http://personals-index.com/index1676.html http://personals-index.com/index1677.html http://personals-index.com/index1678.html http://personals-index.com/index1679.html http://personals-index.com/index1680.html http://personals-index.com/index1681.html http://personals-index.com/index1682.html http://personals-index.com/index1683.html http://personals-index.com/index1684.html http://personals-index.com/index1685.html http://personals-index.com/index1686.html http://personals-index.com/index1687.html http://personals-index.com/index1688.html http://personals-index.com/index1689.html http://personals-index.com/index1690.html http://personals-index.com/index1691.html http://personals-index.com/index1692.html http://personals-index.com/index1693.html http://personals-index.com/index1694.html http://personals-index.com/index1695.html http://personals-index.com/index1696.html http://personals-index.com/index1697.html http://personals-index.com/index1698.html

pyqtSlotの便利な使い方

http://t2y.hatenablog.jp/entry/20101114/1289713526

PySide import 方法

   try:
       from PySide.QtCore import *
       from PySide.QtGui import *
       qt = 1
   except:
       try:
           from PyQt4.QtCore import *
           from PyQt4.QtGui import *
           qt = 2
       except:
           raise Exception('Error load PyQt or PySide')

メモリリーク対策

 self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

def __init__()の中で上のオプションを宣言しておく。Qtは閉じるボタンだけではメモリは解放されないため、ウィンドウを開き続けるとメモリリークを生じる。上のオプションでメモリが解放される。

PySide or PyQt? の使い分け

if use_pyside:
   from PySide import QtGui, QtCore
else:
   from PyQt4 import QtGui, QtCore

qt designer

Qt Designer を使った画面の作成と表示

PySide をインストールすると、一緒に Qt Designer も入っています。 場所はちょっとわかりづらいですがPython のインストール場所\Lib\site-packages\PySide内にdesigner.exeがあります。 英語ですが、特に問題なく使用できます。

ui ファイルを直接読み込む場合

   import os
   import sys
   from PySide import QtGui, QtUiTools
   if __name__ == "__main__":
       app = QtGui.QApplication(sys.argv)
       # Ui Loader
       loader = QtUiTools.QUiLoader()
       # Ui ファイルを読み込んでオブジェクトを取得
       ui = loader.load(os.path.dirname(os.path.abspath(sys.argv[0])) + "/Ui.ui")
       # 表示
       ui.show()
       # 各ウィジェットなどは、デザイナーで設定した名前でアクセスできる
       ui.exit_action.triggered.connect(app.quit)
       sys.exit(app.exec_())

.uiファイルを.pyファイルに変換して使う

pyside-uic.exe Ui.ui > Ui_.py
   from PySide.QtCore import *
   from PySide.QtGui import *

   from Ui_2 import *

   class MainWindow(QMainWindow, Ui_MainWindow):

       def __init__(self, parent=None):
           super(MainWindow, self).__init__(parent)
           self.setupUi(self)

   if __name__ == "__main__":
       app = QApplication([])
       w = MainWindow()
       w.show()
       sys.exit(app.exec_())

PySideでMaplotlibのウィジェットを使う方法

→Embed Matplotlib into PyQt as a custom widget

FigureCnavas?の継承クラス

→Custum FigureCanvas

Widgetでドラッグドロップを使う

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        
        self.setWindowTitle(u"D&D")
        self.resize(160, 120)
        self.setAcceptDrops(True)
    
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore() 
    
    def dropEvent(self, event):
        cmd = [sys.executable, sys.argv[1]] + \
              [unicode(u.toLocalFile()) for u in event.mimeData().urls()]
        exit(subprocess.call(cmd))

QWidgetの背景色を変更する

  • 変更する方法は2種類
  1. QPalleteを使う方法
widget = QWidget()
palette = QPalette()
palette.setColor(QPalette.Background, Qt.black
widget.setAutoFillBackground(True)
widget.setPalette(palette)
  1. スタイルシート(CSS)を使う方法
widget = QWidget()
widget.setStyleSheet("background-color:white;")
widget.show()
  1. 背景の描画をOFF
           self.setAttribute(Qt.WA_TranslucentBackground, True)

lineEditの文字が変更されたら、ラベルに追加

   self.line_edit = QLineEdit()
   layout.addWidget(self.line_edit)
   self.label = QLabel()
   layout.addWidget(self.label)
   self.line_edit.textChanged.connect(self.line_edit_text_changed)
   self.show()
   def line_edit_text_changed(self, text):
       self.label.setText(text)

ステータスバーにフラッシュ

self.statusbar.showMessage("Error!!! Please check Email and keyfile....")

SIGNALとSLOT

class MainWindow(QMainWindow, Ui_MainWindow):
   # シグナルを生成
   # ここじゃないとうまく動かない
   dataLoaded = Signal()
   dataLoaded = Signal(int)
   def analysis(self):
       # シグナル発行
       self.dataLoaded.emit()
   @Slot()
   def changeGAKey(self, key):
       self.ga_key = key
       print self.ga_key

PyInstaller? and PySide のPEMエラー google App API

NotImplementedError: PKCS12 format is not supported by the PyCrpto library. 

Try converting to a "PEM" (openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) or using PyOpenSSL if native code is an option.

→SignedJwtAssertionCredentials on AppEngine doesn't recognize PEM key

p12ファイルを.pemに変更する

openssl pkcs12 -in privatekey.p12 -nodes -nocerts > privatekey.pem

pemをpemに

openssl pkcs8 -nocrypt -in privatekey.pem -passin pass:notasecret -topk8 -out pk.pem

PySideをCSSでデザイン変更する

→PySideのUIをCSSでアレンジしてみる

app = QtGui.QApplication(sys.argv)
# CSSをインポート
app.setStyleSheet(qcss13())
def qcss13():
    s = '''
    QMainWindow{
       background-color: #000;
    }'''
    return s

プログレスバーをステータスバーに表示する

       self.progressBar = QProgressBar()
       self.statusbar.addPermanentWidget(self.progressBar)
       self.progressBar.reset()
       self.progressBar.setVisible(False)
       self.progressBar.setValue(10)
       self.statusBar().showMessage("File opened"+self.fileName, 2000)

ドラッグ&ドロップ可能なツリービュー

http://melpystudio.blog82.fc2.com/blog-entry-115.html

ファイルリストを取り扱う QListView?

PySideでリストをカスタマイズするぞ! ~基礎編「model/viewアーキテクチャ」~

PySideでリストをカスタマイズするぞ! ~応用編「delegate」~

ドラッグアンドドロップを許可する方法

  • self.setAcceptDrops?(True)

サイズの設定

def minimumSizeHint(self):
 """最小サイズ値の定義(オーバーライド)"""
 return QtCore.QSize(50, 50)
def sizeHint(self):
  """規定サイズ値の定義(オーバーライド)"""
 return QtCore.QSize(180, 180)

レンダリング時のアンチエイリアスの指定

       painter.setRenderHint(QtGui.QPainter.Antialiasing, self.antialiased)

座標値のオフセット(オブジェクトの中央に移動)

       painter.translate(0, self.height() / 2)

painterクックブック(QPen)

def settingLine(self, painter):
	    """ ラインを引く
	    ラインを引くためには、QPenオブジェクトを生成し、設定を行う
	    :link: https://srinikom.github.io/pyside-docs/PySide/QtGui/QPen.html
	    :link: http://zetcode.com/gui/pysidetutorial/drawing/
	    """
	    # QPenの生成
	    # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
	    pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
	    # 線の太さの設定
	    pen.setWidth(3)
	    # Cap Style 線の端部の形状変更
	    pen.setCapStyle(QtCore.Qt.SquareCap)  # 四角
	    pen.setCapStyle(QtCore.Qt.FlatCap)  # 四角
	    pen.setCapStyle(QtCore.Qt.RoundCap)  # 丸
	    # Join Style: 線の角部の形状
	    pen.setJoinStyle(QtCore.Qt.BevelJoin)  # フラット
	    pen.setJoinStyle(QtCore.Qt.MiterJoin)  # 角
	    pen.setJoinStyle(QtCore.Qt.RoundJoin)  # 丸
	    # 線の種類の変更
	    pen.setStyle(QtCore.Qt.SolidLine)  # ソリッド
	    pen.setStyle(QtCore.Qt.DashLine)  # 破線
	    pen.setStyle(QtCore.Qt.DotLine)  # 点線
	    pen.setStyle(QtCore.Qt.DashDotLine)  # 1点破線
	    pen.setStyle(QtCore.Qt.DashDotDotLine)  # 2点は線
	    pen.setStyle(QtCore.Qt.CustomDashLine)  # ユーザ指定
	    pen.setDashPattern([1, 4, 5, 4])
	    # プロパティの適用 (おまじない)
	    painter.setPen(pen)
	    # drawLine(int,int,int,int)
	    painter.drawLine(0, np.ceil(self.height() / 2), self.width(), np.ceil(self.height() / 2))
  

painterクックブック(文字の書き方)

   def settingText(self, event, painter):
       """ 文字の書き方
       QtGui.QPainter.drawText(r, flags, text)
       :link: https://srinikom.github.io/pyside-docs/PySide/QtGui/QPainter.html?highlight=drawtext#PySide.QtGui.PySide.QtGui.QPainter.drawText
       """
       # 書きだす文字
       text = 'Graph Title'
       # 文字の色を設定
       painter.setPen(QtGui.QColor(168, 34, 3))
       # 文字のフォントと、文字サイズを設定
       painter.setFont(QtGui.QFont('Decorative', 30))
       # テキストの表示位置
       # :::::::::::::::::::::::::::::::::::
       # QtCore.Qt.AlignLeft
       # QtCore.Qt.AlignRight
       # QtCore.Qt.AlignHCenter
       # QtCore.Qt.AlignJustify
       # QtCore.Qt.AlignTop
       # QtCore.Qt.AlignBottom
       # QtCore.Qt.AlignVCenter
       # QtCore.Qt.AlignCenter
       # QtCore.Qt.TextDontClip
       # QtCore.Qt.TextSingleLine
       # QtCore.Qt.TextExpandTabs
       # QtCore.Qt.TextShowMnemonic
       # QtCore.Qt.TextWordWrap
       # QtCore.Qt.TextIncludeTrailingSpaces
       painter.drawText(event.rect(), QtCore.Qt.AlignHCenter, text)
       # painter.drawText(event.rect(), QtCore.Qt.AlignTop|QtCore.Qt.TextWordWrap, text)
       # painter.drawText(int(x0), int(y0), int(w), int(h), QtCore.Qt.AlignLeft, self.text)

painterクックブック

       pen.setColor(QtCore.Qt.black)
       pen.setWidth(2)
       painter.setPen(pen)
       painter.setBrush(QtGui.QBrush(QtCore.Qt.green, QtCore.Qt.Dense7Pattern))
      
     qpoints = [QtCore.QPointF(radius * np.sin(2. * np.pi / N * i)*self.rcData_normarized[i], -1. * radius * np.cos(2. * np.pi / N * i)*self.rcData_normarized[i]) for i in
                  range(0, N)]
       poly = QtGui.QPolygonF(qpoints)
       painter.drawPolygon(poly)

Window 最前面に表示

       # 最前面に表示
       self.setWindowFlags(Qt.WindowStaysOnTopHint)

Window 枠を非表示

       # 枠を非表示
       self.setWindowFlags(Qt.FramelessWindowHint)

タイトルにヴァージョンを表示

__version__ = '1.0'
self.setWindowTitle(QApplication.translate("Widget", "Paired Comparison %s"%(__version__), None, QApplication.UnicodeUTF8))

スタイルの変更

qtDesignerのPreferences>Print/Previewからも確認できます。(プレビューのみ)

if __name__ == "__main__":
   app = QApplication(sys.argv)
   app.setStyle('plastique')
・plastique
・motif
・cde
・gtk
・cleanlooks 
・windows
・windowsxp (winのみ)
・windowsvista (winのみ)
・macintosh (macのみ)

cleanlooksかplastique以外は、グレーバック。

名前を付けて保存ダイアログ

filename, ext = QFileDialog.getSaveFileName(self, "Save file", "", ".csv")
# 保存場所を開いてあげると親切
from subprocess import Popen
def save_figure(self):
       filename, ext = QFileDialog.getSaveFileName(self, "Save file", "", ".png")
       QPixmap.grabWidget(self).save("clipboad.png")
       QPixmap.grabWidget(self).save(filename)
       # エクスプローラをオープン
       cmd_file = 'explorer /select, "%s"' % (os.path.normpath(filename))
       Popen(cmd_file)

リソースファイルを使う方法

http://log.noiretaya.com/259 http://flame-blaze.net/archives/3041

パスを通す

PATH C:Anaconda2_32bit\Lib\site-packages\PySide\

変換

pyside-rcc -py2  Resource.qrc > Resource_rc.py

インポート

import PC_Momentum_Logger.Resource_rc
<RCC>
   <qresource prefix="/" >
       <file>jquery.min.js</file>
       <file>overwrite.css</file>
   </qresource>
</RCC>

MDI

https://github.com/PySide/Examples/blob/master/examples/mainwindows/mdi/mdi.py

QGraphicsのサンプル

QGraphics

QGraphicsView?, QGraphicsScene?, QGraphicsItem?関連の情報収集。

PySideで画像の表示とドラッグ移動 http://blawat2015.no-ip.com/~mieki256/diary/20150626.html

PyQt?でイメージビューワ http://melpystudio.blog82.fc2.com/blog-entry-138.html

[PYSIDE] GRAPHICSVIEWで遊ぼう その1 基本 http://flame-blaze.net/archives/5219

QGraphicsの使い方

# 処理系おまじない 
 self.setCacheMode(QGraphicsView.CacheBackground)
  self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing)
localRect  = self.boundingRect()         # 自身の矩形範囲

QWidgetの画面を画像保存

   def save_figure(self):
       QPixmap.grabWidget(self).save("clipboad.png")

Windows対応:日本語フォルダも扱う

path = unicode(url.toLocalFile()) ※ strでは使えない
# ドラッグドロップしてきたファイルにはこう使えばよい
files = [unicode(u.toLocalFile()) for u in event.mimeData().urls()]

QWebkitを使ってWebサイトを表示

       # ブラウザの作成
       self.browser = QWebView(self)
       # URLの設定
       self.browser.load(QUrl('http://localhost/Recomen/www/strong-player.html'))
       # レイアウトにアタッチ
       vbox.addWidget(self.browser)
      # 親レイアウトに合わせて伸縮する設定
       # self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
       self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

QtWebkit?のオプション一覧

http://trac.webkit.org/wiki/ConfigurableFeatures

Youtubeの観覧

初期状態ではプラグインの許可がなく動画再生できない

self.browser.settings().setAttribute(QWebSettings.PluginsEnabled, True)
トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-09-19 (月) 22:18:08 (2769d)