欢迎大家同时关注我在仿真秀中的账号——“ANSA攻城狮 ”,会有更多干货文章以及课程。
上篇文章
主要介绍了在创建GUI界面中常见的组件创建函数,那如何在窗口中将各种不同的组件排列出我们想要的布局呢?下面就介绍一些常用的布局类函数。
该函数可以在父类组件、布局下创建内部内容横向或者纵向布置的盒子。
布局如下所示,左边的是横向布局,右侧的是纵向布局 ,这里需要注意一点的是在BCBoxLayout中创建其他的组件或者布局时首先需要使用创建函数创建需要的组件或者布局,其次guitk.BCGridLayoutCreate(p,numRows,numCols)使用BCBoxLayoutInsert()来控制插入的位置,这里请大家咨询查找帮助文档熟悉函数的参数及返回值。
下面据一些具体的例子来看一下这两种布局类的函数是如何使用的,假设我们要创建如下的窗口。
首先创建一个窗口,这里注意一定要使用guitk.BCShow(w),才能显示窗口。
接着我们创建第一部分中的BCLabel以及BCLineEdit组件。先创建一个BCBoxLayout用来容纳BCLabel以及BCLineEdit组件,注意在创建BCBoxLayout中方向是水平。
接着我们创建BCBoxLayout下面的BCGridLayout,这里配合BCGridLayoutAddWidget()来讲BCPushButton一一插入到相应位置
最后我们来建立最后的OK和Cancel按键,这里我们直接把这两个按键放在了BCWindow下,当然你再建立一个属于BCWindow的BCBoxLayout或者BCGridLayout,再把这两个按键在其中布局也可以,不过没什么必要。
这里再来一些优化,可以看到不同的部分之间挨得很近,布局太过紧凑。这里可以通过在BCBoxLayout、BCGridLayout、BCPushButton之间增加BCSplitter来解决。
创建出来的效果大致是下面这个样子
该组件使用的逻辑是:
这里在介绍一下BCButtonGroupCreateHidden()的使用方法。这个函数和BCButtonGroupCreate()使用方法相同,只是他创建出的没有外框、没有名称,像下边这样
BCButtonGroupCreateHidden()函数使用的逻辑是
大家一定现在有所疑惑,这么做不是脱裤子放屁吗,直接在BCWindow上创建BCRadioButton组件和上面的效果是一样的,有必要这么麻烦吗?
答案是有,而且非常有。这样做的好处是所创建出的BCButtonGroup中的组件可以保留原来的属性下面是BCButtonGroup相关的一些函数
比如说BCButtonGroupFind的功能可以让我们知道此时用户按下的是那个按键。如果不借助BCButtonGroup的特性直接在BCWindow中直接创建按键,我们是不能知道此时用户按下的是哪个按键。
下面的例子展示了,按下按钮后打印出BCButtonGroup中按钮的id以及相应的名字。
from ansa import guitk
def main():
#创建BCWindow
window = guitk.BCWindowCreate( "Exclusive ButtonGroup", guitk.constants.BCOnExitDestroy )
#在BCWindow上创建纵向布局的BCButtonGroup
exclusive = guitk.BCButtonGroupCreateHidden( window, "", guitk.constants.BCVertical )
#在BCButtonGroup中创建一个按钮
list = guitk.BCPushButtonCreate( window, "List View", None, None )
#将此按钮设置为按下后一直处于pressed的状态
guitk.BCButtonSetToggleButton( list, True )
#将按钮插入BCButtonGroup的第一个位置
guitk.BCButtonGroupInsert(exclusive, list, 0)
tree = guitk.BCPushButtonCreate( window, "Tree View", None, None )
guitk.BCButtonGroupInsert(exclusive,tree, 1)
guitk.BCButtonSetToggleButton( tree, True )
guitk.BCButtonGroupInsert(exclusive, tree, 1)
icon = guitk.BCPushButtonCreate( window, "Icon View", None, None )
guitk.BCButtonGroupInsert(exclusive,icon, 2)
guitk.BCButtonSetToggleButton( icon, True )
guitk.BCButtonGroupInsert(exclusive, icon, 2)
#设置按钮按下后的执行函数
guitk.BCButtonGroupSetClickedFunction( exclusive, buttonGroupClicked, None )
#设置一开始BCButtonGroup中那个按键被选中,这里是名为list的按钮一开始处于选中状态
guitk.BCButtonGroupSetButton( exclusive, guitk.BCButtonGroupId(exclusive, list) )
#打印一开始被选中的按钮的id,BCButtonGroupGetSelectedId用来获取按钮的id
print('Selected index: ' + str(guitk.BCButtonGroupGetSelectedId(exclusive)))
#出选中的按钮在别的按钮被按下后最初被选中的按钮变为非选中状态
guitk.BCButtonGroupSetExclusive(exclusive, True )
guitk.BCShow(window)
def buttonGroupClicked(bg, index, data):
button = guitk.BCButtonGroupFind( bg, index )
buttonText = guitk.BCButtonText( button )
if (guitk.BCButtonGroupGetSelectedId(bg) == index ):
print( 'Index is: ' + str(index) + ' and button text is: ' + buttonText)
else:
print ('I should not be here')
return 0
if __name__ == '__main__':
main()