問題描述
我正在使用 Python-2.7
和 kivy
.
我運(yùn)行 test.py
然后顯示一個(gè)菜單 Test
.當(dāng)我點(diǎn)擊它然后顯示 list
的數(shù)據(jù).誰能告訴我如何在列表中添加垂直 scrollbar
.
test.py
從 kivy.app 導(dǎo)入 App從 kivy.uix.boxlayout 導(dǎo)入 BoxLayout從 kivy.properties 導(dǎo)入 BooleanProperty、ListProperty、ObjectProperty、NumericProperty、DictProperty從 kivy.uix.recycleview.views 導(dǎo)入 RecycleDataViewBehavior從 kivy.uix.button 導(dǎo)入按鈕從 kivy.uix.recyclegridlayout 導(dǎo)入 RecycleGridLayout從 kivy.uix.behaviors 導(dǎo)入 FocusBehavior從 kivy.uix.recycleview.layout 導(dǎo)入 LayoutSelectionBehavior從 kivy.uix.popup 導(dǎo)入彈出窗口從 kivy.core.window 導(dǎo)入窗口從 kivy.clock 導(dǎo)入時(shí)鐘窗口大小 = (600, 325)類 SelectableRecycleGridLayout(FocusBehavior,LayoutSelectionBehavior,回收網(wǎng)格布局):''' 將選擇和焦點(diǎn)行為添加到視圖.'''selected_row = NumericProperty(0)def get_nodes(self):節(jié)點(diǎn) = self.get_selectable_nodes()如果 self.nodes_order_reversed:節(jié)點(diǎn)=節(jié)點(diǎn)[::-1]如果不是節(jié)點(diǎn):返回?zé)o,無selected = self.selected_nodesif not selected: # 沒有選擇,選擇第一個(gè)self.select_node(節(jié)點(diǎn)[0])self.selected_row = 0返回?zé)o,無if len(nodes) == 1: # 唯一可選擇的節(jié)點(diǎn)已經(jīng)被選中返回?zé)o,無最后 = 節(jié)點(diǎn)索引(選定 [-1])self.clear_selection()最后返回,節(jié)點(diǎn)def select_next(self):'''選擇下一行'''最后,節(jié)點(diǎn) = self.get_nodes()如果不是節(jié)點(diǎn):返回如果最后 == len(nodes) - 1:self.select_node(節(jié)點(diǎn)[0])self.selected_row = 節(jié)點(diǎn)[0]別的:self.select_node(nodes[last + 1])self.selected_row = 節(jié)點(diǎn)[last + 1]def select_previous(self):''' 選擇上一行 '''最后,節(jié)點(diǎn) = self.get_nodes()如果不是節(jié)點(diǎn):返回如果不是最后:self.select_node(節(jié)點(diǎn)[-1])self.selected_row = 節(jié)點(diǎn)[-1]別的:self.select_node(nodes[last - 1])self.selected_row = 節(jié)點(diǎn)[last - 1]def select_current(self):''' 選擇當(dāng)前行 '''最后,節(jié)點(diǎn) = self.get_nodes()如果不是節(jié)點(diǎn):返回self.select_node(節(jié)點(diǎn)[self.selected_row])類 SelectableButton(RecycleDataViewBehavior,按鈕):''' 為按鈕添加選擇支持 '''索引 = 無選擇 = BooleanProperty(False)可選 = BooleanProperty(True)def refresh_view_attrs(self, rv, index, data):''' 捕捉并處理視圖變化 '''self.index = 索引return super(SelectableButton, self).refresh_view_attrs(rv, index, data)def on_touch_down(自我,觸摸):'''在觸地時(shí)添加選擇'''if super(SelectableButton, self).on_touch_down(touch):返回真如果 self.collide_point(*touch.pos) 和 self.selectable:打印(on_touch_down:自我=",自我)返回 self.parent.select_with_touch(self.index, touch)def apply_selection(self, rv, index, is_selected):''' 響應(yīng)視圖中項(xiàng)目的選擇.'''self.selected = is_selectedRV類(BoxLayout):data_items = ListProperty([])row_data = DictProperty({})col1_data = ListProperty([])col2_data = ListProperty([])col1_row_controller = ObjectProperty(無)col2_row_controller = ObjectProperty(無)def __init__(self, **kwargs):超級(房車,自我).__init__(**kwargs)self.get_states()Clock.schedule_once(self.set_default_first_row, .0005)self._request_keyboard()def _request_keyboard(self):self._keyboard = Window.request_keyboard(self._keyboard_closed,自我,'文本')如果 self._keyboard.widget:# 如果它存在,這個(gè)小部件是一個(gè)你可以使用的 VKeyboard 對象# 更改鍵盤布局.經(jīng)過self._keyboard.bind(on_key_down=self._on_keyboard_down)def _keyboard_closed(self):self._keyboard.unbind(on_key_down=self._on_keyboard_down)self._keyboard = 無def _on_keyboard_down(自我,鍵盤,鍵碼,文本,修飾符):if keycode[1] == 'down': # keycode[274, 'down'] 按下# 響應(yīng)鍵盤向下箭頭按下self.display_keystrokes(鍵盤、鍵碼、文本、修飾符)self.col1_row_controller.select_next()self.col2_row_controller.select_next()elif keycode[1] == 'up': # keycode[273, 'up] 按下# 響應(yīng)鍵盤向上箭頭按下self.display_keystrokes(鍵盤、鍵碼、文本、修飾符)self.col1_row_controller.select_previous()self.col2_row_controller.select_previous()# Keycode由整數(shù)+字符串組成# 如果我們按下escape,釋放鍵盤如果鍵碼 [1] == '轉(zhuǎn)義':鍵盤.release()# 返回 True 以接受密鑰.否則,它將被# 系統(tǒng).返回真def display_keystrokes(self, keyboard, keycode, text, modifiers):print("
鍵", keycode, "已被按下")print(" - 文本是 %r" % 文本)print(" - 修飾符是 %r" % 修飾符)def on_keyboard_select(self):''' 響應(yīng)鍵盤事件調(diào)用 Popup '''# 為 Popup 設(shè)置行數(shù)據(jù)self.row_data = self.col1_data[self.col1_row_controller.selected_row]# 調(diào)用彈出窗口self.popup_callback()def on_mouse_select(self, instance):'''響應(yīng)鼠標(biāo)事件調(diào)用Popup '''if (self.col1_row_controller.selected_row != instance.index或 self.col2_row_controller.selected_row != instance.index):# 鼠標(biāo)點(diǎn)擊的行不等于當(dāng)前選中的行self.col1_row_controller.selected_row = instance.indexself.col2_row_controller.selected_row = instance.index# 高亮鼠標(biāo)點(diǎn)擊/選中的行self.col1_row_controller.select_current()self.col2_row_controller.select_current()# 為 Popup 設(shè)置行數(shù)據(jù)# 我們可以使用 col1_data 或 col2_data,因?yàn)樗鼈兪侵貜?fù)的,并且每個(gè)都存儲(chǔ)相同的信息self.row_data = self.col1_data[instance.index]# 調(diào)用彈出窗口self.popup_callback()def popup_callback(self):# 啟用鍵盤請求self._request_keyboard()def set_default_first_row(self, dt):''' 設(shè)置默認(rèn)第一行為選中'''self.col1_row_controller.select_next()self.col2_row_controller.select_next()定義更新(自我):self.col1_data = [{'text': str(x[0]), 'Id': str(x[0]), 'Name': x[1], 'key': 'Id', 'selectable': 真的}對于 self.data_items 中的 x]self.col2_data = [{'text': x[1], 'Id': str(x[0]), 'Name': x[1], 'key': 'Name', 'selectable': True}對于 self.data_items 中的 x]def get_states(self):行 = [(1, 'abc'), (1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc')]我 = 0對于行中的行:self.data_items.append([row[0], row[1], i])我 += 1打印(self.data_items)自我更新()類 MainMenu(BoxLayout):states_cities_or_areas = ObjectProperty(無)rv = 對象屬性(無)定義顯示狀態(tài)(自我):self.remove_widgets()self.rv = RV()self.states_cities_or_areas.add_widget(self.rv)def remove_widgets(self):self.states_cities_or_areas.clear_widgets()類測試應(yīng)用程序(應(yīng)用程序):標(biāo)題=測試"定義構(gòu)建(自我):返回主菜單()如果 __name__ == '__main__':TestApp().run()
test.kv
#:kivy 1.10.0<可選按鈕>:畫布之前:顏色:rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)長方形:pos: self.pos尺寸:self.sizebackground_color: [1, 0, 0, 1] if self.selected else [1, 1, 1, 1] #深紅色 else深灰色on_press: app.root.rv.on_mouse_select(self)<房車>:col1_row_controller:col1_row_controllercol2_row_controller: col2_row_controller方向:垂直"網(wǎng)格布局:大小提示:1,無size_hint_y:無身高:25列數(shù):3標(biāo)簽:size_hint_x: .1文字:身份證"標(biāo)簽:size_hint_x:0.5文字:姓名"滾動(dòng)視圖:id: kr_scrolldo_scroll_x: 假高度:2盒子布局:回收視圖:size_hint_x: .1數(shù)據(jù):root.col1_data視圖類:可選按鈕"可選回收網(wǎng)格布局:id: col1_row_controllerkey_selection: '可選擇的'列數(shù):1default_size:無,dp(26)default_size_hint:1,無size_hint_y:無高度:self.minimum_height方向:垂直"多選:真touch_multiselect:真回收視圖:size_hint_x:0.5數(shù)據(jù):root.col2_data視圖類:可選按鈕"可選回收網(wǎng)格布局:id: col2_row_controllerkey_selection: '可選擇的'列數(shù):1default_size:無,dp(26)default_size_hint:1,無size_hint_y:無高度:self.minimum_height方向:垂直"多選:真touch_multiselect:真<菜單按鈕@按鈕>:text_size: self.size對齊:中間"padding_x: 5尺寸:(80,30)size_hint:(無,無)背景顏色:90、90、90、90背景正常:''顏色:0、0.517、0.705、1邊框:(0, 10, 0, 0)<主菜單>:states_cities_or_areas: states_cities_or_areas盒子布局:方向:垂直"#間距:10盒子布局:畫布之前:長方形:pos: self.pos尺寸:self.sizesize_hint_y: 1菜單按鈕:編號:btn文字:'測試'尺寸:(60,30)on_release: root.display_states()盒子布局:畫布之前:長方形:pos: self.pos尺寸:self.size顏色:RGB:(1,1,1)標(biāo)簽:size_hint_x: 45盒子布局:id: states_cities_or_areassize_hint_y: 10標(biāo)簽:size_hint_y: 1
問題
<塊引用>如何僅在 customerId 列和其他列中設(shè)置文本右對齊應(yīng)該左對齊嗎?
解決方案
片段
def apply_selection(self, rv, index, is_selected):''' 響應(yīng)視圖中項(xiàng)目的選擇.'''self.selected = is_selectedself.text_size = self.size如果 index == rv.data[index]['range'][0]:self.halign = '對'別的:self.halign = '左'
輸出
標(biāo)簽 - 文本垂直增長并以特定寬度換行
一個(gè)可以垂直增長但以一定寬度包裹文本的Label:
標(biāo)簽:size_hint_y:無text_size:self.width,無高度:self.texture_size[1]
要在 X 軸/水平和 Y 軸/垂直滾動(dòng) GridLayout,請將 size_hint 屬性設(shè)置為 (None, None).
ScrollView - ScrollEffect、scroll_type、bar_width 等
<塊引用>默認(rèn)情況下,ScrollView 允許沿 X 軸和 Y 軸滾動(dòng).您可以通過將 do_scroll_x 或 do_scroll_y 屬性設(shè)置為 False 來顯式禁用軸上的滾動(dòng).
要在 Y 軸/垂直方向上滾動(dòng) GridLayout,請?jiān)O(shè)置孩子的寬度為 ScrollView (size_hint_x=1),并設(shè)置size_hint_y 屬性為無:
當(dāng)滾動(dòng)超出 ScrollView 的邊界時(shí),它使用 ScrollEffect 來處理過度滾動(dòng).
滾動(dòng)類型
設(shè)置用于滾動(dòng)視圖內(nèi)容的滾動(dòng)類型.可用選項(xiàng)有:['content']、['bars']、['bars'、'content']
['bars'] 通過拖動(dòng)或滑動(dòng)滑動(dòng)條來滾動(dòng)內(nèi)容.
網(wǎng)格布局
<塊引用>cols_minimum
每列的最小寬度字典.字典鍵是列號,例如0、1、2……
cols_minimum 是一個(gè) DictProperty,默認(rèn)為 {}.
片段
:行控制器:行控制器bar_width: 10bar_color: 1, 0, 0, 1 # 紅色bar_inactive_color: 0, 0, 1, 1 # 藍(lán)色effect_cls: "滾動(dòng)效果"滾動(dòng)類型:['條']數(shù)據(jù):root.rv_data視圖類:可選按鈕"可選回收網(wǎng)格布局:id:row_controllerkey_selection: '可選擇的'列:root.total_col_headingscols_minimum:root.cols_minimumdefault_size:無,dp(26)default_size_hint:1,無size_hint:無,無高度:self.minimum_height寬度:self.minimum_width方向:垂直"多選:真touch_multiselect:真
以下示例演示:
- 在 X 軸上滾動(dòng)表格標(biāo)題.
- 支持X軸和Y軸滾動(dòng).
- 支持彈窗 Y 軸滾動(dòng).
- 適用于數(shù)據(jù)庫表中的任何列.
- 使用 GridLayout 改變列寬cols_minimum.
- 將兩個(gè) RecycleView 合二為一,因?yàn)椴恍枰獮?ID 設(shè)置一個(gè) recycleview.
- 可選擇的按鈕.
SQLite 示例數(shù)據(jù)庫
chinook SQLite 示例數(shù)據(jù)庫
示例
main.py
從 kivy.app 導(dǎo)入 App從 kivy.uix.boxlayout 導(dǎo)入 BoxLayout從 kivy.properties 導(dǎo)入 BooleanProperty、ListProperty、ObjectProperty、NumericProperty、DictProperty從 kivy.uix.recycleview.views 導(dǎo)入 RecycleDataViewBehavior從 kivy.uix.button 導(dǎo)入按鈕從 kivy.uix.recyclegridlayout 導(dǎo)入 RecycleGridLayout從 kivy.uix.behaviors 導(dǎo)入 FocusBehavior從 kivy.uix.recycleview.layout 導(dǎo)入 LayoutSelectionBehavior從 kivy.uix.popup 導(dǎo)入彈出窗口從 kivy.core.window 導(dǎo)入窗口從 kivy.clock 導(dǎo)入時(shí)鐘從 kivy.uix.scrollview 導(dǎo)入 ScrollView從 kivy.uix.label 導(dǎo)入標(biāo)簽從 kivy.uix.textinput 導(dǎo)入 TextInput從 kivy.uix.recycleview 導(dǎo)入 RecycleView將 sqlite3 導(dǎo)入為 lite重新進(jìn)口窗口大小 = (600, 325)類 PopupLabelCell(標(biāo)簽):經(jīng)過類 EditStatePopup(彈出):def __init__(self, obj, **kwargs):super(EditStatePopup, self).__init__(**kwargs)self.populate_content(obj)def populate_content(self, obj):對于 x 在范圍內(nèi)(len(obj.table_header.col_headings)):self.container.add_widget(PopupLabelCell(text=obj.table_header.col_headings[x]))textinput = TextInput(text=str(obj.row_data[x]))如果 x == 0:textinput.readonly = Trueself.container.add_widget(textinput)類 SelectableRecycleGridLayout(FocusBehavior,LayoutSelectionBehavior,回收網(wǎng)格布局):''' 將選擇和焦點(diǎn)行為添加到視圖.'''selected_row = NumericProperty(0)obj = ObjectProperty(無)def get_nodes(self):節(jié)點(diǎn) = self.get_selectable_nodes()如果 self.nodes_order_reversed:節(jié)點(diǎn)=節(jié)點(diǎn)[::-1]如果不是節(jié)點(diǎn):返回?zé)o,無selected = self.selected_nodesif not selected: # 沒有選擇,選擇第一個(gè)self.selected_row = 0self.select_row(節(jié)點(diǎn))返回?zé)o,無if len(nodes) == 1: # 唯一可選擇的節(jié)點(diǎn)已經(jīng)被選中返回?zé)o,無最后 = 節(jié)點(diǎn)索引(選定 [-1])self.clear_selection()最后返回,節(jié)點(diǎn)def select_next(self, obj):'''選擇下一行'''自我.obj = obj最后,節(jié)點(diǎn) = self.get_nodes()如果不是節(jié)點(diǎn):返回如果最后 == len(nodes) - 1:self.selected_row = 節(jié)點(diǎn)[0]別的:self.selected_row = 節(jié)點(diǎn)[last + 1]self.selected_row += self.obj.total_col_headingsself.select_row(節(jié)點(diǎn))def select_previous(self, obj):''' 選擇上一行 '''自我.obj = obj最后,節(jié)點(diǎn) = self.get_nodes()如果不是節(jié)點(diǎn):返回如果不是最后:self.selected_row = 節(jié)點(diǎn)[-1]別的:self.selected_row = 節(jié)點(diǎn)[last - 1]self.selected_row -= self.obj.total_col_headingsself.select_row(節(jié)點(diǎn))def select_current(self, obj):''' 選擇當(dāng)前行 '''自我.obj = obj最后,節(jié)點(diǎn) = self.get_nodes()如果不是節(jié)點(diǎn):返回self.select_row(節(jié)點(diǎn))def select_row(自我,節(jié)點(diǎn)):col = self.obj.rv_data[self.selected_row]['range']對于范圍內(nèi)的 x(col[0],col[1] + 1):self.select_node(節(jié)點(diǎn)[x])類 SelectableButton(RecycleDataViewBehavior,按鈕):''' 為按鈕添加選擇支持 '''索引 = 無選擇 = BooleanProperty(False)可選 = BooleanProperty(True)def refresh_view_attrs(self, rv, index, data):''' 捕捉并處理視圖變化 '''self.index = 索引return super(SelectableButton, self).refresh_view_attrs(rv, index, data)def on_touch_down(自我,觸摸):'''在觸地時(shí)添加選擇'''if super(SelectableButton, self).on_touch_down(touch):返回真如果 self.collide_point(*touch.pos) 和 self.selectable:打印(on_touch_down:自我=",自我)返回 self.parent.select_with_touch(self.index, touch)def apply_selection(self, rv, index, is_selected):''' 響應(yīng)視圖中項(xiàng)目的選擇.'''self.selected = is_selectedself.text_size = self.size如果 index == rv.data[index]['range'][0]:self.halign = '對'別的:self.halign = '左'類 HeaderCell(標(biāo)簽):經(jīng)過類表頭(滾動(dòng)視圖):"""固定的表頭,用數(shù)據(jù)表滾動(dòng) x"""標(biāo)頭 = 對象屬性(無)col_headings = ListProperty([])cols_minimum = 字典屬性({})def __init__(self, **kwargs):super(TableHeader, self).__init__(**kwargs)self.db = lite.connect('chinook.db')self.db_cursor = self.db.cursor()self.get_table_column_headings()def get_table_column_headings(self):self.db_cursor.execute("PRAGMA table_info(customers)")col_headings = self.db_cursor.fetchall()對于 col_headings 中的 col_heading:data_type = col_heading[2]如果 data_type == 整數(shù)":self.cols_minimum[col_heading[0]] = 100別的:self.cols_minimum[col_heading[0]] = int(re.findall(r'd+', data_type).pop(0)) * 5self.col_headings.append(col_heading[1])self.header.add_widget(HeaderCell(text=col_heading[1], width=self.cols_minimum[col_heading[0]]))房車類(回收視圖):row_data = ()rv_data = ListProperty([])row_controller = ObjectProperty(無)total_col_headings = NumericProperty(0)cols_minimum = 字典屬性({})table_header = ObjectProperty(無)def __init__(self, table_header, **kwargs):超級(房車,自我).__init__(**kwargs)self.table_header = table_headerself.total_col_headings = len(table_header.col_headings)self.cols_minimum = table_header.cols_minimumself.database_connection()self.get_states()Clock.schedule_once(self.set_default_first_row, .0005)self._request_keyboard()def 數(shù)據(jù)庫連接(自我):self.db = lite.connect('chinook.db')self.db_cursor = self.db.cursor()def _request_keyboard(self):self._keyboard = Window.request_keyboard(self._keyboard_closed,自我,'文本')如果 self._keyboard.widget:# 如果它存在,這個(gè)小部件是一個(gè)你可以使用的 VKeyboard 對象# 更改鍵盤布局.經(jīng)過self._keyboard.bind(on_key_down=self._on_keyboard_down)def _keyboard_closed(self):self._keyboard.unbind(on_key_down=self._on_keyboard_down)self._keyboard = 無def _on_keyboard_down(自我,鍵盤,鍵碼,文本,修飾符):if keycode[1] == 'down': # keycode[274, 'down'] 按下# 響應(yīng)鍵盤向下箭頭按下self.display_keystrokes(鍵盤、鍵碼、文本、修飾符)self.row_controller.select_next(self)elif keycode[1] == 'up': # keycode[273, 'up] 按下# 響應(yīng)鍵盤向上箭頭按下self.display_keystrokes(鍵盤、鍵碼、文本、修飾符)self.row_controller.select_previous(self)elif len(修飾符)>0 和修飾符[0] == 'ctrl' 和 text == 'e': # ctrl + e 按下# 響應(yīng)鍵盤 ctrl + e 按下,并調(diào)用 Popupself.display_keystrokes(鍵盤、鍵碼、文本、修飾符)self.on_keyboard_select()# Keycode由整數(shù)+字符串組成# 如果我們按下escape,釋放鍵盤如果鍵碼 [1] == '轉(zhuǎn)義':鍵盤.release()# 返回 True 以接受密鑰.否則,它將被# 系統(tǒng).返回真def display_keystrokes(self, keyboard, keycode, text, modifiers):print("
鍵", keycode, "已被按下")print(" - 文本是 %r" % 文本)print(" - 修飾符是 %r" % 修飾符)def on_keyboard_select(self):''' 響應(yīng)鍵盤事件調(diào)用 Popup '''# 為 Popup 設(shè)置行數(shù)據(jù)self.setup_row_data(self.rv_data[self.row_controller.selected_row]['Index'])# 調(diào)用彈出窗口self.popup_callback()def on_mouse_select(self, instance):'''響應(yīng)鼠標(biāo)事件調(diào)用Popup '''如果 self.row_controller.selected_row != instance.index:# 鼠標(biāo)點(diǎn)擊的行不等于當(dāng)前選中的行self.row_controller.selected_row = instance.index# 高亮鼠標(biāo)點(diǎn)擊/選中的行self.row_controller.select_current(self)# 為 Popup 設(shè)置行數(shù)據(jù)self.setup_row_data(self.rv_data[instance.index]['Index'])# 調(diào)用彈出窗口self.popup_callback()# 啟用鍵盤請求self._request_keyboard()def setup_row_data(自我,價(jià)值):self.db_cursor.execute("SELECT * FROM customers WHERE CustomerId=?", value)self.row_data = self.db_cursor.fetchone()def popup_callback(self):''' 實(shí)例化并打開彈出窗口 '''popup = EditStatePopup(self)popup.open()def set_default_first_row(self, dt):''' 設(shè)置默認(rèn)第一行為選中'''self.row_controller.select_next(self)def get_states(self):self.db_cursor.execute("SELECT * FROM customers ORDER BY CustomerId ASC")行 = self.db_cursor.fetchall()數(shù)據(jù) = []低 = 0高 = self.total_col_headings - 1對于行中的行:對于我在范圍內(nèi)(長度(行)):data.append([row[i], row[0], [low, high]])低 += self.total_col_headings高 += self.total_col_headingsself.rv_data = [{'text': str(x[0]), 'Index': str(x[1]), 'range': x[2], 'selectable': True} for x in data]類表(BoxLayout):rv = 對象屬性(無)def __init__(self, **kwargs):超級(表,自我).__init__(**kwargs)self.orientation = "垂直"self.header = TableHeader()self.rv = RV(self.header)self.rv.fbind('scroll_x', self.scroll_with_header)self.add_widget(self.header)self.add_widget(self.rv)def scroll_with_header(self, obj, value):self.header.scroll_x = 值類 MainMenu(BoxLayout):states_cities_or_areas = ObjectProperty(無)表 = 對象屬性(無)定義顯示狀態(tài)(自我):self.remove_widgets()self.table = 表()self.states_cities_or_areas.add_widget(self.table)def remove_widgets(self):self.states_cities_or_areas.clear_widgets()類測試應(yīng)用程序(應(yīng)用程序):標(biāo)題=測試"定義構(gòu)建(自我):返回主菜單()如果 __name__ == '__main__':TestApp().run()
test.kv
#:kivy 1.10.0<彈出標(biāo)簽單元格>size_hint:(無,無)身高:30text_size: self.size對齊:左"對齊:中間"<EditStatePopup>:容器:容器size_hint:無,無尺寸:400、275標(biāo)題大小:20# title_font: "Verdana"auto_dismiss: 假盒子布局:方向:垂直"滾動(dòng)視圖:bar_width: 10bar_color: 1, 0, 0, 1 # 紅色bar_inactive_color: 0, 0, 1, 1 # 藍(lán)色effect_cls: "滾動(dòng)效果"滾動(dòng)類型:['條']size_hint:(1,無)網(wǎng)格布局:編號:容器列數(shù):2行默認(rèn)高度:30cols_minimum: {0: 100, 1: 300}# 間距:10, 10# 填充:20、20size_hint:(無,無)高度:self.minimum_height盒子布局:按鈕:大小提示:1, 0.2文本:保存更改"on_release:root.dismiss()按鈕:大小提示:1, 0.2文本:取消更改"on_release: root.dismiss()<可選按鈕>:畫布之前:顏色:rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)長方形:pos: self.pos尺寸:self.sizebackground_color: [1, 0, 0, 1] if self.selected else [1, 1, 1, 1] #深紅色 else深灰色on_press:app.root.table.rv.on_mouse_select(self)<標(biāo)題單元格>size_hint:(無,無)身高:25text_size: self.size對齊:左"對齊:中間"背景_禁用_正常:''disabled_color: (1, 1, 1, 1)畫布之前:顏色:RGBA:1、0.502、0、1長方形:pos: self.pos尺寸:self.size<表頭>:標(biāo)頭:標(biāo)頭bar_width: 0do_scroll: 假size_hint:(1,無)身高:25effect_cls: "滾動(dòng)效果"網(wǎng)格布局:id: 標(biāo)頭行數(shù):1cols_minimum:root.cols_minimumsize_hint:(無,無)寬度:self.minimum_width高度:self.minimum_height<房車>:行控制器:行控制器bar_width: 10bar_color: 1, 0, 0, 1 # 紅色bar_inactive_color: 0, 0, 1, 1 # 藍(lán)色effect_cls: "滾動(dòng)效果"滾動(dòng)類型:['條']數(shù)據(jù):root.rv_data視圖類:可選按鈕"可選回收網(wǎng)格布局:id:row_controllerkey_selection: '可選擇的'列:root.total_col_headingscols_minimum:root.cols_minimumdefault_size:無,dp(26)default_size_hint:1,無size_hint:無,無高度:self.minimum_height寬度:self.minimum_width方向:垂直"多選:真touch_multiselect:真<菜單按鈕@按鈕>:text_size: self.size對齊:中間"padding_x: 5尺寸:(80,30)size_hint:(無,無)背景顏色:90、90、90、90背景正常:''顏色:0、0.517、0.705、1邊框:(0, 10, 0, 0)<主菜單>:states_cities_or_areas: states_cities_or_areas盒子布局:方向:垂直"盒子布局:畫布之前:長方形:pos: self.pos尺寸:self.sizesize_hint_y: 1菜單按鈕:編號:btn文字:'測試'尺寸:(60,30)on_release: root.display_states()盒子布局:畫布之前:長方形:pos: self.pos尺寸:self.size顏色:RGB:(1,1,1)標(biāo)簽:size_hint_x: 45盒子布局:id: states_cities_or_areassize_hint_y: 10標(biāo)簽:size_hint_y: 1
輸出
I am using Python-2.7
and kivy
.
I run test.py
then show a menu Test
.When i click on it then show list
of data.
Can someone tell me how to add vertical scrollbar
on list.
test.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, NumericProperty, DictProperty
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window
from kivy.clock import Clock
Window.size = (600, 325)
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
selected_row = NumericProperty(0)
def get_nodes(self):
nodes = self.get_selectable_nodes()
if self.nodes_order_reversed:
nodes = nodes[::-1]
if not nodes:
return None, None
selected = self.selected_nodes
if not selected: # nothing selected, select the first
self.select_node(nodes[0])
self.selected_row = 0
return None, None
if len(nodes) == 1: # the only selectable node is selected already
return None, None
last = nodes.index(selected[-1])
self.clear_selection()
return last, nodes
def select_next(self):
''' Select next row '''
last, nodes = self.get_nodes()
if not nodes:
return
if last == len(nodes) - 1:
self.select_node(nodes[0])
self.selected_row = nodes[0]
else:
self.select_node(nodes[last + 1])
self.selected_row = nodes[last + 1]
def select_previous(self):
''' Select previous row '''
last, nodes = self.get_nodes()
if not nodes:
return
if not last:
self.select_node(nodes[-1])
self.selected_row = nodes[-1]
else:
self.select_node(nodes[last - 1])
self.selected_row = nodes[last - 1]
def select_current(self):
''' Select current row '''
last, nodes = self.get_nodes()
if not nodes:
return
self.select_node(nodes[self.selected_row])
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
print("on_touch_down: self=", self)
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
class RV(BoxLayout):
data_items = ListProperty([])
row_data = DictProperty({})
col1_data = ListProperty([])
col2_data = ListProperty([])
col1_row_controller = ObjectProperty(None)
col2_row_controller = ObjectProperty(None)
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_states()
Clock.schedule_once(self.set_default_first_row, .0005)
self._request_keyboard()
def _request_keyboard(self):
self._keyboard = Window.request_keyboard(
self._keyboard_closed, self, 'text'
)
if self._keyboard.widget:
# If it exists, this widget is a VKeyboard object which you can use
# to change the keyboard layout.
pass
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def _keyboard_closed(self):
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'down': # keycode[274, 'down'] pressed
# Respond to keyboard down arrow pressed
self.display_keystrokes(keyboard, keycode, text, modifiers)
self.col1_row_controller.select_next()
self.col2_row_controller.select_next()
elif keycode[1] == 'up': # keycode[273, 'up] pressed
# Respond to keyboard up arrow pressed
self.display_keystrokes(keyboard, keycode, text, modifiers)
self.col1_row_controller.select_previous()
self.col2_row_controller.select_previous()
# Keycode is composed of an integer + a string
# If we hit escape, release the keyboard
if keycode[1] == 'escape':
keyboard.release()
# Return True to accept the key. Otherwise, it will be used by
# the system.
return True
def display_keystrokes(self, keyboard, keycode, text, modifiers):
print("
The key", keycode, "have been pressed")
print(" - text is %r" % text)
print(" - modifiers are %r" % modifiers)
def on_keyboard_select(self):
''' Respond to keyboard event to call Popup '''
# setup row data for Popup
self.row_data = self.col1_data[self.col1_row_controller.selected_row]
# call Popup
self.popup_callback()
def on_mouse_select(self, instance):
''' Respond to mouse event to call Popup '''
if (self.col1_row_controller.selected_row != instance.index
or self.col2_row_controller.selected_row != instance.index):
# Mouse clicked on row is not equal to current selected row
self.col1_row_controller.selected_row = instance.index
self.col2_row_controller.selected_row = instance.index
# Hightlight mouse clicked/selected row
self.col1_row_controller.select_current()
self.col2_row_controller.select_current()
# setup row data for Popup
# we can use either col1_data or col2_data because they are duplicate and each stores the same info
self.row_data = self.col1_data[instance.index]
# call Popup
self.popup_callback()
def popup_callback(self):
# enable keyboard request
self._request_keyboard()
def set_default_first_row(self, dt):
''' Set default first row as selected '''
self.col1_row_controller.select_next()
self.col2_row_controller.select_next()
def update(self):
self.col1_data = [{'text': str(x[0]), 'Id': str(x[0]), 'Name': x[1], 'key': 'Id', 'selectable': True}
for x in self.data_items]
self.col2_data = [{'text': x[1], 'Id': str(x[0]), 'Name': x[1], 'key': 'Name', 'selectable': True}
for x in self.data_items]
def get_states(self):
rows = [(1, 'abc'), (1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc'),(1, 'abc')]
i = 0
for row in rows:
self.data_items.append([row[0], row[1], i])
i += 1
print(self.data_items)
self.update()
class MainMenu(BoxLayout):
states_cities_or_areas = ObjectProperty(None)
rv = ObjectProperty(None)
def display_states(self):
self.remove_widgets()
self.rv = RV()
self.states_cities_or_areas.add_widget(self.rv)
def remove_widgets(self):
self.states_cities_or_areas.clear_widgets()
class TestApp(App):
title = "test"
def build(self):
return MainMenu()
if __name__ == '__main__':
TestApp().run()
test.kv
#:kivy 1.10.0
<SelectableButton>:
canvas.before:
Color:
rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
Rectangle:
pos: self.pos
size: self.size
background_color: [1, 0, 0, 1] if self.selected else [1, 1, 1, 1] # dark red else dark grey
on_press: app.root.rv.on_mouse_select(self)
<RV>:
col1_row_controller: col1_row_controller
col2_row_controller: col2_row_controller
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
Label:
size_hint_x: .1
text: "Id"
Label:
size_hint_x: .5
text: "Name"
ScrollView:
id: kr_scroll
do_scroll_x: False
height: 2
BoxLayout:
RecycleView:
size_hint_x: .1
data: root.col1_data
viewclass: 'SelectableButton'
SelectableRecycleGridLayout:
id: col1_row_controller
key_selection: 'selectable'
cols: 1
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
RecycleView:
size_hint_x: .5
data: root.col2_data
viewclass: 'SelectableButton'
SelectableRecycleGridLayout:
id: col2_row_controller
key_selection: 'selectable'
cols: 1
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
<MenuButton@Button>:
text_size: self.size
valign: "middle"
padding_x: 5
size : (80,30)
size_hint : (None, None)
background_color: 90 , 90, 90, 90
background_normal: ''
color: 0, 0.517, 0.705, 1
border: (0, 10, 0, 0)
<MainMenu>:
states_cities_or_areas: states_cities_or_areas
BoxLayout:
orientation: 'vertical'
#spacing : 10
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 1
MenuButton:
id: btn
text: 'Test'
size : (60,30)
on_release: root.display_states()
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
Label:
size_hint_x: 45
BoxLayout:
id: states_cities_or_areas
size_hint_y: 10
Label:
size_hint_y: 1
Question
How to set text right align in only customerId column and other column should be left align?
Solution
Snippet
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
self.text_size = self.size
if index == rv.data[index]['range'][0]:
self.halign = 'right'
else:
self.halign = 'left'
Output
Label - Text grow vertically and wraps at a certain width
A Label that can grow vertically but wraps the text at a certain width:
Label:
size_hint_y: None
text_size: self.width, None
height: self.texture_size[1]
To scroll a GridLayout on it’s X-axis/horizontally and Y-axis/vertically, set size_hint property to (None, None).
ScrollView - ScrollEffect, scroll_type, bar_width, etc.
By default, the ScrollView allows scrolling along both the X and Y axes. You can explicitly disable scrolling on an axis by setting the do_scroll_x or do_scroll_y properties to False.
To scroll a GridLayout on it’s Y-axis/vertically, set the child’s width to that of the ScrollView (size_hint_x=1), and set the size_hint_y property to None:
When scrolling would exceed the bounds of the ScrollView, it uses a ScrollEffect to handle the overscroll.
scroll_type
Sets the type of scrolling to use for the content of the scrollview. Available options are: [‘content’], [‘bars’], [‘bars’, ‘content’]
[‘bars’] Content is scrolled by dragging or swiping the scoll bars.
Grid Layout
cols_minimum
Dict of minimum width for each column. The dictionary keys are the column numbers, e.g. 0, 1, 2…
cols_minimum is a DictProperty and defaults to {}.
Snippets
<RV>:
row_controller: row_controller
bar_width: 10
bar_color: 1, 0, 0, 1 # red
bar_inactive_color: 0, 0, 1, 1 # blue
effect_cls: "ScrollEffect"
scroll_type: ['bars']
data: root.rv_data
viewclass: 'SelectableButton'
SelectableRecycleGridLayout:
id: row_controller
key_selection: 'selectable'
cols: root.total_col_headings
cols_minimum: root.cols_minimum
default_size: None, dp(26)
default_size_hint: 1, None
size_hint: None, None
height: self.minimum_height
width: self.minimum_width
orientation: 'vertical'
multiselect: True
touch_multiselect: True
The following example demonstrates:
- Scrolling of the table header on the X-axis.
- Support scrolling on the X-axis and Y-axis.
- Support scrolling on the Y-axis in the Popup window.
- Works for any columns in database table.
- Varying column width using GridLayout cols_minimum.
- Combined two RecycleView into one as there is no need to have a recycleview just for the ID.
- Selectable buttons.
SQLite Sample Database
chinook SQLite sample database
Example
main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, NumericProperty, DictProperty
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.recycleview import RecycleView
import sqlite3 as lite
import re
Window.size = (600, 325)
class PopupLabelCell(Label):
pass
class EditStatePopup(Popup):
def __init__(self, obj, **kwargs):
super(EditStatePopup, self).__init__(**kwargs)
self.populate_content(obj)
def populate_content(self, obj):
for x in range(len(obj.table_header.col_headings)):
self.container.add_widget(PopupLabelCell(text=obj.table_header.col_headings[x]))
textinput = TextInput(text=str(obj.row_data[x]))
if x == 0:
textinput.readonly = True
self.container.add_widget(textinput)
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
selected_row = NumericProperty(0)
obj = ObjectProperty(None)
def get_nodes(self):
nodes = self.get_selectable_nodes()
if self.nodes_order_reversed:
nodes = nodes[::-1]
if not nodes:
return None, None
selected = self.selected_nodes
if not selected: # nothing selected, select the first
self.selected_row = 0
self.select_row(nodes)
return None, None
if len(nodes) == 1: # the only selectable node is selected already
return None, None
last = nodes.index(selected[-1])
self.clear_selection()
return last, nodes
def select_next(self, obj):
''' Select next row '''
self.obj = obj
last, nodes = self.get_nodes()
if not nodes:
return
if last == len(nodes) - 1:
self.selected_row = nodes[0]
else:
self.selected_row = nodes[last + 1]
self.selected_row += self.obj.total_col_headings
self.select_row(nodes)
def select_previous(self, obj):
''' Select previous row '''
self.obj = obj
last, nodes = self.get_nodes()
if not nodes:
return
if not last:
self.selected_row = nodes[-1]
else:
self.selected_row = nodes[last - 1]
self.selected_row -= self.obj.total_col_headings
self.select_row(nodes)
def select_current(self, obj):
''' Select current row '''
self.obj = obj
last, nodes = self.get_nodes()
if not nodes:
return
self.select_row(nodes)
def select_row(self, nodes):
col = self.obj.rv_data[self.selected_row]['range']
for x in range(col[0], col[1] + 1):
self.select_node(nodes[x])
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
print("on_touch_down: self=", self)
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
self.text_size = self.size
if index == rv.data[index]['range'][0]:
self.halign = 'right'
else:
self.halign = 'left'
class HeaderCell(Label):
pass
class TableHeader(ScrollView):
"""Fixed table header that scrolls x with the data table"""
header = ObjectProperty(None)
col_headings = ListProperty([])
cols_minimum = DictProperty({})
def __init__(self, **kwargs):
super(TableHeader, self).__init__(**kwargs)
self.db = lite.connect('chinook.db')
self.db_cursor = self.db.cursor()
self.get_table_column_headings()
def get_table_column_headings(self):
self.db_cursor.execute("PRAGMA table_info(customers)")
col_headings = self.db_cursor.fetchall()
for col_heading in col_headings:
data_type = col_heading[2]
if data_type == "INTEGER":
self.cols_minimum[col_heading[0]] = 100
else:
self.cols_minimum[col_heading[0]] = int(re.findall(r'd+', data_type).pop(0)) * 5
self.col_headings.append(col_heading[1])
self.header.add_widget(HeaderCell(text=col_heading[1], width=self.cols_minimum[col_heading[0]]))
class RV(RecycleView):
row_data = ()
rv_data = ListProperty([])
row_controller = ObjectProperty(None)
total_col_headings = NumericProperty(0)
cols_minimum = DictProperty({})
table_header = ObjectProperty(None)
def __init__(self, table_header, **kwargs):
super(RV, self).__init__(**kwargs)
self.table_header = table_header
self.total_col_headings = len(table_header.col_headings)
self.cols_minimum = table_header.cols_minimum
self.database_connection()
self.get_states()
Clock.schedule_once(self.set_default_first_row, .0005)
self._request_keyboard()
def database_connection(self):
self.db = lite.connect('chinook.db')
self.db_cursor = self.db.cursor()
def _request_keyboard(self):
self._keyboard = Window.request_keyboard(
self._keyboard_closed, self, 'text'
)
if self._keyboard.widget:
# If it exists, this widget is a VKeyboard object which you can use
# to change the keyboard layout.
pass
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def _keyboard_closed(self):
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'down': # keycode[274, 'down'] pressed
# Respond to keyboard down arrow pressed
self.display_keystrokes(keyboard, keycode, text, modifiers)
self.row_controller.select_next(self)
elif keycode[1] == 'up': # keycode[273, 'up] pressed
# Respond to keyboard up arrow pressed
self.display_keystrokes(keyboard, keycode, text, modifiers)
self.row_controller.select_previous(self)
elif len(modifiers) > 0 and modifiers[0] == 'ctrl' and text == 'e': # ctrl + e pressed
# Respond to keyboard ctrl + e pressed, and call Popup
self.display_keystrokes(keyboard, keycode, text, modifiers)
self.on_keyboard_select()
# Keycode is composed of an integer + a string
# If we hit escape, release the keyboard
if keycode[1] == 'escape':
keyboard.release()
# Return True to accept the key. Otherwise, it will be used by
# the system.
return True
def display_keystrokes(self, keyboard, keycode, text, modifiers):
print("
The key", keycode, "have been pressed")
print(" - text is %r" % text)
print(" - modifiers are %r" % modifiers)
def on_keyboard_select(self):
''' Respond to keyboard event to call Popup '''
# setup row data for Popup
self.setup_row_data(self.rv_data[self.row_controller.selected_row]['Index'])
# call Popup
self.popup_callback()
def on_mouse_select(self, instance):
''' Respond to mouse event to call Popup '''
if self.row_controller.selected_row != instance.index:
# Mouse clicked on row is not equal to current selected row
self.row_controller.selected_row = instance.index
# Hightlight mouse clicked/selected row
self.row_controller.select_current(self)
# setup row data for Popup
self.setup_row_data(self.rv_data[instance.index]['Index'])
# call Popup
self.popup_callback()
# enable keyboard request
self._request_keyboard()
def setup_row_data(self, value):
self.db_cursor.execute("SELECT * FROM customers WHERE CustomerId=?", value)
self.row_data = self.db_cursor.fetchone()
def popup_callback(self):
''' Instantiate and Open Popup '''
popup = EditStatePopup(self)
popup.open()
def set_default_first_row(self, dt):
''' Set default first row as selected '''
self.row_controller.select_next(self)
def get_states(self):
self.db_cursor.execute("SELECT * FROM customers ORDER BY CustomerId ASC")
rows = self.db_cursor.fetchall()
data = []
low = 0
high = self.total_col_headings - 1
for row in rows:
for i in range(len(row)):
data.append([row[i], row[0], [low, high]])
low += self.total_col_headings
high += self.total_col_headings
self.rv_data = [{'text': str(x[0]), 'Index': str(x[1]), 'range': x[2], 'selectable': True} for x in data]
class Table(BoxLayout):
rv = ObjectProperty(None)
def __init__(self, **kwargs):
super(Table, self).__init__(**kwargs)
self.orientation = "vertical"
self.header = TableHeader()
self.rv = RV(self.header)
self.rv.fbind('scroll_x', self.scroll_with_header)
self.add_widget(self.header)
self.add_widget(self.rv)
def scroll_with_header(self, obj, value):
self.header.scroll_x = value
class MainMenu(BoxLayout):
states_cities_or_areas = ObjectProperty(None)
table = ObjectProperty(None)
def display_states(self):
self.remove_widgets()
self.table = Table()
self.states_cities_or_areas.add_widget(self.table)
def remove_widgets(self):
self.states_cities_or_areas.clear_widgets()
class TestApp(App):
title = "test"
def build(self):
return MainMenu()
if __name__ == '__main__':
TestApp().run()
test.kv
#:kivy 1.10.0
<PopupLabelCell>
size_hint: (None, None)
height: 30
text_size: self.size
halign: "left"
valign: "middle"
<EditStatePopup>:
container: container
size_hint: None, None
size: 400, 275
title_size: 20
# title_font: "Verdana"
auto_dismiss: False
BoxLayout:
orientation: "vertical"
ScrollView:
bar_width: 10
bar_color: 1, 0, 0, 1 # red
bar_inactive_color: 0, 0, 1, 1 # blue
effect_cls: "ScrollEffect"
scroll_type: ['bars']
size_hint: (1, None)
GridLayout:
id: container
cols: 2
row_default_height: 30
cols_minimum: {0: 100, 1: 300}
# spacing: 10, 10
# padding: 20, 20
size_hint: (None, None)
height: self.minimum_height
BoxLayout:
Button:
size_hint: 1, 0.2
text: "Save Changes"
on_release:
root.dismiss()
Button:
size_hint: 1, 0.2
text: "Cancel Changes"
on_release: root.dismiss()
<SelectableButton>:
canvas.before:
Color:
rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
Rectangle:
pos: self.pos
size: self.size
background_color: [1, 0, 0, 1] if self.selected else [1, 1, 1, 1] # dark red else dark grey
on_press: app.root.table.rv.on_mouse_select(self)
<HeaderCell>
size_hint: (None, None)
height: 25
text_size: self.size
halign: "left"
valign: "middle"
background_disabled_normal: ''
disabled_color: (1, 1, 1, 1)
canvas.before:
Color:
rgba: 1, 0.502, 0, 1
Rectangle:
pos: self.pos
size: self.size
<TableHeader>:
header: header
bar_width: 0
do_scroll: False
size_hint: (1, None)
height: 25
effect_cls: "ScrollEffect"
GridLayout:
id: header
rows: 1
cols_minimum: root.cols_minimum
size_hint: (None, None)
width: self.minimum_width
height: self.minimum_height
<RV>:
row_controller: row_controller
bar_width: 10
bar_color: 1, 0, 0, 1 # red
bar_inactive_color: 0, 0, 1, 1 # blue
effect_cls: "ScrollEffect"
scroll_type: ['bars']
data: root.rv_data
viewclass: 'SelectableButton'
SelectableRecycleGridLayout:
id: row_controller
key_selection: 'selectable'
cols: root.total_col_headings
cols_minimum: root.cols_minimum
default_size: None, dp(26)
default_size_hint: 1, None
size_hint: None, None
height: self.minimum_height
width: self.minimum_width
orientation: 'vertical'
multiselect: True
touch_multiselect: True
<MenuButton@Button>:
text_size: self.size
valign: "middle"
padding_x: 5
size : (80,30)
size_hint : (None, None)
background_color: 90 , 90, 90, 90
background_normal: ''
color: 0, 0.517, 0.705, 1
border: (0, 10, 0, 0)
<MainMenu>:
states_cities_or_areas: states_cities_or_areas
BoxLayout:
orientation: 'vertical'
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 1
MenuButton:
id: btn
text: 'Test'
size : (60,30)
on_release: root.display_states()
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
Label:
size_hint_x: 45
BoxLayout:
id: states_cities_or_areas
size_hint_y: 10
Label:
size_hint_y: 1
Output
這篇關(guān)于Python:如何在 RecycleView 中添加垂直滾動(dòng)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!