用Python实现安卓中Toast效果

欢迎加入QQ群:853840665,一块学习分享资料

用Python实现安卓中Toast效果

转载自:http://baijiahao.baidu.com/builder/preview/s?id=1622985718361002416

做过安卓开发的同学都知道,安卓上的Toast是个很好用的通知型工具,但是转到Windows上开发,你会发现基本上只有丑到爆的Dialog,MessageBox,或者右下角提示框。

用Python实现安卓中Toast效果

MessageBox

用Python实现安卓中Toast效果

Notifier

那么Window上可不可以实现安卓上Toast的功能呢?答案是肯定的。先给你们看看截图

用Python实现安卓中Toast效果

默认样式

用Python实现安卓中Toast效果

可以更改背景颜色

用Python实现安卓中Toast效果

可以任意设置字体和大小

用Python实现安卓中Toast效果

可以设置字体颜色

用Python实现安卓中Toast效果

在窗口中弹出一个Toast

看了这些截图有没有感觉在窗口中弹出这么一个Toast比MessageBox好看多了。

而且调用也很简单,跟安卓中类似,一句即可实现通知,只是方法名书写方式保持跟python规范一致。

用Python实现安卓中Toast效果

显示在屏幕*,显示时间定义为长

用Python实现安卓中Toast效果

显示在控件*,并修改默认背景色

下面简要说一下实现方法:

一:首先要创建一个窗体:

窗体创建之后,把窗体进行隐藏

用Python实现安卓中Toast效果

二:定义必要的属性

包括背景颜色,字体颜色,要显示的字体,依托的父类(若为None,则显示在屏幕*),Toast的坐标

用Python实现安卓中Toast效果

三:重写paintEvent方法

这一步当然是必须的啦,不管绘制什么图形,都要重写此方法。

在方法中绘制Toast的外形和要显示的文字,代码如下

height = self.get_font_size()
width = len(self._text) * height * 0.8
if height < self._min_height:
height = self._min_height
else:
height = self._min_height * 2
print("resize height:%d" % height)

if width < self._min_width:
width = self._min_width
self.resize(width, height)
if self._x_pos != 0 and self._y_pos != 0:
self.move(self._x_pos - width / 2, self._y_pos - height / 2)
print("move widget")
painter = QPainter(self)
painter.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
rectangle = QRectF(0, 0, width, height)
brush = QBrush(QColor(self._background_color), Qt.SolidPattern)
painter.setBrush(brush)
painter.setPen(QPen(QColor(self._background_color)))
painter.drawRoundedRect(rectangle, height / 2, height / 2, Qt.AbsoluteSize)
self._draw_text(painter, rectangle, self._text)

四:定时关闭

 

用Python实现安卓中Toast效果

实现这最重要的四步,基本功能就能实现了。此外我还实现了渐变显示,感兴趣的可以加关注要源码。