IronPython事始め

レイアウト

FlowLayoutPanelレイアウトとButtonコントロールを使ったプログラムを作成します。

"Add"ボタンを押す事で、FlowLayoutPanelのデフォルトルールに沿ってボタンが配置されます。 ウィンドウの形を変えながら、ボタンを増減させると左から右に向かって(フロー方向LeftToRight)ボタンが増えていく様子がわかると思います。

1. 画面キャプチャ

$alt $alt

2. サンプルコード:Layoutに沿ってボタンを追加する

MSDNのAPIリファレンスにあるサンプルコードを元にしました。 MSDNの例ではフロー方向をTopDownなどに変更する事もできるようになっていますが、そこは省略しています。

03_04_form_flowlayout.ipy

# coding=Shift_JIS
# IronPython Example:  FlowLayoutPanel
# - 
# @author: YasuhiroABE <yasu@yasundial.org>
# @see: FlowLayoutPanel Class Example from MSDN API Reference
#
import clr
clr.AddReferenceByPartialName("System.Windows.Forms")
clr.AddReferenceByPartialName("System.Drawing")
import System
from System.Windows.Forms import Form
from System.Windows.Forms import FlowLayoutPanel
from System.Windows.Forms import Button
from System.Windows.Forms import MessageBox
from System.Windows.Forms import DockStyle
from System.Drawing import Size

## init Form object
form = Form()
form.Text = "Hello World!"
form.Size = Size(300,200)

## init FlowLayoutPanel object
flowLayout = FlowLayoutPanel()
flowLayout.Size = form.Size
flowLayout.Dock = DockStyle.Fill
flowLayout.AutoScroll = True

## 生成したButtonオブジェクトを記憶するリストです
buttonList = []
## setup add button
addButton = Button()
addButton.Text = "Add"
def addButton_click(sender, arge):
  b = Button()
  b.Text = "No. " + str(len(buttonList))
  buttonList.append(b)
  flowLayout.Controls.Add(b)
  pass
addButton.Click += addButton_click
flowLayout.Controls.Add(addButton)

## setup del button
delButton = Button()
delButton.Text = "Delete"
def delButton_click(sender, arge):
  if(len(buttonList) == 0): return
  b = buttonList.pop()
  flowLayout.Controls.Remove(b)
  pass
delButton.Click += delButton_click
flowLayout.Controls.Add(delButton)

form.Controls.Add(flowLayout)
System.Windows.Forms.Application.Run(form)

3. コントロールの初期サイズについて

FlowLayoutPanelのインスタンスを単純にFormオブジェクトに追加しただけではサイズがおかしくなるので、flowLayout.Size = form.Sizeで初期サイズをウィンドウの大きさと同じに設定しています。 さらにウィンドウのリサイズに合わせて動くためにflowLayout.Dock = DockStyle.Fillを追加しています。


Created: 2010-03-11, Last modified: 2010-03-19

2009,2010 © Yasuhiro ABE <yasu@yasundial.org>

Valid XHTML + RDFa RDFa it (RDF/XML)!

正当なCSSです!

Creative Commons License www.yasundial.org by Yasuhiro ABE is licensed under a Creative Commons Attribution 2.1 Japan License. Permissions beyond the scope of this license may be available at http://www.yasundial.org/info/license.html.