HarmonyOS NEXT 使用Text实现部分文本高亮和超链接样式

本示例通过自定义Span类型,在Text组件中使用ForEach遍历,根据不同的Span类型生成不同样式和功能的Span组件,实现部分文本高亮和超链接。

效果图预览

使用说明

  1. 点击超链接,根据链接类型出现相应提示弹窗。
  2. 长按消息卡片出现提示弹窗。

实现思路

  1. 定义 CustomSpanType 枚举类型,此处定义了 Normal、Hashtag、Mention、VideoLink 和 DetailLink 五种类型。
export enum CustomSpanType {
  Normal, // 普通文本,不含任何特殊格式或标记
  Hashtag, // 话题标签
  Mention, // @提及
  VideoLink, // 视频链接
  DetailLink // 正文详情
}
  1. 创建 CustomSpan 数据类,用于表示不同类型的 Span 对象。
export class CustomSpan {
  type: CustomSpanType; // 文本类型
  content: string; // 文本内容
  url?: string; // 跳转的链接地址

  constructor(type: CustomSpanType = CustomSpanType.Normal, content: string, url?: string) {
    this.type = type;
    this.content = content;
    if (url) {
      this.url = url;
    }
  }
}
  1. 使用 Text 组件结合 ForEach 方法遍历 spans 中的 CustomSpan 对象,根据不同的 Span 类型生成不同样式和功能的 Span 组件。
Text() {
  ForEach(this.spans, (item: CustomSpan) => {
    if (item.type === CustomSpanType.Normal) {
      Span(item.content)
        .fontSize($r('app.string.ohos_id_text_size_body1'))
    } else if (item.type === CustomSpanType.Hashtag || item.type === CustomSpanType.Mention || item.type === CustomSpanType.DetailLink) {
      TextLinkSpan({ item: item })
    } else {
      VideoLinkSpan({ item: item })
    }
  })
}
.width($r('app.string.styled_text_layout_100'))
.fontSize($r('app.string.ohos_id_text_size_body1'))
.margin({ top: $r('app.string.ohos_id_card_margin_start') })
  1. 对于 Normal 类型的 Span,直接使用 Span 组件展示文本内容,并设置相应的样式。
Span(item.content)
  .fontSize($r('app.string.ohos_id_text_size_body1'))
  1. 对于 Hashtag、Mention 和 DetailLink 类型的 Span,在 TextLinkSpan 组件中添加带有超链接功能的 Span 组件,根据 CustomSpan 的类型和内容,实现对应的样式和交互功能,例如显示提示信息或执行其他操作。
@Component
struct TextLinkSpan {
  @State linkBackgroundColor: Color | Resource = Color.Transparent; // 超链接背景色
  private item: CustomSpan = new CustomSpan(CustomSpanType.Normal, '');
  @State myItem: CustomSpan = this.item;

  aboutToAppear(): void {
    // LazyForEach中Text组件嵌套自定义组件会有数据初次不渲染问题,异步修改状态变量更新视图
    setTimeout(() => {
      this.myItem = this.item;
    })
  }

  build(){
    Span(this.myItem.content)
      .fontColor($r('app.color.styled_text_link_font_color'))// 超链接字体颜色
      .fontSize($r('app.string.ohos_id_text_size_body1'))
      .textBackgroundStyle({ color: this.linkBackgroundColor })
      .onClick(() => {
        this.linkBackgroundColor = $r('app.color.styled_text_link_clicked_background_color'); // 点击后的背景色
        setTimeout(() => {
          this.linkBackgroundColor = Color.Transparent;
        }, BACKGROUND_CHANGE_DELAY)
        // 根据文本超链接的类型做相应处理
        if (this.myItem.type === CustomSpanType.Hashtag) {
          promptAction.showToast({
            message: $r('app.string.styled_text_hashtag_toast_message')
          });
        } else if (this.myItem.type === CustomSpanType.Mention) {
          promptAction.showToast({
            message: $r('app.string.styled_text_user_page_toast_message')
          });
        } else {
          promptAction.showToast({
            message: $r('app.string.styled_text_content_details_toast_message')
          });
        }
      })
  }
}
  1. 对于 VideoLink 类型的 Span,使用 VideoLinkSpan 组件添加图标和超链接功能,在点击事件中显示提示信息或执行跳转视频页操作。
@Component
struct VideoLinkSpan {
  @State linkBackgroundColor: Color | Resource = Color.Transparent;
  private item: CustomSpan = new CustomSpan(CustomSpanType.Normal, '');
  @State myItem: CustomSpan = this.item;

  aboutToAppear(): void {
    // LazyForEach中Text组件嵌套自定义组件会有数据初次不渲染问题,异步修改状态变量更新视图
    setTimeout(() => {
      this.myItem = this.item;
    })
  }

  build() {
    ContainerSpan() {
      ImageSpan($r('app.media.styled_text_ic_public_video'))
        .height($r('app.integer.styled_text_video_link_icon_height'))
        .verticalAlign(ImageSpanAlignment.CENTER)
      Span(this.myItem.content)
        .fontColor($r('app.color.styled_text_link_font_color'))
        .fontSize($r('app.string.ohos_id_text_size_body1'))
        .onClick(() => {
          this.linkBackgroundColor = $r('app.color.styled_text_link_clicked_background_color');
          setTimeout(() => {
            this.linkBackgroundColor = Color.Transparent;
          }, BACKGROUND_CHANGE_DELAY)
          promptAction.showToast({
            message: $r('app.string.styled_text_video_function_message')
          });
        })
    }
    .textBackgroundStyle({ color: this.linkBackgroundColor })
  }
}

高性能知识点

本示例使用了LazyForEach进行数据懒加载

工程结构&模块类型

styledtext                                   // har类型
|---/src/main/ets/mock                        
|   |---MockData.ets                         // mock数据
|---/src/main/ets/model                        
|   |---DataSource.ets                       // 列表数据模型                        
|   |---TextModel.ets                        // 数据类型定义
|---/src/main/ets/pages                        
|   |---StyledText.ets                       // 视图层-主页面

模块依赖

  1. 本实例依赖common模块中的资源文件。
  2. 本示例依赖动态路由模块来实现页面的动态加载。

最后

有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)资料用来跟着学习是非常有必要的。 

这份鸿蒙(HarmonyOS NEXT)资料包含了鸿蒙开发必掌握的核心知识要点,内容包含了ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)技术知识点。

希望这一份鸿蒙学习资料能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

如果你是一名有经验的资深Android移动开发、Java开发、前端开发、对鸿蒙感兴趣以及转行人员,可以直接领取这份资料

 获取这份完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

鸿蒙(HarmonyOS NEXT)最新学习路线

  •  HarmonOS基础技能

  • HarmonOS就业必备技能 
  •  HarmonOS多媒体技术

  • 鸿蒙NaPi组件进阶

  • HarmonOS高级技能

  • 初识HarmonOS内核 
  • 实战就业级设备开发

 有了路线图,怎么能没有学习资料呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)鸿蒙(OpenHarmony )开发入门教学视频,内容包含:ArkTS、ArkUI、Web开发、应用模型、资源分类…等知识点。

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

《鸿蒙 (OpenHarmony)开发入门教学视频》

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

OpenHarmony北向、南向开发环境搭建

图片

 《鸿蒙开发基础》

  • ArkTS语言
  • 安装DevEco Studio
  • 运用你的第一个ArkTS应用
  • ArkUI声明式UI开发
  • .……

图片

 《鸿蒙开发进阶》

  • Stage模型入门
  • 网络管理
  • 数据管理
  • 电话服务
  • 分布式应用开发
  • 通知与窗口管理
  • 多媒体技术
  • 安全技能
  • 任务管理
  • WebGL
  • 国际化开发
  • 应用测试
  • DFX面向未来设计
  • 鸿蒙系统移植和裁剪定制
  • ……

图片

《鸿蒙进阶实战》

  • ArkTS实践
  • UIAbility应用
  • 网络案例
  • ……

图片

 获取以上完整鸿蒙HarmonyOS学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料

总结

总的来说,华为鸿蒙不再兼容安卓,对中年程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,他们才能在这个变革的时代中立于不败之地。 

  • 17
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过重载QPlainTextEdit的paintEvent()函数,自定义绘制行号的方式,然后在selectionChanged()信号中重新绘制行。以下是一个简单的实现示例: ```python from PyQt5.QtGui import QTextCursor, QColor, QPainter from PyQt5.QtWidgets import QPlainTextEdit class LineNumberTextEdit(QPlainTextEdit): def __init__(self, parent=None): super(LineNumberTextEdit, self).__init__(parent) self.current_line = None self.line_number_area_width = 50 def paintEvent(self, event): super(LineNumberTextEdit, self).paintEvent(event) if self.current_line: painter = QPainter(self.viewport()) painter.fillRect(0, self.current_line * self.fontMetrics().height(), self.width(), self.fontMetrics().height(), QColor(255, 200, 0)) def resizeEvent(self, event): super(LineNumberTextEdit, self).resizeEvent(event) self.updateLineNumberAreaWidth() def lineNumberAreaWidth(self): digits = 1 count = max(1, self.blockCount()) while count >= 10: count /= 10 digits += 1 return self.fontMetrics().width('9') * digits def updateLineNumberAreaWidth(self): self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0) def lineNumberAreaPaintEvent(self, event): painter = QPainter(self.lineNumberArea) painter.fillRect(event.rect(), QColor(240, 240, 240)) block = self.firstVisibleBlock() block_number = block.blockNumber() top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top() bottom = top + self.blockBoundingRect(block).height() while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): number = str(block_number + 1) painter.setPen(QColor(150, 150, 150)) painter.drawText(0, top, self.lineNumberArea.width(), self.fontMetrics().height(), Qt.AlignRight, number) block = block.next() top = bottom bottom = top + self.blockBoundingRect(block).height() block_number += 1 def lineNumberAreaMousePressEvent(self, event): self.current_line = None self.viewport().update() def lineNumberAreaMouseMoveEvent(self, event): cursor = self.cursorForPosition(event.pos()) if not cursor.isNull(): self.current_line = cursor.blockNumber() self.viewport().update() def lineNumberAreaLeaveEvent(self, event): self.current_line = None self.viewport().update() def lineNumberAreaSizeHint(self): return QSize(self.lineNumberAreaWidth(), 0) def updateLineNumberArea(self, rect): self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height()) def resizeLineNumberArea(self): self.lineNumberArea.setGeometry(0, 0, self.lineNumberAreaWidth(), self.height()) def showEvent(self, event): super(LineNumberTextEdit, self).showEvent(event) if not self.lineNumberArea: self.lineNumberArea = LineNumberArea(self) self.connect(self.lineNumberArea, SIGNAL('updateLineNumberArea'), self.updateLineNumberArea) self.connect(self.lineNumberArea, SIGNAL('resizeLineNumberArea'), self.resizeLineNumberArea) self.lineNumberArea.show() def hideEvent(self, event): super(LineNumberTextEdit, self).hideEvent(event) if self.lineNumberArea: self.lineNumberArea.hide() def scrollContentsBy(self, dx, dy): super(LineNumberTextEdit, self).scrollContentsBy(dx, dy) self.lineNumberArea.scroll(0, dy) def resizeEvent(self, event): super(LineNumberTextEdit, self).resizeEvent(event) self.lineNumberArea.resizeLineNumberArea() def selectionChanged(self): super(LineNumberTextEdit, self).selectionChanged() self.viewport().update() def keyPressEvent(self, event): if event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_C: cursor = self.textCursor() selected_text = cursor.selectedText() lines = selected_text.split('\n') if len(lines) > 1: for i, line in enumerate(lines): if i == len(lines) - 1: lines[i] = line else: lines[i] = line + '\n' QApplication.clipboard().setText(selected_text) else: super(LineNumberTextEdit, self).keyPressEvent(event) else: super(LineNumberTextEdit, self).keyPressEvent(event) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.current_line = None self.viewport().update() super(LineNumberTextEdit, self).mousePressEvent(event) def mouseMoveEvent(self, event): cursor = self.cursorForPosition(event.pos()) if not cursor.isNull(): self.current_line = cursor.blockNumber() self.viewport().update() super(LineNumberTextEdit, self).mouseMoveEvent(event) def leaveEvent(self, event): self.current_line = None self.viewport().update() super(LineNumberTextEdit, self).leaveEvent(event) def focusInEvent(self, event): super(LineNumberTextEdit, self).focusInEvent(event) self.current_line = None self.viewport().update() def focusOutEvent(self, event): super(LineNumberTextEdit, self).focusOutEvent(event) self.current_line = None self.viewport().update() ``` 在这个示例中,我们继承了QPlainTextEdit并添加了一些自定义行为。其中,我们使用了一个LineNumberArea类来显示行号,并在编辑器的paintEvent()中绘制行。 在构造函数中,我们初始化了一些变量和信号连。我们还创建了一个LineNumberArea对象,并将其与updateLineNumberArea()和resizeLineNumberArea()信号连起来。这样,我们可以在编辑器的大小发生变化时调整行号区域的大小。 在paintEvent()函数中,我们首先调用父类的paintEvent()函数,以便在编辑器中绘制文本。然后,如果当前行不为空,我们绘制黄色矩形来当前行。 在resizeEvent()函数中,我们更新行号区域的宽度,并在updateLineNumberArea()函数中更新行号区域的绘图。 在selectionChanged()函数中,我们重新绘制行。 在mousePressEvent()、mouseMoveEvent()和leaveEvent()函数中,我们设置当前行为None,并在viewport()上调用update()函数,从而清除行。 最后,我们覆盖了QPlainTextEdit的keyPressEvent()函数,以便在按下Ctrl+C键时复制多行文本。我们还覆盖了focusInEvent()和focusOutEvent()函数,以便在编辑器失去焦点时清除行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值