白季飞龙的个人主页

PyQt5大杂烩

PyQt5播放音乐

from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
from PyQt5.QtWidgets import *

app = QApplication([])
player = QMediaPlayer()
player.setMedia(QMediaContent(QUrl.fromLocalFile('/mnt/d/music/test/金娃娃-彩虹糖的梦.wma')))
player.play()
app.exec()

注意:player必须在QApplication实例化后创建,否则无报错不播放

PyQt5多线程

import sys
import time

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class BigWork(QThread):
    signal = pyqtSignal(type(None))

    def run(self) -> None:
        print("Big Working...")
        time.sleep(3)
        print("Big done.")
        self.signal.emit(None)

    def terminate(self) -> None:
        print("Terminating...")
        super().terminate()
        print("Terminated.")


class Window(QWidget):
    root_layout: QVBoxLayout
    button1: QPushButton
    button2: QPushButton
    button3: QPushButton
    work: QThread

    def __init__(self) -> None:
        super().__init__()
        self.setup_layout()
        self.work = BigWork()
        self.work.signal.connect(lambda x: print("Signal received:", x))

    def setup_layout(self):
        self.button1 = QPushButton("Start", parent=self)
        self.button2 = QPushButton("Stop", parent=self)
        self.button3 = QPushButton("About Qt", parent=self)

        self.root_layout = QVBoxLayout()
        self.root_layout.addWidget(self.button1)
        self.root_layout.addWidget(self.button2)
        self.root_layout.addWidget(self.button3)

        self.button1.clicked.connect(lambda: self.work.start())
        self.button2.clicked.connect(lambda: self.work.terminate())
        self.button3.clicked.connect(lambda: QMessageBox.aboutQt(self))

        self.resize(600, 400)
        self.setLayout(self.root_layout)


def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

文章首发: https://baijifeilong.github.io


漫漫路,莫论逍遥;潜心修,只为悟道