Qt for Python记录4——时钟和两种方式显示图片

目录

 

一.定时器的用法

1.实例化对象

2.设置时钟的周期事件

3.时钟开始

4.时钟结束

5.样例代码

二.显示图片

1.显示opencv里的图片

2.显示磁盘中的图片


一.定时器的用法

1.实例化对象

定时器比较简单,因为是不需要显示的组件,所以我们并不用过多的编写一些参数,只需要实例化这个对象就可以了。

from PyQt5.QtCore import QTimer
self.timer=QTimer()

2.设置时钟的周期事件

直接把事件绑定到这个函数

self.timer.timeout.connect(self.function)
def function(self):
    …………

3.时钟开始

时钟的计时开始,只需要很简单的把时钟周期添加上就可以了

self.timer.start(1000)#后面是毫秒

4.时钟结束

直接调用stop就行

self.timer.stop()

5.样例代码

这是网上搜索的一个显示当前时间的一个代码:对不起原作者我忘记我从哪儿复制来的了

import sys
from PyQt5.QtWidgets import QWidget,QPushButton,QApplication,QListWidget,QGridLayout,QLabel
from PyQt5.QtCore import QTimer,QDateTime

class WinForm(QWidget):
    def __init__(self,parent=None):
        super(WinForm, self).__init__(parent)
        #设置标题
        self.setWindowTitle('QTimer demo')

        #实例化一些控件
        self.listFile=QListWidget()
        self.lable=QLabel('显示当前时间')
        self.startBtn=QPushButton('开始')
        self.endBtn=QPushButton('结束')

        #栅格布局
        layout=QGridLayout()

        #初始化一个定时器
        self.timer=QTimer()
        #定时器结束,触发showTime方法
        self.timer.timeout.connect(self.showTime)

        #添加控件到栅格指定位置
        layout.addWidget(self.lable,0,0,1,2)
        layout.addWidget(self.startBtn,1,0)
        layout.addWidget(self.endBtn,1,1)

        #开始结束按钮点击触发相应的槽函数
        self.startBtn.clicked.connect(self.startTimer)
        self.endBtn.clicked.connect(self.endTimer)

        #设置布局方式
        self.setLayout(layout)
    def showTime(self):
        #获取系统当前时间
        time=QDateTime.currentDateTime()
        #设置系统时间的显示格式
        timeDisplay=time.toString('yyyy-MM-dd hh:mm:ss dddd')
        #在标签上显示时间
        self.lable.setText(timeDisplay)
    def startTimer(self):
        #设置时间间隔并启动定时器
        self.timer.start(1000)
        #设置开始按钮不可点击,结束按钮可点击
        self.startBtn.setEnabled(False)
        self.endBtn.setEnabled(True)

    def endTimer(self):
        #停止定时器
        self.timer.stop()
        #结束按钮不可点击,开始按钮可以点击
        self.startBtn.setEnabled(True)
        self.endBtn.setEnabled(False)
if __name__ == '__main__':
    app=QApplication(sys.argv)
    form=WinForm()
    form.show()
    sys.exit(app.exec_())

二.显示图片

核心都是创建一个Qimage对象

所以,我们需要引用:

from PyQt5.QtGui import QImage, QPixmap

1.显示opencv里的图片

对于opencv里的图片,我们不能直接加载,还需要对通道做一些处理,然后把它转换成一个Qimage对象

        height, width, channel = self.img.shape
        bytesPerline = 3 * width
        self.qImg = QImage(self.img.data, width, height, bytesPerline, QImage.Format_RGB888).rgbSwapped()
        # 将QImage显示出来
        self.label.setPixmap(QPixmap.fromImage(self.qImg))

2.显示磁盘中的图片

不用像第一种方法那么复杂,直接这样就可以显示图片了

jpg = QtGui.QPixmap("4.jpg")
self.label.setPixmap(jpg)

但是我们的label可能有不同大小,对于缩放图片,我们可以把图像的大小给修改为我们想要的大小

jpg = QtGui.QPixmap("4.jpg").scaled(self.label.width(), self.label.height())
self.label.setPixmap(jpg)
发布了63 篇原创文章 · 获赞 38 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u011017694/article/details/100521642
今日推荐