从零开始开发python和qt项目(三)

0_1524119219399_111.jpg

接下来处理qt界面的逻辑

qt控制爬虫逻辑

# 每20分钟爬新图片
        
self.timerThread = QtCore.QTimer()
        
self.timerThread.setInterval(1000 * 60 * 20)
        
self.timerThread.timeout.connect(self._thread.start)
        
self.timerThread.start()

爬虫会下载图片,造成gui画面卡顿,所以我放在线程中进行,线程里就直接调爬虫命令

class MyThread(QtCore.QThread):

    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)

    def run(self):
        handleTimer()

爬虫下载的图片,需要在qt中显示,我用QFileSystemWatcher监视文件夹,别问我为啥不在下载后通知qt,跨线程通信伤不起

self._watcher = QtCore.QFileSystemWatcher()

if not os.path.exists('cache'):
    os.makedirs('cache')
self._watcher.addPath(os.path.join(currentPath, 'cache'))
self._watcher.directoryChanged.connect(self.handleWatcher)

#监视文件夹更新
    def handleWatcher(self, path):
        for (dirpath, dirnames, filenames) in os.walk(qstring_to_str(path)):
            for file in filenames:
                p = (os.path.join(currentPath, 'cache', file))
                self.addImg(p)


如果有新图片,添加到数组中

    def addImg(self, name):
        # print('ad==',name)
        if not name in self._names:
            self._names.append(name)

每10s轮换一张图片,也是用定时器实现

self._timer = QtCore.QTimer()
self._timer.setInterval(1000 * 10)
self._timer.timeout.connect(self.playImg)
self._timer.start()

时间一到,就把图片塞给label,这样界面就有图片了,关于QPixmap,吐槽一下,在win10测的好好的,一到win7就不好用,各种路径都试了,只好放弃win7

#定义槽
    @QtCore.pyqtSlot('PyQt_PyObject')
    def playImg(self):

        if self._currentIndex < len(self._names):
            path = self._names[self._currentIndex]
            pix = QtGui.QPixmap(path)

            self.ui.label.setPixmap(pix)
            self._currentIndex += 1

程序开发差不多了,接下来,打包成exe

未完待续

posted @ 2021-11-01 14:39  踏月清风  阅读(19)  评论(0编辑  收藏  举报