LoginSignup
14
25

More than 5 years have passed since last update.

Python3とPySide2でGUI作成

Last updated at Posted at 2017-12-07

PySide2でのGUI開発の環境を整えたので覚書に。
- OS:Ubuntu17.10

1. Python3の開発環境構築

PySide2の入手が一番簡単なので今回はAnaconda or Minicondaで構築していきます。
自身は余計なパッケージとかいらないのでMinicondaでいきます。

AnacondaとMinicondaについての詳しいことは他の方の投稿を参照ください
インストールしたら作業用の環境を作っておきます。

2. PySide2をインストール

GitリポジトリをCloneしてビルド実行...とかしたかったんですが何度やってもうまくいかない!!!
なぜでしょう...
そこで今回はconda経由でパッケージを取得します。

$conda install -c conda-forge pyside2

3. ソースコード

QtをDLしてインストール。
そしたらQtCreatorで.uiファイルを編集してGUI部分を作成して保存します。
.uiファイルを.pyに変換します。

pyside2-uic -o 出力したい.pyファイル 作成した.uiファイル

とりあえず初期状態のウィンドウを.pyで出力しました。

mainwindow.py
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Desktop/mainwindow.ui'
#
# Created: Thu Dec  7 20:53:34 2017
#      by: pyside2-uic 2.0.0 running on PySide2 2.0.0~alpha0
#
# WARNING! All changes made in this file will be lost!

from PySide2 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(400, 300)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setObjectName("menuBar")
        MainWindow.setMenuBar(self.menuBar)
        self.mainToolBar = QtWidgets.QToolBar(MainWindow)
        self.mainToolBar.setObjectName("mainToolBar")
        MainWindow.addToolBar(self.mainToolBar)
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        MainWindow.setCentralWidget(self.centralWidget)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtWidgets.QApplication.translate("MainWindow", "MainWindow", None, -1))


そしたらこのGUIの.pyファイルを読み込んで出力するmain.pyを書きます。

main.py

# -*- coding: utf-8 -*-
import sys
from mainwindow import Ui_MainWindow
from PySide2.QtWidgets import *

class MainWindow(QMainWindow):
    #Ui_MainWindow生成のための初期化処理
    def __init__(self, parent = None):

        #UI初期化処理
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

#実行処理
if __name__=="__main__":
    #アプリケーション作成
    app = QApplication(sys.argv)
    #オブジェクト作成
    window = MainWindow()
    #MainWindowの表示
    window.show()
    sys.exit(app.exec_())

4. 実行

2つのファイルを同じフォルダに入れて実行

$python main.py

無事にウィンドウが表示されたら成功です
Screenshot from 2017-12-07 21-18-53.png

とりあえずPySide2でGUI開発をするためのスタート地点ですね。
ここからいろんな機能を追加していけたらと思います。

14
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
25