pyqt5 pyinstaller 打包 QThread QLable QscrollArea 滑动 红果短剧

pyqt5 pyinstaller 打包 QThread QLable QscrollArea 滑动 红果短剧_第1张图片pyqt5 pyinstaller 打包 QThread QLable QscrollArea 滑动 红果短剧_第2张图片

废话 不多说,直接上代码!!!

UI.py

        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
       self.scrollArea.setGeometry(QtCore.QRect(20, 130, 541, 511))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")

主文件

 # 自定义  QLable 实现 可点击 方法
class ClickableQLabel(QLabel):
    clicked = pyqtSignal()
    def __init__(self, parent=None):
        super().__init__(parent)
    def mousePressEvent(self, event):
        self.clicked.emit()

# 渲染并处理 获取的 短剧信息
def select_function_callback(self, result):
    self.pushButton_select.setText('点击查询')
    if result.get("data"):
        self.duanju_select_data = result.get("data")
        self.image_label.setVisible(False)
        self.scrollArea.setVisible(True)
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 539, 510))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        data_num = len(result.get('data'))
        if data_num > 5:
            newHeight = 510 + ((data_num - 5) * 100)
            self.scrollAreaWidgetContents.setMinimumSize(540, newHeight)
        loguru.logger.info(f"self.duanju_select_data    ----   {len(self.duanju_select_data)}")
        for index, values in enumerate(self.duanju_select_data):
            for_frame = f"for_frame_{str(index)}"
            self.for_frame = QtWidgets.QFrame(self.scrollAreaWidgetContents)
            self.for_frame.setGeometry(QtCore.QRect(0, index * 100, 540, 101))
            self.for_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
            self.for_frame.setFrameShadow(QtWidgets.QFrame.Raised)
            self.for_frame.setObjectName(for_frame)

            self.head_img = QtWidgets.QLabel(self.for_frame)
            self.head_img.setGeometry(QtCore.QRect(10, 10, 71, 81))
            self.head_img.setObjectName("head_img")
            # lable 显示 网络 图片
            right_video_headImg_url = QImage.fromData(
                requests.get(values.get('head_img')).content)
            self.head_img.setPixmap(QPixmap(right_video_headImg_url).scaled(QSize(70, 80)))

            font = QtGui.QFont()
            font.setFamily("微软雅黑")
            font.setPointSize(9)
            self.duanju_name = QtWidgets.QLabel(self.for_frame)
            self.duanju_name.setGeometry(QtCore.QRect(100, 40, 110, 30))
            self.duanju_name.setObjectName("duanju_name")
            self.duanju_name.setFont(font)
            self.duanju_name.setText(values.get('duanju_name'))

            self.duanju_type = QtWidgets.QLabel(self.for_frame)
            self.duanju_type.setGeometry(QtCore.QRect(225, 40, 60, 30))
            self.duanju_type.setObjectName("duanju_type")
            self.duanju_type.setFont(font)
            self.duanju_type.setText(values.get('duanju_type'))

            self.duanju_palyCount = ClickableQLabel(self.for_frame)
            self.duanju_palyCount.setGeometry(QtCore.QRect(320, 40, 40, 30))
            self.duanju_palyCount.setObjectName("duanju_palyCount")
            self.duanju_palyCount.setFont(font)

            self.duanju_palyCount.setText(str(int(values.get('duanju_palyCount'))))
            self.duanju_palyCount.clicked.connect(
                partial(self.on_qlable_clicked, values.get("duanju_palyCount")))

            self.duanju_jiShu = ClickableQLabel(self.for_frame)
            self.duanju_jiShu.setGeometry(QtCore.QRect(390, 40, 30, 30))
            self.duanju_jiShu.setObjectName("duanju_jiShu")
            self.duanju_jiShu.setFont(font)
            self.duanju_jiShu.setText(str(int(values.get('duanju_jishu'))))
            self.duanju_jiShu.clicked.connect(
                partial(self.on_qlable_clicked, values.get("duanju_jishu")))
            self.downloads_video = QtWidgets.QPushButton(self.for_frame)
            self.downloads_video.setGeometry(QtCore.QRect(455, 30, 60, 40))
            self.downloads_video.setObjectName("downloads_video")
            self.downloads_video.setFont(font)
            self.downloads_video.setText('下载')
            # 给 点击方法 绑定不同的值,
            self.downloads_video.clicked.connect(partial(self.downloads_video_click, values))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
    else:
        self.showMsg("重要提示", result["msg"])


# 下载 短剧视频
class DownloadsVideo(QThread):
	  # 设置信号槽
    downloadsVideoSignal = pyqtSignal(str)
    def __init__(self):
        super(DownloadsVideo, self).__init__()
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0"
        }
        self.video_id_list = []
        self.output_path = None
        self.manager = QNetworkAccessManager()

    def restart(self, video_id_list, output_path):
        self.video_id_list = video_id_list
        self.output_path = output_path

    def run(self):
        for video_info in self.video_id_list:
            video_id = video_info.get("vid")
            vidIndex = int(video_info.get("vidIndex"))
            get_videoDownload_url = f"http://0.0.0.0:5000/api/v1/xxxxxxxx/getmodel?id={video_id}"
            for i in range(10):
                request = QNetworkRequest(QUrl(get_videoDownload_url))
                request.setHeader(QNetworkRequest.UserAgentHeader, self.headers["User-Agent"])
                reply = self.manager.get(request)  # 使用 QNetworkAccessManager 发送异步请求
                event_loop = QEventLoop()
                reply.finished.connect(event_loop.quit)
                event_loop.exec_()
                if reply.error() == QNetworkReply.NoError:
                    respon_text = reply.readAll().data().decode()
                    loguru.logger.info(f"respon --- {respon_text}")
                    status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
                    loguru.logger.info(f"Status code: {status_code}")
                    if "url" in respon_text:
                        respon = json.loads(respon_text)
                        if respon.get("data").get("map"):
                            download_url = respon.get("data").get("map").get("result").get("url")
                            downloads_res = self.download_video(download_url, vidIndex)
                            if downloads_res["is_downloads"]:
                                self.downloadsVideoSignal.emit(f"{downloads_res['output_path_name']} 下载成功")
                            else:
                                self.downloadsVideoSignal.emit(f"{downloads_res['output_path_name']} 下载 失败")
                        break
                else:
                    status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
                    # loguru.logger.info(f"Status code: {status_code}")
                    error_message = reply.errorString()
                    # loguru.logger.info(f"Error message: {error_message}")
                    if i == 9:
                        self.downloadsVideoSignal.emit("当前视频无法下载")
                time.sleep(random.randint(1, 5))

    def download_video(self, download_url, vidIndex):
        filename = f"第{vidIndex}集.mp4"
        output_path_name = self.output_path + filename
        # print(f"output_path_name --- {output_path_name}")
        # 使用requests下载视频
        for i in range(10):
            response = requests.get(download_url, stream=True)
            # 检查响应状态码是否为200(成功)
            if response.status_code == 200:
                with open(output_path_name, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=1024):
                        if chunk:  # 过滤掉keep-alive产生的空数据包
                            f.write(chunk)
                # print(f"Video downloaded successfully to {output_path_name}")
                return {
                    "is_downloads": True,
                    "output_path_name": output_path_name
                }
            else:
                if i == 9:
                    # print(f"Failed to download video. Response status code: {response.status_code}")
                    return {
                        "is_downloads": False,
                        "output_path_name": output_path_name
                    }
            time.sleep(random.randint(1, 3))


# 点击 QLable 实现 粘贴板 复制
def on_qlable_clicked(self, values):
    loguru.logger.info(f"value --- {values}")
    clipboard = qApp.clipboard()
    clipboard.setText(str(int(values)))

# 接收下载 视频 反馈的 信息
def download_video_callback(self, strIng):
    self.textBrowser.append(strIng)

自定义 QLable 实现 点击方法

class ClickableQLabel(QLabel):
    clicked = pyqtSignal()
    def __init__(self, parent=None):
        super().__init__(parent)
    def mousePressEvent(self, event):
        self.clicked.emit()

放置本地图片

self.image_label = QtWidgets.QLabel(self.centralwidget)
self.image_label.setGeometry(QtCore.QRect(20, 130, 540, 511))
# 加载本地图片
pixmap = QtGui.QPixmap(":aaa.jpeg")  # 替换为你的图片路径
if pixmap.isNull():
    print("无法加载图片")
else:
    # 设置 QLabel 的 pixmap
    self.image_label.setPixmap(pixmap)
    # 自动调整 QLabel 的大小以适应图片大小
    self.image_label.setScaledContents(True)

将 输入框 设置 只读

# 将 lineEdit 输入框 设置为 只读
self.folder_lineEdit.setReadOnly(True)

关闭 QScrollArea 水平滚动条

self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

选择 文件夹

# 选择 文件夹
def open_folder_dialog(self):
    folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
    if folder_path:
        self.folder_lineEdit.setText(folder_path)
    else:
        self.showMsg('Error', '请选择一个文件夹')

打包 时 包换本地图片

	1、新建 ".qrc" 结尾 的文件 如:demo.qrc 
	2、将下面代码放入 demo.qrc 文件中:
		<RCC>
		  <qresource prefix="/">
		    <file>文件名称</file>  
		    <file>logo.ico</file>
		    <!-- 添加更多图片或其他资源 -->
		  </qresource>
		</RCC>
	3、 命令行 执行 命令:
			 pyrcc5 -o demo.py demo.qrc  
	4、将 主程序 中 用到图片 的地方 ,名称一定要和在 demo.qrc里面的一致 在地址前面 加 ":"   例如:
		pixmap = QtGui.QPixmap(":aaa.jpeg")  # 替换为你的图片路径
		self.setWindowIcon(QIcon(':logo.ico'))

点击方法

	# QButton 绑定 点击方法
	self.pushButton_select_file.clicked.connect(self.open_folder_dialog)
	# 实例化 类
	self.selectDuanjun = SelectDuanJu()
	# 定义 接收信号槽 返回信息 的 方法
	self.selectDuanjun.selectDuanJuSignal.connect(self.select_function_callback)

设置 pyqt5 打包 .exe 的左上角图标以及软件名称:

	self.setWindowTitle("HongGuoApp短剧下载")
  self.setWindowIcon(QIcon(':logo.ico'))

打包命令

pyinstaller -F -w -n 软件名称 -i .\newLogon.ico .\主程序.py .\demo.py

你可能感兴趣的:(qt,开发语言,python,pyqt,爬虫,windows)