PySideTutorials Clickable button Japanese

From Qt Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

日本語 English

簡単なクリッカブルボタンのチュートリアル

このチュートリアルではPySideの シグナルとスロット の扱い方を紹介します。このQtの機能は、基本的にはグラフィカルウィジェット同士やグラフィカルウィジェットと独自のPythonコードの間の通信を可能にします。ここで紹介するアプリケーションでは、押すたびにPythonコンソールへ Hello World と表示するクリッカブルボタンを作成していきます。

まず必要なQtのクラスとPythonのsysクラスのインポートからはじめましょう。

import sys
from PySide.QtCore import *
from PySide.QtGui import *

次にコンソールに "Hello World"と出力するpythonの関数を作成しましょう。

# 挨拶をします
def sayHello():
 print "Hello World!"

ここではじめてのPySideアプリケーションで述べたように、PySideコードを実行するQApplicationを作成します。

# Qt Applicationを作ります
app = QApplication(sys.argv)

クリッカブルボタン、QPushButtonを作成しましょう。QPushButtonのコンストラクタにPythonの文字列を渡して、ボタンにラベルを付けます。

# ボタンを作ります
button = QPushButton("Click me")

ボタンを表示する前に、先ほど定義した sayHello() 関数とボタンとを接続します。今のところ接続方法には新旧の2つのスタイルがありますが、ここではよりPython的である新スタイルを使っていきます。両方のスタイルの詳細はPySideのシグナルとスロットでご確認ください。QPushButtonは clicked と呼ばれる事前定義シグナルをもっており、ボタンが押されるたびにこのシグナルが送出されます。 ではこのシグナルと sayHello() 関数を接続しましょう。

# ボタンと関数を接続します
button.clicked.connect(sayHello)

最後にボタンを表示してQtのメインループを開始します。

# ボタンを表示します
button.show()
# Qtのループを開始します
app.exec_()

コード全体

#!/usr/bin/python
# -'''- coding: utf-8 -'''-

import sys
from PySide.QtCore import *
from PySide.QtGui import *

def sayHello():
 print "Hello World!"

# Qt Applicationを作ります
app = QApplication(sys.argv)
# ボタンを作成して関数と接続したのち、表示します
button = QPushButton("Click me")
button.clicked.connect(sayHello)
button.show()
# Qtのループを開始します
app.exec_()