废话 不多说,直接上代码!!!
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")
主文件
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")
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)
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)
error_message = reply.errorString()
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
for i in range(10):
response = requests.get(download_url, stream=True)
if response.status_code == 200:
with open(output_path_name, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return {
"is_downloads": True,
"output_path_name": output_path_name
}
else:
if i == 9:
return {
"is_downloads": False,
"output_path_name": output_path_name
}
time.sleep(random.randint(1, 3))
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:
self.image_label.setPixmap(pixmap)
self.image_label.setScaledContents(True)
将 输入框 设置 只读
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'))
点击方法
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