如何在Kivy Popup中设置加粗标题?
给Kivy Popup设置加粗标题的解决方法
问题描述
需要为Popup设置加粗标题,尝试在kv文件中直接格式化title属性,但运行出错。相关代码如下:
kv文件代码
<InfoPopup>: title: '[b]{}[/b]'.format(root.title) size_hint: None, None size: '400dp', '260dp' BoxLayout: orientation: 'vertical' Label: text: root.message text_size: self.size valign: 'middle' halign: root.message_halign padding_x: root.message_padding_x markup: True
Python类代码
class InfoPopup(FormPopup): OPTION_OK = 'ok' message = StringProperty() message_halign = OptionProperty( 'center', options=['left', 'center', 'right', 'justify'] ) message_padding_x = NumericProperty() text_ok = StringProperty('Ok') def _handle_keyboard(self, window, key, *largs): if key == 13 or key == 32: # 回车键和空格键用于确认,ESC键默认关闭弹窗 self.submit_data(self.OPTION_OK) return True return super(InfoPopup, self)._handle_keyboard(window, key, *largs)
调用代码
popup = InfoPopup(title='Book metadata error' if title is None else title, message=str(message), message_halign='left') popup.open()
错误原因
- 循环引用问题:kv中使用
root.title格式化后再赋值给title,导致属性无限循环引用,触发错误。 - 默认标题不支持标记解析:Popup默认的标题显示控件(
title_label)的markup属性默认是False,即使没有循环问题,也不会解析[b]这类加粗标记。
解决方法
下面提供两种可行方案:
方案一:修改默认标题控件的标记支持
1. 添加原始标题属性
在InfoPopup类中新增一个属性存储未格式化的原始标题,避免循环引用:
class InfoPopup(FormPopup): OPTION_OK = 'ok' original_title = StringProperty() # 新增属性存储原始标题 message = StringProperty() message_halign = OptionProperty( 'center', options=['left', 'center', 'right', 'justify'] ) message_padding_x = NumericProperty() text_ok = StringProperty('Ok') def _handle_keyboard(self, window, key, *largs): if key == 13 or key == 32: self.submit_data(self.OPTION_OK) return True return super(InfoPopup, self)._handle_keyboard(window, key, *largs)
2. 配置kv文件
开启默认标题控件的markup支持,并基于原始标题生成加粗标题:
<InfoPopup>: title_label.markup: True # 开启标题的标记解析 title: '[b]{}[/b]'.format(root.original_title) # 基于原始标题生成加粗效果 size_hint: None, None size: '400dp', '260dp' BoxLayout: orientation: 'vertical' Label: text: root.message text_size: self.size valign: 'middle' halign: root.message_halign padding_x: root.message_padding_x markup: True
3. 修改调用代码
调用时传入original_title参数:
popup = InfoPopup( original_title='Book metadata error' if title is None else title, message=str(message), message_halign='left' ) popup.open()
方案二:自定义Popup标题栏
直接替换默认的标题栏,使用支持标记解析的Label实现加粗标题,无需修改Python类:
<InfoPopup>: size_hint: None, None size: '400dp', '260dp' BoxLayout: orientation: 'vertical' # 自定义加粗标题栏 Label: text: '[b]{}[/b]'.format(root.title) markup: True size_hint_y: None height: '40dp' padding_x: '10dp' valign: 'middle' color: 0,0,0,1 # 可根据需求调整标题颜色 # 原内容显示区域 Label: text: root.message text_size: self.size valign: 'middle' halign: root.message_halign padding_x: root.message_padding_x markup: True
调用代码无需修改,保持原来的传参方式即可。
内容的提问来源于stack exchange,提问作者Dart Vinnie
相关产品推荐
相关产品推荐

