PyQtを使い始める

Qt Designerによる画面デザイン

ウィジェットを適当に並べる。使い方はVisualStudioとかとほぼ同じか。完了後、uiファイルとして保存する。

uiファイルをpyファイルへ変換

バッチファイルpyuic4.batを用いる。自分の場合、C:\Python27\Lib\site-packages\PyQt4にあるファイル。

> pyuic4.bat [uiファイル名] > [pyファイル名]

とすれば変換される。画面デザインのライブラリが出来上がる。ここでは、ui_gotocell.pyという名前で作成した。コードの最初の部分だけ下に示す。

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'gotocell.ui'
#
# Created: Fri Oct 10 15:26:51 2014
#      by: PyQt4 UI code generator 4.9.6
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_GoToCellDialog(object):
    def setupUi(self, GoToCellDialog):
        GoToCellDialog.setObjectName(_fromUtf8("GoToCellDialog"))
        GoToCellDialog.resize(228, 71)
        self.verticalLayout = QtGui.QVBoxLayout(GoToCellDialog)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
# (以下略)

main.pyファイルの作成

作成したライブラリを呼び出して画面を表示するために、main.pyファイルを以下のように作成する。

import sys
from PyQt4.QtGui import QApplication, QWidget

from ui_gotocell import Ui_GoToCellDialog

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    ui = Ui_GoToCellDialog()
    ui.setupUi(window)

    window.show()
    sys.exit(app.exec_())

このmain.pyを実行すると、画面が起動する。