Esempio n. 1
0
class SubPropertyPanel(QWidget):
    """ 子属性面板 """
    def __init__(self, songInfo: dict, parent=None):
        super().__init__(parent)

        self.songInfo = songInfo
        self.pen = QPen(QColor(0, 153, 188))

        # 实例化小部件
        self.createWidgets()
        # 初始化小部件的位置
        self.initWidget()
        self.setShadowEffect()
        # 设置层叠样式
        self.setQss()

    def createWidgets(self):
        """ 实例化标签 """
        # 标题
        self.yearLabel = QLabel("年", self)
        self.diskLabel = QLabel("光盘", self)
        self.tconLabel = QLabel("类型", self)
        self.durationLabel = QLabel("时长", self)
        self.propertyLabel = QLabel("属性", self)
        self.songerLabel = QLabel("歌曲歌手", self)
        self.songNameLabel = QLabel("歌曲名", self)
        self.trackNumberLabel = QLabel("曲目", self)
        self.songPathLabel = QLabel("文件位置", self)
        self.albumNameLabel = QLabel("专辑标题", self)
        self.albumSongerLabel = QLabel("专辑歌手", self)
        # 内容
        self.disk = QLabel("1", self)
        self.year = QLabel(self.songInfo["year"], self)
        self.tcon = QLabel(self.songInfo["tcon"], self)
        self.songer = QLabel(self.songInfo["songer"], self)
        self.albumName = QLabel(self.songInfo["album"], self)
        self.duration = QLabel(self.songInfo["duration"], self)
        self.songName = QLabel(self.songInfo["songName"], self)
        self.albumSonger = QLabel(self.songInfo["songer"], self)
        self.songPath = QLabel(self.songInfo["songPath"], self)
        self.trackNumber = QLabel(self.songInfo["tracknumber"], self)
        # 实例化关闭按钮
        self.closeButton = PerspectivePushButton("关闭", self)
        # 创建小部件列表
        self.label_list_1 = [
            self.albumName,
            self.songName,
            self.songPath,
            self.songer,
            self.albumSonger,
        ]
        self.label_list_2 = [
            self.trackNumberLabel,
            self.trackNumber,
            self.diskLabel,
            self.disk,
            self.albumNameLabel,
            self.albumName,
            self.albumSongerLabel,
            self.albumSonger,
            self.tconLabel,
            self.tcon,
            self.durationLabel,
            self.duration,
            self.yearLabel,
            self.year,
            self.songPathLabel,
            self.songPath,
            self.closeButton,
        ]
        self.label_list_3 = [
            self.disk,
            self.year,
            self.tcon,
            self.songer,
            self.albumName,
            self.duration,
            self.songName,
            self.albumSonger,
            self.songPath,
            self.trackNumber,
        ]

    def initWidget(self):
        """ 初始化小部件的属性 """
        self.resize(942, 590)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_StyledBackground)
        # 初始化抬头的位置
        self.tconLabel.move(28, 330)
        self.diskLabel.move(584, 168)
        self.yearLabel.move(652, 330)
        self.songerLabel.move(584, 90)
        self.propertyLabel.move(28, 27)
        self.songNameLabel.move(28, 90)
        self.songPathLabel.move(28, 408)
        self.albumNameLabel.move(28, 252)
        self.durationLabel.move(584, 330)
        self.trackNumberLabel.move(28, 168)
        self.albumSongerLabel.move(584, 252)
        # 初始化内容的位置
        self.tcon.move(28, 362)
        self.year.move(652, 362)
        self.disk.move(584, 202)
        self.songer.move(584, 122)
        self.songName.move(28, 122)
        self.songPath.move(28, 442)
        self.albumName.move(28, 282)
        self.duration.move(584, 362)
        self.trackNumber.move(28, 202)
        self.albumSonger.move(584, 282)
        self.closeButton.move(732, 535)
        # 设置按钮的大小
        self.closeButton.setFixedSize(170, 40)
        # 将关闭信号连接到槽函数
        if not self.parent():
            self.closeButton.clicked.connect(self.deleteLater)
        # 设置宽度
        for label in self.label_list_1:
            if label in [self.songer, self.albumSonger]:
                label.setFixedWidth(291)
            elif label in [self.albumName, self.songName]:
                label.setFixedWidth(500)
            elif label == self.songPath:
                label.setFixedWidth(847)
        # 调整高度
        self.adjustHeight()
        # 允许鼠标选中
        for label in self.label_list_3:
            label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        # 分配ID
        self.year.setObjectName("songer")
        self.songer.setObjectName("songer")
        self.duration.setObjectName("songer")
        self.songPath.setObjectName("songPath")
        self.albumSonger.setObjectName("songer")
        self.propertyLabel.setObjectName("propertyLabel")

    def adjustHeight(self):
        """ 如果有换行的发生就调整高度 """
        newSongName, isSongNameWrap = autoWrap(self.songName.text(), 57)
        newSonger, isSongerWrap = autoWrap(self.songer.text(), 33)
        newAlbumName, isAlbumNameWrap = autoWrap(self.albumName.text(), 57)
        newAlbumSonger, isAlbumSongerWrap = autoWrap(self.albumSonger.text(),
                                                     33)
        newSongPath, isSongPathWrap = autoWrap(self.songPath.text(), 100)
        if isSongNameWrap or isSongerWrap:
            self.songName.setText(newSongName)
            self.songer.setText(newSonger)
            # 后面的所有标签向下平移25px
            for label in self.label_list_2:
                label.move(label.geometry().x(), label.geometry().y() + 25)
            self.resize(self.width(), self.height() + 25)
        if isAlbumNameWrap or isAlbumSongerWrap:
            self.albumName.setText(newAlbumName)
            self.albumSonger.setText(newAlbumSonger)
            # 后面的所有标签向下平移25px
            for label in self.label_list_2[8:]:
                label.move(label.geometry().x(), label.geometry().y() + 25)
            self.resize(self.width(), self.height() + 25)
        if isSongPathWrap:
            self.songPath.setText(newSongPath)
            self.resize(self.width(), self.height() + 25)

    def setQss(self):
        """ 设置层叠样式表 """
        with open("app\\resource\\css\\propertyPanel.qss",
                  "r",
                  encoding="utf-8") as f:
            qss = f.read()
            self.setStyleSheet(qss)

    def paintEvent(self, event):
        """ 绘制边框 """
        painter = QPainter(self)
        # 绘制边框
        painter.setPen(self.pen)
        painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

    def setShadowEffect(self):
        """ 添加阴影效果 """
        self.shadowEffect = QGraphicsDropShadowEffect(self)
        self.shadowEffect.setBlurRadius(50)
        self.shadowEffect.setOffset(0, 5)
        self.setGraphicsEffect(self.shadowEffect)
    def init_ui(self):
        css = ("color: white; " "font-weight: bold")

        # vbox
        hbox = QHBoxLayout()
        bbox = QHBoxLayout()
        self.rbox = QGridLayout()

        hbox.setContentsMargins(0, 0, 0, 0)
        bbox.setContentsMargins(0, 5, 5, 0)
        self.rbox.setContentsMargins(0, 0, 0, 0)
        bbox.addStretch()
        hbox.setSpacing(0)
        bbox.setSpacing(0)

        # title
        self.l1 = QLabel(self)
        self.l1.setFont(self.large_font)
        self.l1.setStyleSheet(css)
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(5)
        shadow.setColor(QColor("#5e5e5e"))
        shadow.setOffset(2, 2)
        self.l1.setGraphicsEffect(shadow)
        hbox.addWidget(self.l1, 0, Qt.AlignCenter)

        # buttons
        b1 = QPushButton("─", self)
        b1.setFont(self.reg_font)
        b1.setStyleSheet(css)
        b1.setMaximumWidth(25)
        b1.setFlat(True)
        bbox.addWidget(b1, 0, Qt.AlignRight)
        b2 = QPushButton("X", self)
        b2.setFont(self.reg_font)
        b2.setStyleSheet(css)
        b2.setMaximumWidth(25)
        b2.setFlat(True)
        bbox.addWidget(b2, 0, Qt.AlignRight)

        # start
        self.download = Download()
        self.download.start()

        self.b5 = QPushButton("Downloading...", self)
        self.b5.setFont(self.large_font)
        # self.b5.setMinimumSize(50, 200)
        self.b5.setEnabled(False)
        self.rbox.addWidget(self.b5, 0, 0, 2, 1, Qt.AlignCenter)

        # if self.download.done is True:
        #     self.b5.setText("Install Red")
        #     self.b5.setEnabled(True)

        # bind
        b1.clicked.connect(self.showMinimized)
        b2.clicked.connect(self.close)
        self.b5.clicked.connect(self.req_ui)
        self.download.finished.connect(self.finish_check)

        self.rbox.addLayout(bbox, 0, 0, 1, 1)
        self.rbox.addLayout(hbox, 0, 0, 2, 1)
        self.setLayout(self.rbox)

        # bg
        bgimg = QImage()
        bgimg.loadFromData(
            urllib.request.urlopen('http://i.imgur.com/VW9eF72.jpg').read())
        bg = QPalette()
        bg.setBrush(QPalette.Background, QBrush(QPixmap(bgimg)))

        # window
        self.setFixedSize(400, 150)
        self.setPalette(bg)
        self.setWindowTitle('Red Discord Bot - Setup')
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
        self.show()
class MainWindow(QMainWindow):

    """Voice Changer main window."""

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
        self.setWindowTitle(__doc__)
        self.setMinimumSize(240, 240)
        self.setMaximumSize(480, 480)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
        self.tray = QSystemTrayIcon(self)
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
        self.menuBar().addMenu("Sound").addAction(
            "STOP !", lambda: call('killall rec', shell=True))
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Hide", lambda: self.hide())
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        # widgets
        group0 = QGroupBox("Voice Deformation")
        self.setCentralWidget(group0)
        self.process = QProcess(self)
        self.process.error.connect(
            lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
        self.control = QDial()
        self.control.setRange(-10, 20)
        self.control.setSingleStep(5)
        self.control.setValue(0)
        self.control.setCursor(QCursor(Qt.OpenHandCursor))
        self.control.sliderPressed.connect(
            lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.control.sliderReleased.connect(
            lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
        self.control.valueChanged.connect(
            lambda: self.control.setToolTip(f"<b>{self.control.value()}"))
        self.control.valueChanged.connect(
            lambda: self.statusBar().showMessage(
                f"Voice deformation: {self.control.value()}", 5000))
        self.control.valueChanged.connect(self.run)
        self.control.valueChanged.connect(lambda: self.process.kill())
        # Graphic effect
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.control.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)
        # Timer to start
        self.slider_timer = QTimer(self)
        self.slider_timer.setSingleShot(True)
        self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
        # an icon and set focus
        QLabel(self.control).setPixmap(
            QIcon.fromTheme("audio-input-microphone").pixmap(32))
        self.control.setFocus()
        QVBoxLayout(group0).addWidget(self.control)
        self.menu = QMenu(__doc__)
        self.menu.addAction(__doc__).setDisabled(True)
        self.menu.setIcon(self.windowIcon())
        self.menu.addSeparator()
        self.menu.addAction(
            "Show / Hide",
            lambda: self.hide() if self.isVisible() else self.showNormal())
        self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
        self.menu.addSeparator()
        self.menu.addAction("Quit", lambda: exit())
        self.tray.setContextMenu(self.menu)
        self.make_trayicon()

    def run(self):
        """Run/Stop the QTimer."""
        if self.slider_timer.isActive():
            self.slider_timer.stop()
        self.glow.setEnabled(True)
        call('killall rec ; killall play', shell=True)
        self.slider_timer.start(3000)

    def on_slider_timer_timeout(self):
        """Run subprocess to deform voice."""
        self.glow.setEnabled(False)
        value = int(self.control.value()) * 100
        command = f'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {value} "'
        print(f"Voice Deformation Value: {value}")
        print(f"Voice Deformation Command: {command}")
        self.process.start(command)
        if self.isVisible():
            self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
            print("Minimizing Main Window to System TrayIcon now...")
            sleep(3)
            self.hide()

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def make_trayicon(self):
        """Make a Tray Icon."""
        if self.windowIcon() and __doc__:
            self.tray.setIcon(self.windowIcon())
            self.tray.setToolTip(__doc__)
            self.tray.activated.connect(
                lambda: self.hide() if self.isVisible()
                else self.showNormal())
            return self.tray.show()
Esempio n. 4
0
	def setUI(self):
		s = QGraphicsDropShadowEffect()
		s.setColor(QColor("#000000"))
		s.setBlurRadius(5)
		s.setOffset(1,1)
		self.frameTree = QFrame(self)
		self.frameTree.setGeometry(0, 0, 600, 600)

		self.defaultTree()

		self.frameInfo = QFrame(self)
		self.frameInfo.setGeometry(605, 5, 190, 590)
		self.frameInfo.setObjectName("Layer2")
		self.frameInfo.setGraphicsEffect(s)

		self.labelAddKnot = QLabel("Add Knot:", self.frameInfo)
		self.labelAddKnot.setGeometry(10, 150, 60, 30)
		self.labelAddKnot.setAlignment(Qt.AlignCenter)
		self.labelAddKnot.setObjectName("Layer2NoBG")
		self.labelAddKnot.setFont(QFont("Arial", 15))
		self.entryAddKnot = QLineEdit(self.frameInfo)
		self.entryAddKnot.setGeometry(120, 150, 60, 30)
		self.entryAddKnot.setAlignment(Qt.AlignCenter)
		self.entryAddKnot.setObjectName("Layer2")
		self.entryAddKnot.setFont(QFont("Arial", 15))
		self.entryAddKnot.setValidator(QRegExpValidator(QRegExp("[0-9]+"), self.entryAddKnot))
		self.buttonAddKnot = QPushButton(QApplication.style().standardIcon(QStyle.SP_DialogApplyButton), '', self.frameInfo)
		self.buttonAddKnot.setGeometry(180, 150, 60, 30)
		self.buttonAddKnot.setObjectName("Layer2")
		self.buttonAddKnot.clicked.connect(self.addKnot)

		self.labelVisualizeKnot = QLabel("Search for:", self.frameInfo)
		self.labelVisualizeKnot.setGeometry(10, 300, 60, 30)
		self.labelVisualizeKnot.setAlignment(Qt.AlignCenter)
		self.labelVisualizeKnot.setObjectName("Layer2NoBG")
		self.labelVisualizeKnot.setFont(QFont("Arial", 15))
		self.entryVisualizeKnot = QLineEdit(self.frameInfo)
		self.entryVisualizeKnot.setGeometry(70, 300, 60, 30)
		self.entryVisualizeKnot.setAlignment(Qt.AlignCenter)
		self.entryVisualizeKnot.setObjectName("Layer2")
		self.entryVisualizeKnot.setFont(QFont("Arial", 15))
		self.entryVisualizeKnot.setValidator(QRegExpValidator(QRegExp("[0-9]+"), self.entryVisualizeKnot))
		self.buttonVisualizeStartPause = QPushButton(QApplication.style().standardIcon(QStyle.SP_MediaPlay), '', self.frameInfo)
		self.buttonVisualizeStartPause.setGeometry(130, 300, 60, 30)
		self.buttonVisualizeStartPause.setObjectName("Layer2")
		self.buttonVisualizeStartPause.clicked.connect(self.startSearch)

		self.labelRemoveKnot = QLabel("Remove\nKnot:", self.frameInfo)
		self.labelRemoveKnot.setGeometry(10, 450, 60, 40)
		self.labelRemoveKnot.setAlignment(Qt.AlignCenter)
		self.labelRemoveKnot.setObjectName("Layer2NoBG")
		self.labelRemoveKnot.setFont(QFont("Arial", 15))
		self.entryRemoveKnot = QLineEdit(self.frameInfo)
		self.entryRemoveKnot.setGeometry(70, 450, 60, 30)
		self.entryRemoveKnot.setAlignment(Qt.AlignCenter)
		self.entryRemoveKnot.setObjectName("Layer2")
		self.entryRemoveKnot.setFont(QFont("Arial", 15))
		self.entryRemoveKnot.setValidator(QRegExpValidator(QRegExp("[0-9]+"), self.entryRemoveKnot))
		self.buttonRemoveKnot = QPushButton(QApplication.style().standardIcon(QStyle.SP_TrashIcon), '', self.frameInfo)
		self.buttonRemoveKnot.setGeometry(130, 450, 60, 30)
		self.buttonRemoveKnot.setObjectName("Layer2")
		self.buttonRemoveKnot.clicked.connect(self.deleteKnot)

		self.labelSize = QLabel("Change Knots Size:", self.frameInfo)
		self.labelSize.setGeometry(10, 540, 180, 30)
		self.labelSize.setAlignment(Qt.AlignCenter)
		self.labelSize.setObjectName("Layer2NoBG")
		self.labelSize.setFont(QFont("Arial", 15))
		self.buttonMinusSize = QPushButton("-", self.frameInfo)
		self.buttonMinusSize.setGeometry(10, 560, 90, 30)
		self.buttonMinusSize.setObjectName("Layer2")
		self.buttonMinusSize.setFont(QFont("Arial", 20))
		self.buttonMinusSize.clicked.connect(lambda: self.changeSize('-'))
		self.buttonMinusSize.setAutoRepeat(True)
		self.buttonPlusSize = QPushButton("+", self.frameInfo)
		self.buttonPlusSize.setGeometry(170, 560, 90, 30)
		self.buttonPlusSize.setObjectName("Layer2")
		self.buttonPlusSize.setFont(QFont("Arial", 20))
		self.buttonPlusSize.clicked.connect(lambda: self.changeSize('+'))
		self.buttonPlusSize.setAutoRepeat(True)
Esempio n. 5
0
class SubAlbumInfoEditPanel(QWidget):
    """ 专辑信息编辑面板主界面 """
    saveInfoSig = pyqtSignal(dict)
    adjustHeightSig = pyqtSignal()
    MAXHEIGHT = 755

    def __init__(self, albumInfo: dict, parent):
        super().__init__(parent)
        self.albumInfo = albumInfo
        self.tcon = self.albumInfo['tcon']  # type:str
        self.songer = self.albumInfo['songer']  # type:str
        self.albumName = self.albumInfo['album']  # type:str
        self.cover_path = self.albumInfo['cover_path']  # type:str
        self.songInfo_list = self.albumInfo['songInfo_list']  # type:list
        self.saveErrorHappened = False
        self.newAlbumCoverPath = None
        # 创建小部件
        self.__createWidgets()
        # 初始化
        self.__initWidget()

    def __createWidgets(self):
        """ 创建小部件 """
        self.delayTimer = QTimer(self)
        # 创建滚动区域和抬头
        self.scrollArea = ScrollArea(self)
        self.scrollWidget = QWidget()
        self.editAlbumInfoLabel = QLabel('编辑专辑信息', self)
        # 上半部分
        self.albumCover = AlbumCoverWindow(self.cover_path, (170, 170),
                                           self.scrollWidget)
        self.albumNameLineEdit = LineEdit(self.albumName, self.scrollWidget)
        self.albumSongerLineEdit = LineEdit(self.songer, self.scrollWidget)
        self.tconLineEdit = LineEdit(self.tcon, self.scrollWidget)
        self.albumNameLabel = QLabel('专辑标题', self.scrollWidget)
        self.albumSongerLabel = QLabel('专辑歌手', self.scrollWidget)
        self.tconLabel = QLabel('类型', self.scrollWidget)
        # 下半部分
        self.songInfoWidget_list = []
        for songInfo in self.songInfo_list:
            songInfoWidget = SongInfoWidget(songInfo, self.scrollWidget)
            songInfoWidget.isTrackNumEmptySig.connect(self.__trackNumEmptySlot)
            self.songInfoWidget_list.append(songInfoWidget)
        self.saveButton = PerspectivePushButton('保存', self)
        self.cancelButton = PerspectivePushButton('取消', self)
        # 创建gif
        # self.loadingLabel = QLabel(self)
        # self.movie = QMovie(
        #    'resource\\images\\loading_gif\\loading.gif', parent=self)

    def __initWidget(self):
        """ 初始化小部件 """
        self.setFixedWidth(936)
        self.setMaximumHeight(self.MAXHEIGHT)
        self.setAttribute(Qt.WA_StyledBackground)
        # self.loadingLabel.setAttribute(Qt.WA_TranslucentBackground)
        # self.loadingLabel.setMovie(self.movie)
        self.scrollArea.setWidget(self.scrollWidget)
        self.songInfoWidgetNum = len(self.songInfoWidget_list)  # type:int
        # 初始化定时器
        self.delayTimer.setInterval(300)
        self.delayTimer.timeout.connect(self.__showFileDialog)
        # 设置滚动区域的大小
        if self.songInfoWidgetNum <= 4:
            self.scrollArea.resize(931, 216 + self.songInfoWidgetNum * 83)
        else:
            self.scrollArea.resize(931, 595)
        # 初始化布局
        self.__initLayout()
        # 信号连接到槽
        self.__connectSignalToSlot()
        # 分配ID
        self.scrollArea.setObjectName('infoEditScrollArea')
        self.editAlbumInfoLabel.setObjectName('editAlbumInfo')
        # 设置阴影和层叠样式
        self.__setShadowEffect()
        self.__setQss()

    def __initLayout(self):
        """ 初始化布局 """
        self.editAlbumInfoLabel.move(30, 30)
        self.scrollArea.move(2, 62)
        self.albumCover.move(30, 13)
        self.albumNameLabel.move(225, 7)
        self.albumSongerLabel.move(578, 7)
        self.tconLabel.move(225, 77)
        self.albumNameLineEdit.move(225, 36)
        self.albumSongerLineEdit.move(578, 36)
        self.tconLineEdit.move(225, 106)
        for i, songInfoWidget in enumerate(self.songInfoWidget_list):
            songInfoWidget.move(0, songInfoWidget.height() * i + 216)
        self.scrollWidget.resize(931, self.songInfoWidgetNum * 83 + 216)
        self.albumNameLineEdit.resize(327, 40)
        self.albumSongerLineEdit.resize(326, 40)
        self.tconLineEdit.resize(327, 40)
        self.saveButton.resize(168, 40)
        self.cancelButton.resize(168, 40)
        self.resize(936, self.scrollArea.y() + self.scrollArea.height() + 98)
        self.saveButton.move(563,
                             self.height() - 16 - self.saveButton.height())
        self.cancelButton.move(735,
                               self.height() - 16 - self.saveButton.height())

    def __setShadowEffect(self):
        """ 添加阴影 """
        self.shadowEffect = QGraphicsDropShadowEffect(self)
        self.shadowEffect.setBlurRadius(50)
        self.shadowEffect.setOffset(0, 5)
        self.setGraphicsEffect(self.shadowEffect)

    def __setQss(self):
        """ 设置层叠样式表 """
        with open(r'resource\css\infoEditPanel.qss', encoding='utf-8') as f:
            self.setStyleSheet(f.read())

    def paintEvent(self, event):
        """ 绘制背景和阴影 """
        # 创建画笔
        painter = QPainter(self)
        # 绘制边框
        pen = QPen(QColor(0, 153, 188))
        painter.setPen(pen)
        painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

    def __trackNumEmptySlot(self, isShowErrorMsg: bool):
        """ 如果曲目为空则禁用保存按钮 """
        self.saveButton.setEnabled(not isShowErrorMsg)
        if not self.sender().bottomErrorLabel.isVisible():
            # 获取曲目为空的小部件的index
            senderIndex = self.songInfoWidget_list.index(self.sender())
            # 调整面板高度
            self.__adjustWidgetPos(senderIndex, isShowErrorMsg)

    def __saveErrorSlot(self, songInfoWidget):
        """ 保存歌曲失败 """
        self.saveErrorHappened = True
        if not songInfoWidget.bottomErrorLabel.isVisible():
            senderIndex = self.songInfoWidget_list.index(songInfoWidget)
            self.__adjustWidgetPos(senderIndex, True)

    def __adjustWidgetPos(self, senderIndex, isShowErrorMsg: bool):
        """ 调整小部件位置 """
        # 调整面板高度
        deltaHeight = 54 if isShowErrorMsg else -54
        if self.height() == self.MAXHEIGHT:
            if deltaHeight < 0:
                height = self.scrollWidget.height() + deltaHeight
                if height < 600:
                    self.resize(936, height + 155)
                    self.adjustHeightSig.emit()
                    self.scrollArea.resize(931, height)
        elif self.MAXHEIGHT - abs(deltaHeight) < self.height(
        ) < self.MAXHEIGHT:
            if deltaHeight > 0:
                self.resize(936, self.MAXHEIGHT)
                self.adjustHeightSig.emit()
                self.scrollArea.resize(931, 600)
            else:
                self.__adjustHeight(deltaHeight)
        elif self.height() <= self.MAXHEIGHT - abs(deltaHeight):
            self.__adjustHeight(deltaHeight)
        self.scrollWidget.resize(931, self.scrollWidget.height() + deltaHeight)
        self.saveButton.move(563,
                             self.height() - 16 - self.saveButton.height())
        self.cancelButton.move(735,
                               self.height() - 16 - self.saveButton.height())
        # 调整后面的小部件的位置
        for songInfoWidget in self.songInfoWidget_list[senderIndex + 1:]:
            songInfoWidget.move(0, songInfoWidget.y() + deltaHeight)

    def __adjustHeight(self, deltaHeight):
        """ 调整高度 """
        self.resize(936, self.height() + deltaHeight)
        self.adjustHeightSig.emit()
        self.scrollArea.resize(931, self.scrollArea.height() + deltaHeight)

    def saveAlbumInfo(self):
        """ 保存专辑信息 """
        # 禁用小部件
        # self.__setWidgetEnable(False)
        # 显示动图
        # self.__showLoadingGif()
        # 更新标签信息
        self.albumInfo['album'] = self.albumNameLineEdit.text()
        self.albumInfo['songer'] = self.albumSongerLineEdit.text()
        self.albumInfo['tcon'] = self.tconLineEdit.text()
        for songInfo, songInfoWidget in zip(self.songInfo_list,
                                            self.songInfoWidget_list):
            album_list = adjustAlbumName(self.albumNameLineEdit.text())
            songInfo['album'] = album_list[0]
            songInfo['modifiedAlbum'] = album_list[-1]
            songInfo['songName'] = songInfoWidget.songNameLineEdit.text()
            songInfo['songer'] = songInfoWidget.songerLineEdit.text()
            songInfo['tcon'] = self.tconLineEdit.text()
            # 根据后缀名选择曲目标签的写入方式
            songInfo['tracknumber'] = songInfoWidget.trackNumLineEdit.text()
            # 实例化标签卡
            id_card = File(songInfo['songPath'])
            modifySongInfo(id_card, songInfo)
            try:
                id_card.save()
            except MutagenError:
                self.__saveErrorSlot(songInfoWidget)
                songInfoWidget.setSaveSongInfoErrorMsgHidden(False)
                break
        if not self.saveErrorHappened:
            self.saveAlbumCover()
            self.saveInfoSig.emit(self.albumInfo)
            self.parent().deleteLater()
        self.saveErrorHappened = False
        # 保存失败时重新启用编辑框
        # self.__setWidgetEnable(True)
        # self.loadingLabel.hide()
        # self.movie.stop()

    def __connectSignalToSlot(self):
        """ 信号连接到槽 """
        self.saveButton.clicked.connect(self.saveAlbumInfo)
        self.cancelButton.clicked.connect(self.parent().deleteLater)
        self.albumCover.clicked.connect(self.delayTimer.start)
        """ self.saveAlbumInfoThread.saveErrorSig.connect(
            lambda index:self.__saveErrorSlot(self.songInfoWidget_list[index])) """

    def __showFileDialog(self):
        """ 显示专辑图片选取对话框 """
        self.delayTimer.stop()
        path, filterType = QFileDialog.getOpenFileName(
            self, '打开', './', '所有文件(*.png;*.jpg;*.jpeg;*jpe;*jiff)')
        if path:
            # 复制图片到封面文件夹下
            if os.path.abspath(self.cover_path) == path:
                return
            # 暂存图片地址并刷新图片
            self.newAlbumCoverPath = path
            self.albumCover.setAlbumCover(path)

    def saveAlbumCover(self):
        """ 保存新专辑封面 """
        if not self.newAlbumCoverPath:
            return
        with open(self.newAlbumCoverPath, 'rb') as f:
            picData = f.read()
            # 给专辑中的所有文件写入同一张封面
            for songInfo in self.songInfo_list:
                writeAlbumCover(songInfo['songPath'], self.newAlbumCoverPath)
            # 更换文件夹下的封面图片
            if self.newAlbumCoverPath == os.path.abspath(self.cover_path):
                return
            # 判断文件格式后修改后缀名
            newSuffix = getPicSuffix(picData)
            # 如果封面路径是默认专辑封面,就修改封面路径
            if self.cover_path == 'resource\\images\\未知专辑封面_200_200.png':
                self.cover_path = 'resource\\Album_Cover\\{0}\\{0}{1}'.format(
                    self.albumInfo['modifiedAlbum'], newSuffix)
            with open(self.cover_path, 'wb') as f:
                f.write(picData)
            oldName, oldSuffix = os.path.splitext(self.cover_path)
            if newSuffix != oldSuffix:
                os.rename(self.cover_path, oldName + newSuffix)
                self.cover_path = oldName + newSuffix
                self.albumInfo['cover_path'] = self.cover_path

    def __setWidgetEnable(self, isEnable: bool):
        """ 设置编辑框是否启用 """
        self.albumCover.setEnabled(isEnable)
        self.saveButton.setEnabled(isEnable)
        self.tconLineEdit.setEnabled(isEnable)
        self.albumNameLineEdit.setEnabled(isEnable)
        self.albumSongerLineEdit.setEnabled(isEnable)
        for songInfoWidget in self.songInfoWidget_list:
            songInfoWidget.setLineEditEnable(isEnable)
        # 更新样式
        self.setStyle(QApplication.style())

    def __showLoadingGif(self):
        """ 显示正在加载动画 """
        self.loadingLabel.resize(77, 77)
        self.loadingLabel.move(
            int(self.width() / 2 - self.loadingLabel.width() / 2),
            int(self.height() / 2 - self.loadingLabel.height() / 2))
        self.loadingLabel.raise_()
        self.loadingLabel.show()
        self.movie.start()
class UINotificationModal(QDialog):
    def __init__(self,
                 Title: str,
                 Message: str,
                 Parent: QMainWindow = None,
                 Align=TopRight,
                 progressBar=False,
                 backgroundColor="#17a2b8",
                 foregroundColor="#FFFFFF",
                 icon=":/source/img/infoNotify.png",
                 multiplier=1,
                 duracion=15):
        self.Parent = Parent
        self.signals = notifySignals()
        self.progressBar = progressBar
        self.Aling = Align
        self.coords = Align(Parent).coords
        self.title = Title
        self.msg = Message
        self.multiplier = multiplier
        self.bg = backgroundColor
        self.fg = foregroundColor
        self.icon = icon
        self.duracion = duracion
        self.focus = False
        QDialog.__init__(self, Parent)
        self.setWindowFlags(Qt.FramelessWindowHint
                            | Qt.WindowStaysOnTopHint)  # removes borders
        self.setAttribute(
            Qt.WA_TranslucentBackground
        )  # Making it translucent to make a trick with the shadows
        self.setAttribute(Qt.WA_DeleteOnClose)  # this should liberate ram
        if not self.Parent is None:
            try:
                self.Parent.signals.resize.connect(self.resizeNotify)
            except:
                pass
        self.setupUi()

    def setupUi(self):
        self.NotificationModal = self
        self.NotificationModal.setObjectName("NotificationModal")
        self.NotificationModal.setWindowModality(QtCore.Qt.WindowModal)
        self.NotificationModal.resize(391, 129)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.NotificationModal.sizePolicy().hasHeightForWidth())
        self.NotificationModal.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Noto Serif")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.NotificationModal.setFont(font)
        self.NotificationModal.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
        self.NotificationModal.setStyleSheet(
            "background-color: rgb(255, 255, 255);")
        self.NotificationModal.setInputMethodHints(QtCore.Qt.ImhSensitiveData)
        self.verticalLayout = QtWidgets.QVBoxLayout(self.NotificationModal)
        self.verticalLayout.setObjectName("verticalLayout")
        self.MainFrame = QtWidgets.QFrame(self.NotificationModal)
        self.MainFrame.setMinimumSize(QtCore.QSize(240, 110))
        self.shadow = QGraphicsDropShadowEffect()
        self.shadow.setBlurRadius(4)
        self.shadow.setOffset(2)
        self.MainFrame.setGraphicsEffect(self.shadow)

        self.MainFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.MainFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.MainFrame.setObjectName("MainFrame")
        self.lblIcon = QtWidgets.QLabel(self.MainFrame)
        self.lblIcon.setGeometry(QtCore.QRect(7, 21, 70, 81))
        self.lblIcon.setText("")

        self.lblIcon.setAlignment(QtCore.Qt.AlignCenter)
        self.lblIcon.setObjectName("lblIcon")
        self.lblTitleScroll = QtWidgets.QScrollArea(self.MainFrame)
        self.lblTitleScroll.setGeometry(QtCore.QRect(75, 10, 151, 24))
        self.lblTitleScroll.setMinimumSize(QtCore.QSize(65, 20))
        self.lblTitleScroll.setMaximumSize(QtCore.QSize(167772, 167772))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.lblTitleScroll.setFont(font)
        self.lblTitleScroll.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.lblTitleScroll.setFrameShadow(QtWidgets.QFrame.Plain)
        self.lblTitleScroll.setLineWidth(0)
        self.lblTitleScroll.setVerticalScrollBarPolicy(
            QtCore.Qt.ScrollBarAsNeeded)
        self.lblTitleScroll.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)
        self.lblTitleScroll.setWidgetResizable(True)
        self.lblTitleScroll.setObjectName("lblTitleScroll")
        self.lblTitleScroll.setStyleSheet("background-color:transparent;")
        self.ScrollTitleLayout = QtWidgets.QWidget()
        self.ScrollTitleLayout.setGeometry(QtCore.QRect(0, 0, 151, 24))
        self.ScrollTitleLayout.setObjectName("ScrollTitleLayout")
        self.vboxlayout = QtWidgets.QVBoxLayout(self.ScrollTitleLayout)
        self.vboxlayout.setContentsMargins(0, 0, 0, 0)
        self.vboxlayout.setSpacing(0)
        self.vboxlayout.setObjectName("vboxlayout")
        self.txtNombre = QtWidgets.QLabel(self.ScrollTitleLayout)
        self.txtNombre.setMaximumSize(QtCore.QSize(16666672, 16666672))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.txtNombre.setFont(font)
        self.txtNombre.setLineWidth(0)
        self.txtNombre.setAlignment(QtCore.Qt.AlignLeading
                                    | QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
        self.txtNombre.setWordWrap(True)
        self.txtNombre.setIndent(5)
        self.txtNombre.setObjectName("txtNombre")
        self.vboxlayout.addWidget(self.txtNombre)
        self.lblTitleScroll.setWidget(self.ScrollTitleLayout)
        self.lblContentScroll = QtWidgets.QScrollArea(self.MainFrame)
        self.lblContentScroll.setGeometry(QtCore.QRect(75, 35, 271, 64))
        self.lblContentScroll.setMinimumSize(QtCore.QSize(65, 20))
        self.lblContentScroll.setMaximumSize(QtCore.QSize(167772, 167772))
        self.lblContentScroll.setStyleSheet("background-color:transparent;")
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.lblContentScroll.setFont(font)
        self.lblContentScroll.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.lblContentScroll.setFrameShadow(QtWidgets.QFrame.Plain)
        self.lblContentScroll.setLineWidth(0)
        self.lblContentScroll.setVerticalScrollBarPolicy(
            QtCore.Qt.ScrollBarAsNeeded)
        self.lblContentScroll.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)
        self.lblContentScroll.setWidgetResizable(True)
        self.lblContentScroll.setObjectName("lblContentScroll")
        self.ScrollContentLayout = QtWidgets.QWidget()
        self.ScrollContentLayout.setGeometry(QtCore.QRect(0, 0, 271, 64))
        self.ScrollContentLayout.setObjectName("ScrollContentLayout")
        self._2 = QtWidgets.QVBoxLayout(self.ScrollContentLayout)
        self._2.setContentsMargins(0, 0, 0, 0)
        self._2.setSpacing(0)
        self._2.setObjectName("_2")
        self.txtContent = QtWidgets.QLabel(self.ScrollContentLayout)
        self.txtContent.setMaximumSize(QtCore.QSize(16666672, 16666672))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.txtContent.setFont(font)

        self.txtContent.setLineWidth(0)
        self.txtContent.setAlignment(QtCore.Qt.AlignLeading
                                     | QtCore.Qt.AlignLeft
                                     | QtCore.Qt.AlignTop)
        self.txtContent.setWordWrap(True)
        self.txtContent.setIndent(5)
        self.txtContent.setObjectName("txtContent")
        self._2.addWidget(self.txtContent)
        self.lblContentScroll.setWidget(self.ScrollContentLayout)
        self.btnExit = QtWidgets.QPushButton(self.MainFrame)
        self.btnExit.setGeometry(QtCore.QRect(345, 5, 24, 24))
        self.btnExit.setText("")
        self.btnExit.setStyleSheet("border:0;")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/source/img/exitNotify.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btnExit.setIcon(icon1)
        self.btnExit.setIconSize(QtCore.QSize(24, 24))
        self.btnExit.setFlat(True)
        self.btnExit.setObjectName("btnExit")
        self.verticalLayout.addWidget(self.MainFrame)
        QtCore.QMetaObject.connectSlotsByName(self.NotificationModal)

        self.btnExit.clicked.connect(self.close)

        # set the color
        self.MainFrame.setStyleSheet("background-color:%s;" % self.bg)

        # set the foregroundColor

        self.txtContent.setStyleSheet("color:%s;" % self.fg)
        self.txtNombre.setStyleSheet("color:%s;background-color:transparent;" %
                                     self.fg)

        # progress bar

        if self.progressBar and not self.duracion is None:
            self.progressBar = QtWidgets.QProgressBar(self.MainFrame)
            self.progressBar.setGeometry(QtCore.QRect(0, 105, 371, 5))
            self.progressBar.setStyleSheet(
                "QProgressBar {border: none;background-color:transparent;} QProgressBar::chunk {background-color: #A9A9A9;width: 20px;}"
            )
            self.progressBar.setProperty("value", 100)
            self.progressBar.setFormat("")
            self.progressBar.setObjectName("progressBar")
            self.animBar = QPropertyAnimation(self.progressBar, b"value")
            self.animBar.setDuration(self.duracion * 1000)
            self.animBar.setStartValue(100)
            self.animBar.setEndValue(0)
            self.animBar.start(QAbstractAnimation.DeleteWhenStopped)
            self.animBar.finished.connect(self.close)

        if not self.progressBar and not self.duracion is None:
            QTimer.singleShot(self.duracion * 1000, self.close)

        # set the icon

        self.lblIcon.setPixmap(self.icon)
        self.lblIcon.setScaledContents(False)

        #set the text

        self.txtNombre.setText(self.title)
        self.txtContent.setText(self.msg)
        self.txtContent.setWordWrap(True)

        # set the location
        self.NotificationModal.setGeometry(
            self.coords(self.multiplier).x(),
            self.coords(self.multiplier).y(), 391, 128)

        # handle over and leave mouse event

    def updateLocation(self):
        self.animLocation = QPropertyAnimation(self.NotificationModal,
                                               b"geometry")
        self.animLocation.setDuration(100)
        self.animLocation.setStartValue(
            QRect(
                self.coords(self.multiplier).x(),
                self.coords(self.multiplier).y(), 391, 128))
        self.multiplier -= 1
        self.animLocation.setEndValue(
            QRect(
                self.coords(self.multiplier).x(),
                self.coords(self.multiplier).y(), 391, 128))
        self.animLocation.start(QAbstractAnimation.DeleteWhenStopped)

    def enterEvent(self, evt):
        self.focus = True

    def leaveEvent(self, evt):
        self.focus = False

    def mousePressEvent(self, evt):
        if evt.buttons() == Qt.LeftButton:
            self.clickCount = 0
        if evt.buttons() == Qt.RightButton:
            self.clickCount = 1

    def mouseReleaseEvent(self, evt):
        from PyQt5.QtWidgets import QApplication
        from PyQt5.QtCore import QTimer
        if self.clickCount == 1 or self.clickCount == 0:
            QTimer.singleShot(QApplication.doubleClickInterval(),
                              partial(self.perfomClickAction, evt))

    def mouseDoubleClickEvent(self, evt):
        self.clickCount = 2
        self.signals.double_click.emit(evt)

    def perfomClickAction(self, evt):
        if self.clickCount == 0:
            self.signals.left_click.emit(evt)
        if self.clickCount == 1:
            self.signals.right_click.emit(evt)

    def resizeNotify(self):
        self.NotificationModal.setGeometry(
            self.coords(self.multiplier).x(),
            self.coords(self.multiplier).y(), 391, 128)

    def close(self):
        self.signals.close.emit(self)
        if not self.Parent is None:
            try:
                self.Parent.signals.resize.disconnect(self.resizeNotify)
                self.signals.left_click.disconnect()
                self.signals.right_click.disconnect()
                self.signals.double_click.disconnect()
            except:
                pass

    def sizeHint(self):
        return QtCore.QSize(391, 129)
Esempio n. 7
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip(
            "Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Close
                                          | QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
Esempio n. 8
0
class AvatarWidget(QLabel):

    clicked = pyqtSignal()

    def __init__(self, *args, **kwargs):
        super(AvatarWidget, self).__init__(*args, **kwargs)
        self.setCursor(Qt.PointingHandCursor)
        self._rotate = 0
        self._radius = 0
        self._step = 45
        self._padding = 10
        self._image = ""
        self._shadowColor = "#212121"
        self._pixmap = None
        self._direction = None  # clockwise 顺时针 anticlockwise 逆时针
        self._timer = QTimer(self, timeout=self.update)
        self._effect = QGraphicsDropShadowEffect(self)
        self._effect.setBlurRadius(self._padding * 2)
        self._effect.setOffset(0, 0)

    def __del__(self):
        del self._pixmap
        self.stop()

    def stop(self):
        self._timer.stop()

    def update(self):
        if self._direction == "clockwise":  # 顺时针
            # 0 45 90 135 180 225 270 315 360
            if self._rotate == -360:
                self._rotate = 45
            else:
                self._rotate += self._step
            if self._rotate > 360:  # 旋转一周后停止
                self._rotate = 360
                self._direction = None
                self._timer.stop()  # 停止计时器
            else:
                super(AvatarWidget, self).update()
        elif self._direction == "anticlockwise":  # 逆时针
            # 360 -45 -90 -135 -180 -225 -270 -315 -360
            if self._rotate == 360:
                self._rotate = -45
            else:
                self._rotate -= self._step
            if self._rotate < -360:
                self._rotate = -360
                self._direction = None
                self._timer.stop()
            else:
                super(AvatarWidget, self).update()

    def paintEvent(self, event):
        '''绘制事件'''
        if not self._pixmap or self._pixmap.isNull():
            return super(AvatarWidget, self).paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        ph = self._padding / 2
        if self._direction in ("clockwise", "anticlockwise"):
            painter.translate(self.rect().center())  # 设置中心为旋转的中心
            painter.rotate(self._rotate)  # 旋转
            # 绘制图片
            painter.drawPixmap(
                QPointF((-self.width() + self._padding) / 2,
                        (-self.height() + self._padding) / 2), self._pixmap)
            painter.translate(-self.rect().center())  # 将原点复位
        else:
            painter.drawPixmap(QPointF(ph, ph), self._pixmap)


#         painter.setPen(  # 边框圆圈
#             QPen(QColor(self._shadowColor), 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
#         painter.drawRoundedRect(
#             ph, ph, self._pixmap.width(),
#             self._pixmap.height(), self._radius, self._radius)  # 画边框圆圈

    def mouseReleaseEvent(self, event):
        super(AvatarWidget, self).mouseReleaseEvent(event)
        self.clicked.emit()

    def enterEvent(self, event):
        '''鼠标进入事件'''
        self._effect.setColor(QColor(self._shadowColor))
        self._effect.setBlurRadius(self._padding * 2)
        self.setGraphicsEffect(self._effect)
        self._timer.stop()
        self._direction = "clockwise"  # 顺时针旋转
        self._timer.start(60)

    def leaveEvent(self, event):
        '''鼠标离开事件'''
        self._effect.setBlurRadius(0)
        self.setGraphicsEffect(self._effect)
        self._timer.stop()
        self._direction = "anticlockwise"  # 逆时针旋转
        self._timer.start(60)

    def getImage(self) -> str:
        return self._image

    def setPixmap(self, path: str) -> None:
        self._image = path
        size = min(self.width(), self.height()) - self.padding  # 需要边距的边框
        self._radius = int(size / 2)
        self._pixmap = QPixmap(size, size)
        self._pixmap.fill(Qt.transparent)  # 填充背景为透明
        tmp = QPixmap(path).scaled(size, size, Qt.KeepAspectRatioByExpanding,
                                   Qt.SmoothTransformation)
        # QPainter
        painter = QPainter()
        painter.begin(self._pixmap)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        # QPainterPath
        path = QPainterPath()
        path.addRoundedRect(0, 0, size, size, self._radius, self._radius)
        # 切割圆
        painter.setClipPath(path)
        painter.drawPixmap(0, 0, tmp)
        painter.end()
        del tmp

    def getPadding(self) -> int:
        return self._padding

    def setPadding(self, padding):
        self._padding = padding

    def getShadowColor(self) -> str:
        return self._shadowColor

    def setShadowColor(self, color: str):
        self._shadowColor = color

    image = pyqtProperty(str, getImage, setPixmap)
    padding = pyqtProperty(int, getPadding, setPadding)
    shadowColor = pyqtProperty(str, getShadowColor, setShadowColor)
Esempio n. 9
0
class Clipper(QPushButton):
    def __init__(self, master):
        super().__init__()

        self._id = 0
        self.master = master

        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setOffset(0, 0)
        self.shadow.setColor(QColor(255, 255, 255))

        self.setMinimumHeight(200)
        self.setGraphicsEffect(self.shadow)
        self.setObjectName("ClipperButton")

        self.enterEvent = lambda event: self.shadow.setBlurRadius(15)
        self.leaveEvent = lambda event: self.shadow.setBlurRadius(0)

        self.titlebar = QFrame(self)
        self.titlebar.resize(330, 30)
        self.titlebar.setObjectName("ClipperTitlebar")

        self._titlebar_text = QLineEdit(self.titlebar)
        self._titlebar_text.resize(self.width() - 30, 30)
        self._titlebar_text.move(30, 0)
        self._titlebar_text.setText("New Clipper")

        self.text_label_frame = QFrame(self)
        self.text_label_frame.resize(330, 170)
        self.text_label_frame.move(0, 30)
        self.text_label_frame.mousePressEvent = lambda event: self.text_label_pressed(
        )

        self._text_label = ClassicQLabel(self.text_label_frame)
        self._text_label.resize(
            self.text_label_frame.frameGeometry().width() - 15,
            self.text_label_frame.frameGeometry().height() - 15)
        self._text_label.move(5, 5)
        self._text_label.mousePressEvent = lambda event: self.text_label_pressed(
        )
        self._text_label.setWordWrap(True)
        self._text_label.setAlignment(Qt.AlignTop)

        self.delete_button = QPushButton(self)
        self.delete_button.resize(30, 30)
        self.delete_button.clicked.connect(self.delete_button_clicked)

    def text_label_pressed(self):
        if len(self._text_label.text()) > 0:
            QApplication.clipboard().setText(self._text_label.text())

    def delete_button_clicked(self):
        window_clippers.pop(self.id)
        self.master.resize_window_clippers()
        self.setParent(None)

    @property
    def text(self):
        return self._text_label.text()

    @text.setter
    def text(self, text):
        self.title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
        self._text_label.setText(text)

    @property
    def title(self):
        return self._titlebar_text.text()

    @title.setter
    def title(self, text):
        self._titlebar_text.setText(text)

    @property
    def id(self):
        return self._id

    @id.setter
    def id(self, id):
        self._id = id
Esempio n. 10
0
def set_shadow_effect(widget):
    effect = QGraphicsDropShadowEffect()
    effect.setOffset(1, 1)
    effect.setBlurRadius(35)
    effect.setColor(Qt.darkGray)
    widget.setGraphicsEffect(effect)
Esempio n. 11
0
class QtNode(QGraphicsWidget):

    def __init__(self, node, view):
        super(QtNode, self).__init__()

        self._spacingConstant = 5.0
        self._roundness = 3

        self._labelColor = QColor(255, 255, 255)
        self._label = QGraphicsSimpleTextItem(self)
        self._label.setBrush(self._labelColor)
        self._label.setText(node.name)

        self._selectedColor = QColor(255, 255, 255)
        self._shapePen = QPen(Qt.NoPen)
        self._shapePen.setColor(self._selectedColor)
        self._shapePen.setWidthF(1.5)

        self._brush = QBrush(QColor(*COLOUR_THEMES[node.node_type]))

        self._dropShadowEffect = QGraphicsDropShadowEffect()
        self.setGraphicsEffect(self._dropShadowEffect)

        self._dropShadowEffect.setOffset(0.0, 10.0)
        self._dropShadowEffect.setBlurRadius(8.0)
        self._dropShadowEffect.setColor(QColor(0, 0, 0, 50))

        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemIsSelectable)
        self.setAcceptHoverEvents(True)

        self.setToolTip(node.tooltip)

        self._name = node.name
        self._node = node
        self._view = weakref.ref(view)

        self._busy = False
        self._socketRows = OrderedDict()

        # Build IO pin socket rows
        for pin_name in node.pin_order:
            if pin_name in node.inputs:
                pin = node.inputs[pin_name]

            else:
                pin = node.outputs[pin_name]

            socket_row = SocketRow(self, pin)
            self._socketRows[pin_name] = socket_row

        self.updateLayout()

    def node(self):
        return self._node

    def view(self):
        return self._view()

    def name(self):
        return self._name

    def setName(self, name):
        self._name = name
        self._label.setText(name)
        self.updateLayout()

    def labelColor(self):
        return self._labelColor

    def onDeleted(self):
        if self.isSelected():
            self.setSelected(False)

        for socket_row in self._socketRows.values():
            socket_row.onDeleted()

        self._socketRows.clear()

    def hoverEnterEvent(self, event):
        self.view().guiOnHoverEnter(self)

    def hoverLeaveEvent(self, event):
        self.view().guiOnHoverExit(self)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemPositionHasChanged:
            for socket_row in self._socketRows.values():
                socket_row.socket().updateConnectionPositions()

            # Move node
            if not self._busy:
                self._busy = True

                self.view().guiOnMoved(self)
                self._busy = False

        elif change == QGraphicsItem.ItemSelectedHasChanged:
            self.onSelected()

        return QGraphicsItem.itemChange(self, change, value)

    def contextMenuEvent(self, event):
        self.view().guiOnNodeRightClick(self, event)

    def onSelected(self):
        if self.isSelected():
            self._shapePen.setStyle(Qt.SolidLine)
            self.view().guiOnNodeSelected(self)

        else:
            self._shapePen.setStyle(Qt.NoPen)
            self.view().guiOnNodeDeselected(self)

    def paint(self, painter, option, widget):
        shape = QPainterPath()
        shape.addRoundedRect(self.rect(), self._roundness, self._roundness)

        painter.setPen(self._shapePen)
        painter.setBrush(self._brush)
        painter.drawPath(shape)

    def setPos(self, *pos):
        if len(pos) == 1:
            point = QPointF(pos[0])

        else:
            point = QPointF(*pos)

        self._lastPos = point

        QGraphicsWidget.setPos(self, point)

    def mouseDoubleClickEvent(self, event):
        pass

    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:
            pass

        else:
            QGraphicsWidget.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        self.view().guiOnFinishedMove()

        QGraphicsWidget.mouseReleaseEvent(self, event)

    def mouseMoveEvent(self, event):
        QGraphicsWidget.mouseMoveEvent(self, event)

    def dragMoveEvent(self, *args, **kwargs):
        pass

    def getSocketRow(self, name):
        return self._socketRows[name]

    def refreshSocketRows(self):
        for socket_row in self._socketRows.values():
            socket_row.refresh()

    def updateLayout(self):
        label_width = self._label.boundingRect().width()
        width = label_width
        y_pos = self._label.boundingRect().bottom() + self._spacingConstant

        for socket_row in self._socketRows.values():
            if socket_row.isVisible():
                socket_row.updateLayout()

                socket_row.setPos(self._spacingConstant, y_pos)
                height = socket_row.boundingRect().height()

                y_pos += height

                attributeWidth = socket_row.boundingRect().width()
                if attributeWidth > width:
                    width = attributeWidth

        for socket_row in self._socketRows.values():
            if socket_row.isVisible():
                hook = socket_row.socket()
                if hook.isOutput():
                    hook.setPos(width - hook.boundingRect().width(), hook.pos().y())

        width = self._spacingConstant + width + self._spacingConstant
        self._label.setPos((width - label_width) / 2.0, self._spacingConstant)

        self.resize(width, y_pos + self._spacingConstant)
        self.update()
Esempio n. 12
0
class Firmament(QWidget):
	def __init__(self):
		QWidget.__init__(self)
		self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
		self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
		#self.setWindowOpacity(1)
		self.setMaximumHeight(30)
		self.resize(QSize(ancho, 30))
		self.container = QHBoxLayout()
		self.container.setContentsMargins(0,0,0,0)
		self.container.setSpacing(0)
		self.setLayout(self.container)

		#Widget de contenido, ignorar el resto, no he ordenado nada jijijiji.
		self.contenido = QWidget()
		self.container.addWidget(self.contenido,0)
		self.contenido.setStyleSheet("background-color: rgba(255, 255, 255,0.5);")
		#Crea la sombra
		self.shadow = QGraphicsDropShadowEffect(self.contenido)
		self.shadow.setColor(QColor(0,0,0,30))
		self.shadow.setBlurRadius(15)		
		self.shadow.setOffset(0,4)
		self.contenido.setGraphicsEffect(self.shadow)

		self.layout = QGridLayout()
		self.layout.setContentsMargins(0,0,0,0)
		self.layout.setSpacing(0)

		self.cuarzoBtn = QPushButton()
		self.cuarzoBtn.setAttribute(QtCore.Qt.WA_TranslucentBackground)
		self.batteryStatus = QPushButton()
		self.wifiStatus = QPushButton()
		self.volumeControl = QPushButton()
		self.shutdownControl = QPushButton()

		self.cuarzoBtn.setIcon(QIcon("src/img/cuarzo_16x16.png"))
		self.batteryStatus.setIcon(QIcon("src/img/battery-full.png"))
		self.wifiStatus.setIcon(QIcon("src/img/network-wireless-signal-good.png"))
		self.volumeControl.setIcon(QIcon("src/img/audio-volume-high.png"))
		self.shutdownControl.setIcon(QIcon("src/img/system-devices-panel.png"))

		self.cuarzoBtn.setIconSize(QSize(16,16))
		self.batteryStatus.setIconSize(QSize(22,22))
		self.wifiStatus.setIconSize(QSize(22,22))
		self.volumeControl.setIconSize(QSize(22,22))
		self.shutdownControl.setIconSize(QSize(22,22))

		self.cuarzoBtn.setStyleSheet("background-color: rgba(255, 255, 255, 0);")
		self.batteryStatus.setStyleSheet("background-color: rgba(255, 255, 255, 0);")		
		self.wifiStatus.setStyleSheet("background-color: rgba(255, 255, 255, 0);")
		self.volumeControl.setStyleSheet("background-color: rgba(255, 255, 255, 0);")
		self.shutdownControl.setStyleSheet("background-color: rgba(255, 255, 255, 0);")

		# Grupo de Iconos de Derecha
		self.btnGroup = QWidget()
		self.topicons = QHBoxLayout()
		self.topicons.setContentsMargins(0,0,0,0)
		self.topicons.setSpacing(0)
		self.topicons.addWidget(self.wifiStatus)
		self.topicons.addWidget(self.volumeControl)
		self.topicons.addWidget(self.batteryStatus)
		self.topicons.addWidget(self.shutdownControl)
		self.btnGroup.setLayout(self.topicons)

		self.layout.addWidget(self.cuarzoBtn,0,0,QtCore.Qt.AlignLeft)
		self.layout.addWidget(clock,0,1,QtCore.Qt.AlignCenter)
		self.layout.addWidget(self.btnGroup,0,2, QtCore.Qt.AlignRight)

		self.contenido.setLayout(self.layout)
Esempio n. 13
0
    def shadow(self):

        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(self.shadowSize)
        shadow.setOffset(self.shadowOffset)
        self.text.setGraphicsEffect(shadow)
Esempio n. 14
0
 def setShadow(self, rgb: tuple, r: int, offset=(0, 0)):
     effect_shadow = QGraphicsDropShadowEffect(self)
     effect_shadow.setOffset(*offset)  # 偏移
     effect_shadow.setBlurRadius(r)  # 阴影半径
     effect_shadow.setColor(QColor(*rgb))  # 阴影颜色
     return effect_shadow
Esempio n. 15
0
class SubDeleteSongFolderPanel(QWidget):
    """ 子删除文件夹卡对话框 """
    def __init__(self, folderName, parent):
        super().__init__(parent)
        self.folderName = folderName
        # 创建小部件
        self.createWidgets()
        # 初始化
        self.initWidget()
        self.initLayout()
        self.setQss()

    def createWidgets(self):
        """ 创建小部件 """
        self.titleLabel = QLabel("删除此文件夹吗?", self)
        self.subTitleLabel = QLabel("删除此文件夹吗?", self)
        self.contentLabel = QLabel(
            '如果将"' + self.folderName + '"文件夹从音乐中移除,则该文件夹不会再出现在音乐中,但不会被删除。',
            self)
        self.deleteButton = QPushButton("删除文件夹", self)
        self.cancelButton = QPushButton("取消", self)

    def initWidget(self):
        """ 初始化小部件 """
        self.resize(852, 235)
        self.adjustHeight()

        self.setAttribute(Qt.WA_TranslucentBackground | Qt.WA_StyledBackground)
        self.setShadowEffect()
        # 初始化按钮
        self.deleteButton.resize(126, 40)
        self.cancelButton.resize(113, 40)
        # 信号连接到槽函数
        self.cancelButton.clicked.connect(self.parent().deleteLater)
        # 分配ID
        self.titleLabel.setObjectName("titleLabel")
        self.subTitleLabel.setObjectName("subTitleLabel")
        self.contentLabel.setObjectName("contentLabel")

    def initLayout(self):
        """ 初始化布局 """
        self.subTitleLabel.move(30, 67)
        self.contentLabel.move(30, 116)
        self.deleteButton.move(552, 167)
        self.cancelButton.move(708, 167)

    def setShadowEffect(self):
        """ 添加阴影 """
        self.shadowEffect = QGraphicsDropShadowEffect(self)
        self.shadowEffect.setBlurRadius(50)
        self.shadowEffect.setOffset(0, 5)
        self.setGraphicsEffect(self.shadowEffect)

    def adjustHeight(self):
        """ 调整长度 """
        newText, isWordWrap = autoWrap(self.contentLabel.text(), 92)
        if isWordWrap:
            self.resize(852, self.height() + 23)
            self.contentLabel.setText(newText)

    def paintEvent(self, e):
        """ 绘制背景 """
        painter = QPainter(self)
        painter.setPen(Qt.NoPen)
        brush = QBrush(Qt.white)
        painter.setBrush(brush)
        painter.drawRect(self.rect())
        brush.setColor(QColor(0, 126, 153, 255))
        painter.setBrush(brush)
        painter.drawRect(1, 37, self.width() - 2, self.height() - 37)
        super().paintEvent(e)

    def setQss(self):
        """ 设置层叠样式 """
        with open(r"app\resource\css\deleteSongFolderPanel.qss",
                  encoding="utf-8") as f:
            self.setStyleSheet(f.read())
Esempio n. 16
0
class SubSongInfoEditPanel(QWidget):
    """ 歌曲信息编辑面板的子窗口 """

    saveInfoSig = pyqtSignal(dict, dict)

    def __init__(self, songInfo: dict, parent):
        super().__init__(parent)

        self.songInfo = deepcopy(songInfo)
        self.oldSongInfo = deepcopy(songInfo)
        # 实例化小部件
        self.__createWidgets()
        # 初始化小部件
        self.__initWidget()
        self.__initLayout()
        self.setShadowEffect()
        # 设置层叠样式
        self.__setQss()

    def __createWidgets(self):
        """ 实例化小部件 """
        # 实例化按钮
        self.saveButton = PerspectivePushButton("保存", self)
        self.cancelButton = PerspectivePushButton("取消", self)
        # 实例化标签
        self.yearLabel = QLabel("年", self)
        self.tconLabel = QLabel("类型", self)
        self.diskLabel = QLabel("光盘", self)
        self.trackNumLabel = QLabel("曲目", self)
        self.songNameLabel = QLabel("歌曲名", self)
        self.songPathLabel = QLabel("文件位置", self)
        self.albumNameLabel = QLabel("专辑标题", self)
        self.songerNameLabel = QLabel("歌曲歌手", self)
        self.albumSongerLabel = QLabel("专辑歌手", self)
        self.editInfoLabel = QLabel("编辑歌曲信息", self)
        self.songPath = QLabel(self.songInfo["songPath"], self)
        self.emptyTrackErrorIcon = ErrorIcon(self)
        self.bottomErrorIcon = ErrorIcon(self)
        self.bottomErrorLabel = QLabel(self)
        # 实例化单行输入框
        self.diskEditLine = LineEdit("1", self)
        self.tconEditLine = LineEdit(self.songInfo["tcon"], self)
        self.yearEditLine = LineEdit(self.songInfo["year"], self)
        self.albumNameEditLine = LineEdit(self.songInfo["album"], self)
        self.songNameEditLine = LineEdit(self.songInfo["songName"], self)
        self.songerNameEditLine = LineEdit(self.songInfo["songer"], self)
        self.albumSongerEditLine = LineEdit(self.songInfo["songer"], self)
        self.trackNumEditLine = LineEdit(self.songInfo["tracknumber"], self)

        # 创建集中管理小部件的列表
        self.leftLabel_list = [
            self.songNameLabel,
            self.trackNumLabel,
            self.albumNameLabel,
            self.tconLabel,
        ]

        self.rightLabel_list = [
            self.songerNameLabel,
            self.diskLabel,
            self.albumSongerLabel,
            self.yearLabel,
        ]

        self.leftEditLine_list = [
            self.songNameEditLine,
            self.trackNumEditLine,
            self.albumNameEditLine,
            self.tconEditLine,
        ]

        self.rightEditLine_list = [
            self.songerNameEditLine,
            self.diskEditLine,
            self.albumSongerEditLine,
            self.yearEditLine,
        ]

        self.editLine_list = [
            self.songNameEditLine,
            self.songerNameEditLine,
            self.trackNumEditLine,
            self.diskEditLine,
            self.albumNameEditLine,
            self.albumSongerEditLine,
            self.tconEditLine,
            self.yearEditLine,
        ]

    def __initWidget(self):
        """ 初始化小部件的属性 """
        self.resize(932, 652)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_StyledBackground)
        # 默认选中歌名编辑框
        self.songNameEditLine.setFocus()
        self.songNameEditLine.clearButton.show()
        # 给每个单行输入框设置大小
        for editLine in self.editLine_list:
            editLine.setFixedSize(408, 40)

        # 设置按钮的大小
        self.saveButton.setFixedSize(165, 41)
        self.cancelButton.setFixedSize(165, 41)

        # 设置报警标签位置
        self.bottomErrorLabel.setMinimumWidth(100)
        self.emptyTrackErrorIcon.move(7, 224)
        self.bottomErrorIcon.hide()
        self.bottomErrorLabel.hide()
        self.emptyTrackErrorIcon.hide()
        self.installEventFilter(self)

        # 如果曲目为空就禁用保存按钮并更改属性
        self.trackNumEditLine.setProperty("hasText", "true")
        if not self.trackNumEditLine.text():
            self.saveButton.setEnabled(False)
            self.emptyTrackErrorIcon.show()
            self.trackNumEditLine.setProperty("hasText", "false")

        # 给输入框设置过滤器
        rex_trackNum = QRegExp(r"(\d)|([1-9]\d{1,2})")
        rex_year = QRegExp(r"\d{4}年{0,1}")
        validator_tracknum = QRegExpValidator(rex_trackNum, self.trackNumEditLine)
        validator_disk = QRegExpValidator(rex_trackNum, self.diskEditLine)
        validator_year = QRegExpValidator(rex_year, self.yearEditLine)
        self.trackNumEditLine.setValidator(validator_tracknum)
        self.diskEditLine.setValidator(validator_disk)
        self.yearEditLine.setValidator(validator_year)

        # 将曲目输入框数字改变的信号连接到槽函数
        self.trackNumEditLine.textChanged.connect(self.checkTrackEditLine)

        # 将按钮点击信号连接到槽函数
        self.saveButton.clicked.connect(self.saveInfo)
        if not self.parent():
            self.cancelButton.clicked.connect(self.deleteLater)

        # 分配ID
        self.editInfoLabel.setObjectName("editSongInfo")
        self.songerNameEditLine.setObjectName("songer")
        self.albumSongerEditLine.setObjectName("songer")
        self.songPath.setObjectName("songPath")
        self.bottomErrorLabel.setObjectName("bottomErrorLabel")

    def __initLayout(self):
        """ 初始化小部件的排版 """
        self.editInfoLabel.move(30, 30)
        self.songPathLabel.move(30, 470)
        self.songPath.move(30, 502)
        self.saveButton.move(566, 595)
        self.cancelButton.move(736, 595)
        label_top_y = 95

        for i, (label_left, label_right) in enumerate(
            zip(self.leftLabel_list, self.rightLabel_list)
        ):
            label_left.setObjectName("infoTypeLabel")
            label_right.setObjectName("infoTypeLabel")
            label_left.move(30, label_top_y + i * 87)
            label_right.move(494, label_top_y + i * 87)

        editLine_top_y = 127

        for i, (editLine_left, editLine_right) in enumerate(
            zip(self.leftEditLine_list, self.rightEditLine_list)
        ):
            editLine_left.move(30, editLine_top_y + i * 87)
            editLine_right.move(494, editLine_top_y + i * 87)

        # 调整高度
        newSongPath, isWordWrap = autoWrap(self.songPath.text(), 100)
        if isWordWrap:
            self.songPath.setText(newSongPath)
            self.resize(self.width(), self.height() + 25)
            self.cancelButton.move(self.cancelButton.x(), self.cancelButton.y() + 25)
            self.saveButton.move(self.saveButton.x(), self.saveButton.y() + 25)
        # 调整报错标签的位置
        self.bottomErrorIcon.move(30, self.height() - 110)
        self.bottomErrorLabel.move(55, self.height() - 112)

    def __setQss(self):
        """ 设置层叠样式表 """
        with open(r"app\resource\css\infoEditPanel.qss", encoding="utf-8") as f:
            self.setStyleSheet(f.read())

    def paintEvent(self, event):
        """ 绘制背景和阴影 """
        # 创建画笔
        self.pen = QPen(QColor(0, 153, 188))
        painter = QPainter(self)
        # 绘制边框
        painter.setPen(self.pen)
        painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

    def saveInfo(self):
        """ 保存标签卡信息 """
        album_list = adjustAlbumName(self.albumNameEditLine.text())
        self.songInfo["songName"] = self.songNameEditLine.text()
        self.songInfo["songer"] = self.songerNameEditLine.text()
        self.songInfo["album"] = album_list[0]
        self.songInfo["modifiedAlbum"] = album_list[-1]
        # 根据后缀名选择曲目标签的写入方式
        self.songInfo["tracknumber"] = self.trackNumEditLine.text()
        self.songInfo["tcon"] = self.tconEditLine.text()
        if self.yearEditLine.text()[:4] != "未知年份":
            self.songInfo["year"] = self.yearEditLine.text()[:4] + "年"
        else:
            self.songInfo["year"] = "未知年份"
        if not modifySongInfo(self.songInfo):
            self.bottomErrorLabel.setText("遇到未知错误,请稍后再试")
            self.bottomErrorLabel.show()
            self.bottomErrorIcon.show()
        else:
            self.saveInfoSig.emit(self.oldSongInfo, self.songInfo)
            self.parent().deleteLater()

    def checkTrackEditLine(self):
        """ 检查曲目输入框的内容是否为空 """
        if not self.trackNumEditLine.text():
            self.bottomErrorLabel.setText("曲目必须是1000以下的数字")
            self.bottomErrorLabel.show()
            self.emptyTrackErrorIcon.show()
            self.bottomErrorIcon.show()
            self.saveButton.setEnabled(False)
            self.trackNumEditLine.setProperty("hasText", "false")
        else:
            self.trackNumEditLine.setProperty("hasText", "true")
            self.bottomErrorLabel.hide()
            self.bottomErrorIcon.hide()
            self.emptyTrackErrorIcon.hide()
            self.saveButton.setEnabled(True)
        self.trackNumEditLine.setStyle(QApplication.style())

    def setShadowEffect(self):
        """ 添加阴影 """
        self.shadowEffect = QGraphicsDropShadowEffect(self)
        self.shadowEffect.setBlurRadius(50)
        self.shadowEffect.setOffset(0, 5)
        self.setGraphicsEffect(self.shadowEffect)
Esempio n. 17
0
class Sidebar(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent

        self.items = []
        self.color = random.randint(0, 255)
        self.colorStep = self.parent.css.var("sidebar_colorStep", int)
        self.colorOffset = self.parent.css.var("sidebar_colorOffset", int)
        self.layout = QVBoxLayout(self)
        self.scrollArea = QScrollArea(self.parent)

        # Setup scrollarea
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scrollArea.setFixedSize(self.parent.sidebarWidth,
                                     self.parent.height())
        self.scrollArea.setStyleSheet("border: none;")
        self.scrollArea.setWidget(self)

        # Setup sidebar itself
        self.setFixedWidth(self.parent.sidebarWidth)
        self.setMinimumHeight(self.parent.height() -
                              2)  # 2 to fix scroll height
        self.layout.setAlignment(Qt.AlignTop)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        # Shadow is not visible due to it's z-index. Maybe another stacking context?
        # I didn't figure out how to fix it :/
        self.shadow = QGraphicsDropShadowEffect()
        self.shadow.setBlurRadius(10)
        self.shadow.setOffset(0)
        self.shadow.setColor(Color(28, 28, 28))
        self.scrollArea.setGraphicsEffect(self.shadow)

        # Create placeholder item
        self.placeholder = Item(self)

    def findItemByName(self, name):
        return next(
            (item for item in self.items if item.name and item.name == name),
            None)

    def generateName(self):
        name = 65

        while self.findItemByName(chr(name)):
            name += 1

        return chr(name)

    def generateColor(self):
        self.color += self.colorStep + self.colorOffset

        return Color.fromHSL(self.color % 255, 180, 127)

    def updateCanvas(self):
        self.parent.canvas.update()

    def paintEvent(self, event):
        o = QStyleOption()
        o.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, o, p, self)
Esempio n. 18
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.i = 0
        self.i1 = 0
        self.initUI()

    def initUI(self):

        self.scroll = QScrollArea(
            self
        )  # Scroll Area which contains the widgets, set as the centralWidget
        self.widget1 = QWidget(self)
        self.widget1.setStyleSheet('background-color:#FAF6F5;')
        self.widget1.resize(1024, 1800)
        # self.widget2=QWidget(self)
        # self.widget2.setStyleSheet('background-color:black;')
        # self.widget2.resize(1024,800)
        # self.widget2.move(0,500)
        self.setGeometry(100, 100, 1024, 768)
        #self.vbox = QVBoxLayout()
        #self.widget1.setLayout(self.vbox)                # Widget that contains the collection of Vertical Box
        self.epf = QLabel("", self.widget1)
        effect = QGraphicsDropShadowEffect(self.epf)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf.setGraphicsEffect(effect)
        self.epf.setStyleSheet((
            "QLabel{background-color:white; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf.setGeometry(4, 3, 1000, 60)

        self.epf1 = QLabel("", self.widget1)
        #self.epf.setFont(QFont('Arial', 18))
        effect = QGraphicsDropShadowEffect(self.epf1)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf1.setGraphicsEffect(effect)
        self.epf1.setStyleSheet((
            "QLabel{background-color:#FCFCFE; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf1.setGeometry(20, 93, 970, 1680)
        source_label = QLabel("Face Swap Using Hard Drive Videos",
                              self.widget1)
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(250, 113, 600, 35)

        qq = u'\u2190'
        bb = QPushButton(qq + ' Back', self.widget1)
        bb.setGeometry(20, 3, 85, 58)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(18)
        bb.setFont(font)
        bb.setStyleSheet((
            "QPushButton{background-color:white; color: black;border-style: ridge;border-width:0px;border-radius: 0px;border-color: white;}"
        ))
        #bb.clicked.connect(self.bb_onClick)
        self.epf = QLabel("", self.widget1)
        #self.epf.setFont(QFont('Arial', 18))
        effect = QGraphicsDropShadowEffect(self.epf)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf.setGraphicsEffect(effect)
        self.epf.setStyleSheet((
            "QLabel{background-color:white; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf.setGeometry(50, 163, 900, 420)
        source_label = QLabel("Add Source Videos", self.widget1)
        source_label.setStyleSheet('background-color:white;')
        source_label.setFont(QFont('Arial', 21))
        source_label.setGeometry(100, 175, 600, 30)
        self.add_svideo = QPushButton('+', self.widget1)
        self.add_svideo.setGeometry(850, 213, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(18)
        self.add_svideo.setFont(font)
        self.add_svideo.setStyleSheet((
            "QPushButton{background-color:red; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.add_svideo.clicked.connect(self.add_svideo_onClick)

        self.del_svideo = QPushButton('-', self.widget1)
        self.del_svideo.setGeometry(800, 213, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(28)
        self.del_svideo.setFont(font)
        self.del_svideo.setStyleSheet((
            "QPushButton{background-color:blue; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.del_svideo.clicked.connect(self.del_svideo_onClick)

        self.dataView = QTreeWidget(self.widget1)
        self.dataView.setRootIsDecorated(False)
        self.dataView.setHeaderLabels(['Ref No', 'Source Videos'])
        self.dataView.header().setStyleSheet(
            'padding-top:-2px;background-color:white;font-size:21pt; font-family: Arial;border-width:1px;border-style:outset;border-color:black; '
        )
        self.dataView.setColumnCount(2)
        self.dataView.setColumnWidth(0, 100)
        self.dataView.setColumnWidth(1, 100)

        self.dataView.setStyleSheet('background-color:white;color: black;')
        self.dataView.setFont(QFont('Times New Roman', 22))

        self.dataView.setGeometry(100, 260, 800, 265)
        #self.dataView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        QScroller.grabGesture(self.dataView.viewport(), QScroller.TouchGesture)
        #self.dataView.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
        #self.dataView.itemClicked.connect(self.onItemClicked)

        self.epf = QLabel("", self.widget1)
        #self.epf.setFont(QFont('Arial', 18))
        effect = QGraphicsDropShadowEffect(self.epf)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf.setGraphicsEffect(effect)
        self.epf.setStyleSheet((
            "QLabel{background-color:white; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf.setGeometry(50, 603, 900, 420)
        source_label = QLabel("Add Destination Videos", self.widget1)
        source_label.setStyleSheet('background-color:white;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(100, 613, 600, 30)
        self.add_dvideo = QPushButton('+', self.widget1)
        self.add_dvideo.setGeometry(850, 653, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(18)
        self.add_dvideo.setFont(font)
        self.add_dvideo.setStyleSheet((
            "QPushButton{background-color:red; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.add_dvideo.clicked.connect(self.add_dvideo_onClick)

        self.del_dvideo = QPushButton('-', self.widget1)
        self.del_dvideo.setGeometry(800, 653, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(28)
        self.del_dvideo.setFont(font)
        self.del_dvideo.setStyleSheet((
            "QPushButton{background-color:blue; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.del_dvideo.clicked.connect(self.del_dvideo_onClick)

        self.dataView1 = QTreeWidget(self.widget1)
        self.dataView1.setRootIsDecorated(False)
        self.dataView1.setHeaderLabels(['Ref No', 'Destination Videos'])
        self.dataView1.header().setStyleSheet(
            'padding-top:-2px;background-color:white;font-size:21pt; font-family: Arial;border-width:1px;border-style:outset;border-color:black; '
        )
        self.dataView1.setColumnCount(2)
        self.dataView1.setColumnWidth(0, 100)
        self.dataView1.setColumnWidth(1, 100)

        self.dataView1.setStyleSheet('background-color:white;color: black;')
        self.dataView1.setFont(QFont('Times New Roman', 22))

        self.dataView1.setGeometry(100, 700, 800, 265)

        source_label = QLabel("Picture of Person In Source Video",
                              self.widget1)
        source_label.setFont(QFont('Arial', 22))
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setGeometry(100, 1113, 600, 30)
        self.lineEdit3 = QLineEdit(self.widget1)
        self.lineEdit3.setEnabled(False)
        self.lineEdit3.setFont(QFont('Arial', 11))
        self.lineEdit3.setGeometry(100, 1160, 650, 40)
        self.lineEdit3.setStyleSheet("background-color:white;color:black;")
        self.lineEdit3.setObjectName("lineEdit3")

        self.srcvideo_b = QPushButton('Select File', self.widget1)
        self.srcvideo_b.setGeometry(790, 1155, 120, 50)
        effect = QGraphicsDropShadowEffect(self.srcvideo_b)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.srcvideo_b.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.srcvideo_b.setFont(font)
        self.srcvideo_b.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.srcvideo_b.clicked.connect(self.srcvideo_b_onClick)

        source_label = QLabel("Picture of Person In Destination Video",
                              self.widget1)
        source_label.setFont(QFont('Arial', 22))
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setGeometry(100, 1213, 600, 30)
        self.lineEdit4 = QLineEdit(self.widget1)
        self.lineEdit4.setEnabled(False)
        self.lineEdit4.setFont(QFont('Arial', 11))
        self.lineEdit4.setGeometry(100, 1260, 650, 40)
        self.lineEdit4.setStyleSheet("background-color:white;color:black;")
        self.lineEdit4.setObjectName("lineEdit4")

        self.dstvideo_b = QPushButton('Select File', self.widget1)
        self.dstvideo_b.setGeometry(790, 1255, 120, 50)
        effect = QGraphicsDropShadowEffect(self.dstvideo_b)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.dstvideo_b.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.dstvideo_b.setFont(font)
        self.dstvideo_b.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.dstvideo_b.clicked.connect(self.dstvideo_b_onClick)

        source_label = QLabel("Output Video in which face is to be replaced",
                              self.widget1)
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(100, 1313, 600, 30)
        self.lineEdit5 = QLineEdit(self.widget1)
        self.lineEdit5.setEnabled(False)
        self.lineEdit5.setFont(QFont('Arial', 11))
        self.lineEdit5.setGeometry(100, 1360, 650, 40)
        self.lineEdit5.setStyleSheet("background-color:white;color:black;")
        self.lineEdit5.setObjectName("lineEdit5")

        self.output_v = QPushButton('Select File', self.widget1)
        self.output_v.setGeometry(790, 1355, 120, 50)
        effect = QGraphicsDropShadowEffect(self.output_v)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.output_v.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.output_v.setFont(font)
        self.output_v.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.output_v.clicked.connect(self.output_v_onClick)

        source_label = QLabel("Output Directory", self.widget1)
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(100, 1413, 600, 30)
        self.lineEdit6 = QLineEdit(self.widget1)
        self.lineEdit6.setEnabled(False)
        self.lineEdit6.setFont(QFont('Arial', 11))
        self.lineEdit6.setGeometry(100, 1460, 650, 40)
        self.lineEdit6.setStyleSheet("background-color:white;color:black;")
        self.lineEdit6.setObjectName("lineEdit6")

        self.output_d = QPushButton('Select Folder', self.widget1)
        self.output_d.setGeometry(790, 1455, 120, 50)
        effect = QGraphicsDropShadowEffect(self.output_d)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.output_d.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.output_d.setFont(font)
        self.output_d.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.output_d.clicked.connect(self.output_d_onClick)

        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.widget1)
        #self.scroll.setWidget(self.widget2)
        # self.scroll.setGeometry(0,0,1024,768)

        self.buttonWindow4 = QPushButton('Start', self.widget1)
        self.buttonWindow4.setGeometry(440, 1570, 215, 85)
        self.effect = QGraphicsDropShadowEffect(self.buttonWindow4)
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.buttonWindow4.setGraphicsEffect(self.effect)
        self.font = QFont()
        self.font.setFamily("Arial")
        self.font.setBold(True)
        self.font.setWeight(50)
        self.font.setPointSize(18)
        self.buttonWindow4.setFont(self.font)
        self.buttonWindow4.setStyleSheet((
            "QPushButton{background-color:#3C81F8; color: black;border-style: ridge;border-width:1px;border-radius: 10px;border-color: black;}"
        ))

        self.buttonWindow4.clicked.connect(self.start)

        self.setCentralWidget(self.scroll)
        self.setWindowTitle('Face Swap')

        self.dataView.itemClicked.connect(self.onItemClicked)
        self.dataView1.itemClicked.connect(self.onItemClicked1)
        self.show()

    def onItemClicked(self):
        #global getChildNode
        getSelected = self.dataView.selectedItems()
        #if getSelected:
        baseNode = getSelected[0]
        self.getChildNode = baseNode.text(1)
        print(self.getChildNode)

    def add_svideo_onClick(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileNamesrc, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "MP4 File (*.mp4)",
            options=options)
        #self.lineEdit5.setText('{}'.format(str(self.fileName3)))
        t = youtube.srcvideo_list
        t.append('{}'.format(str(self.fileNamesrc)))
        print(t, youtube.srcvideo_list)
        QTreeWidgetItem(self.dataView, [str(self.i), t[self.i]])
        self.i = self.i + 1
        #for i,x in enumerate(t):
        #print(i,x)
        #QTreeWidgetItem(self.dataView,[str(i),x])
    def del_svideo_onClick(self):
        #for i in reversed(range(self.dataView.childCount())):
        #self.dataView.removeChild(self.dataView.child(i))
        #keydata=self.getChildNode
        #QTreeWidgetItem.removeRow(int(keydata))
        try:
            #if len(self.getChildNode)==0:
            #raise ValueError
            #self.close()
            #self.destroy()
            #gc.collect()
            #info.info1=getChildNode
            #self.e.show()
            keydata = self.getChildNode
            print(keydata)
            t = youtube.srcvideo_list
            print(t)
            t.remove(keydata)
            self.i = self.i - 1
            #t.append(self.lineEdit1.text())
            #print(t)
            self.dataView.clear()
            for i, x in enumerate(t):
                #print(i,x)
                QTreeWidgetItem(self.dataView, [str(i), x])
            # #self.getChildNode=''
        except:
            print("error")
            #self.popup1=popup1(name='      Please select any user to edit!',name2='Okay!')
            #self.popup1.show()
    def onItemClicked1(self):
        #global getChildNode
        getSelected = self.dataView1.selectedItems()
        #if getSelected:
        baseNode = getSelected[0]
        self.getChildNode1 = baseNode.text(1)
        print(self.getChildNode1)

    def add_dvideo_onClick(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileNamedst, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "MP4 File (*.mp4)",
            options=options)
        t = youtube.dstvideo_list
        t.append('{}'.format(str(self.fileNamedst)))
        print(t, youtube.dstvideo_list)
        QTreeWidgetItem(self.dataView1, [str(self.i1), t[self.i1]])
        self.i1 = self.i1 + 1
        #for i,x in enumerate(t):
        #print(i,x)
        #QTreeWidgetItem(self.dataView,[str(i),x])
    def del_dvideo_onClick(self):
        try:
            keydata = self.getChildNode1
            print(keydata)
            t = youtube.dstvideo_list
            print(t)
            t.remove(keydata)
            self.i1 = self.i1 - 1
            #t.append(self.lineEdit1.text())
            #print(t)
            self.dataView1.clear()
            for i, x in enumerate(t):
                #print(i,x)
                QTreeWidgetItem(self.dataView1, [str(i), x])
            # #self.getChildNode=''
        except:
            print("error")
            #self.popup1=popup1(name='      Please select any user to edit!',name2='Okay!')
            #self.popup1.show()

    def srcvideo_b_onClick(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName1, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "PNG File (*.png)",
            options=options)
        self.lineEdit3.setText('{}'.format(str(self.fileName1)))
        print(self.fileName1)

    def dstvideo_b_onClick(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName2, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "PNG File (*.png)",
            options=options)
        self.lineEdit4.setText('{}'.format(str(self.fileName2)))
        print(self.fileName2)

    def output_v_onClick(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName3, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "MP4 File (*.mp4)",
            options=options)
        self.lineEdit5.setText('{}'.format(str(self.fileName3)))
        print(self.fileName3)

    def output_d_onClick(self):
        self.fileName4 = str(QFileDialog.getExistingDirectory())
        self.lineEdit6.setText('{}'.format(str(self.fileName4)))
        print(self.fileName4)

    def start(self):
        youtube.lineedit3 = self.lineEdit3.text()
        self.calc = External1()
        self.calc.start()
Esempio n. 19
0
class SubSelectSongFolderPanel(QWidget):
    """ 子选择歌曲文件夹面板 """

    updateSelectedFoldersSig = pyqtSignal(list)  # 发送更新了的歌曲文件夹列表

    def __init__(self, selectedFolders: list, parent):
        super().__init__(parent)
        # 读入配置文件
        # self.readConfig()
        self.selectedFolders = selectedFolders.copy()
        # 创建小部件
        self.__createWidgets()
        # 初始化
        self.__initWidget()
        self.__initLayout()

    def __createWidgets(self):
        """ 创建小部件 """
        self.addFolderTimer = QTimer(self)
        self.deleteFolderTimer = QTimer(self)
        self.addFolderCard = AddFolderCard(self)
        self.completeButton = PerspectivePushButton("完成", self)
        self.titleLabel = QLabel('从本地曲库创建个人"收藏"', self)
        self.folderCard_list = []
        if self.selectedFolders:
            self.subTitleLabel = QLabel("现在我们正在查看这些文件夹", self)
            for folderPath in self.selectedFolders:
                folderCard = FolderCard(folderPath, self)
                # 在显示删除文件卡对话框前加个延时
                folderCard.clicked.connect(self.startDeleteFolderTimer)
                self.folderCard_list.append(folderCard)

    def __initWidget(self):
        """ 初始化小部件 """
        self.setFixedWidth(440)
        self.setFixedHeight(324 + 100 * len(self.folderCard_list))
        self.setAttribute(Qt.WA_StyledBackground)
        # 添加阴影
        self.setShadowEffect()
        # 初始化定时器
        self.addFolderTimer.setInterval(500)
        self.deleteFolderTimer.setInterval(600)
        self.addFolderTimer.timeout.connect(self.showFileDialog)
        self.deleteFolderTimer.timeout.connect(self.showDeleteFolderCardPanel)
        # 将信号连接到槽函数
        self.addFolderCard.clicked.connect(self.addFolderTimer.start)
        self.completeButton.clicked.connect(self.updateSelectedFolders)
        # 分配ID
        self.setObjectName("father")
        self.titleLabel.setObjectName("titleLabel")
        if hasattr(self, "subTitleLabel"):
            self.subTitleLabel.setObjectName("subTitleLabel")
        self.__setQss()

    def __initLayout(self):
        """ 初始化布局 """
        self.titleLabel.move(31, 31)
        self.addFolderCard.move(36, 120)
        self.completeButton.move(223, self.height() - 71)
        if hasattr(self, "subTitleLabel"):
            self.subTitleLabel.move(31, 79)
            for index, folderCard in enumerate(self.folderCard_list):
                folderCard.move(36, 220 + index * 100)

    def startDeleteFolderTimer(self):
        """ 打卡定时器并记录发送者 """
        self.__clickedFolder = self.sender()
        self.deleteFolderTimer.start()

    def showFileDialog(self):
        """ 定时器溢出时显示文件对话框 """
        self.addFolderTimer.stop()
        path = QFileDialog.getExistingDirectory(self, "选择文件夹", "./")
        if path and path not in self.selectedFolders:
            # 将斜杠替换为反斜杠
            path = path.replace("/", "\\")
            # 将选择的文件夹路径插入列表
            self.selectedFolders.append(path)
            # 创建文件路径卡
            self.setFixedHeight(self.height() + 100)
            self.parent().setSubWindowPos()
            newFolderCard = FolderCard(path, self)
            newFolderCard.move(36, self.height() - 206)
            self.folderCard_list.append(newFolderCard)
            newFolderCard.clicked.connect(self.startDeleteFolderTimer)

    def showDeleteFolderCardPanel(self):
        """ 显示删除文件夹对话框 """
        self.deleteFolderTimer.stop()
        self.deleteSongFolderPanel = DeleteSongFolderPanel(
            self.__clickedFolder.folderName, self.window())
        self.deleteSongFolderPanel.deleteButton.clicked.connect(
            self.deleteSongFolder)
        self.deleteSongFolderPanel.exec_()

    def deleteSongFolder(self):
        """ 删除选中的文件卡 """
        sender = self.__clickedFolder
        sender.deleteLater()
        # 获取下标
        index = self.folderCard_list.index(sender)
        self.selectedFolders.remove(sender.folderPath)
        self.folderCard_list.remove(sender)
        self.deleteSongFolderPanel.deleteLater()
        # 将下面的卡片上移
        for folderCard in self.folderCard_list[index:]:
            folderCard.move(folderCard.x(), folderCard.y() - 100)
        # 更新高度
        self.setFixedHeight(self.height() - 100)
        self.parent().setSubWindowPos()

    def setShadowEffect(self):
        """ 添加阴影 """
        self.shadowEffect = QGraphicsDropShadowEffect(self)
        self.shadowEffect.setBlurRadius(60)
        self.shadowEffect.setOffset(0, 5)
        self.setGraphicsEffect(self.shadowEffect)

    def readConfig(self):
        """ 从json文件读入配置 """
        try:
            with open("app\\config\\config.json", encoding="utf-8") as f:
                self.__config = json.load(f)  # type:dict
        except:
            self.__config = {"selected-folders": []}
        if "selected-folders" not in self.__config.keys():
            self.__config["selected-folders"] = []

    def paintEvent(self, e):
        """ 绘制边框 """
        pen = QPen(QColor(172, 172, 172))
        pen.setWidth(2)
        painter = QPainter(self)
        painter.setPen(pen)
        painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

    def __setQss(self):
        """ 设置层叠样式 """
        with open(r"app\resource\css\selectSongFolderPanel.qss",
                  encoding="utf-8") as f:
            self.setStyleSheet(f.read())

    def updateSelectedFolders(self):
        """ 更新主界面中选中的歌曲文件夹列表 """
        QApplication.processEvents()
        # 保存设置后禁用窗口
        self.setEnabled(False)
        self.updateSelectedFoldersSig.emit(self.selectedFolders)
        self.parent().deleteLater()

    def resizeEvent(self, e):
        """ 改变高度时移动按钮 """
        self.completeButton.move(223, self.height() - 71)
Esempio n. 20
0
    def initUI(self):

        self.scroll = QScrollArea(
            self
        )  # Scroll Area which contains the widgets, set as the centralWidget
        self.widget1 = QWidget(self)
        self.widget1.setStyleSheet('background-color:#FAF6F5;')
        self.widget1.resize(1024, 1800)
        # self.widget2=QWidget(self)
        # self.widget2.setStyleSheet('background-color:black;')
        # self.widget2.resize(1024,800)
        # self.widget2.move(0,500)
        self.setGeometry(100, 100, 1024, 768)
        #self.vbox = QVBoxLayout()
        #self.widget1.setLayout(self.vbox)                # Widget that contains the collection of Vertical Box
        self.epf = QLabel("", self.widget1)
        effect = QGraphicsDropShadowEffect(self.epf)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf.setGraphicsEffect(effect)
        self.epf.setStyleSheet((
            "QLabel{background-color:white; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf.setGeometry(4, 3, 1000, 60)

        self.epf1 = QLabel("", self.widget1)
        #self.epf.setFont(QFont('Arial', 18))
        effect = QGraphicsDropShadowEffect(self.epf1)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf1.setGraphicsEffect(effect)
        self.epf1.setStyleSheet((
            "QLabel{background-color:#FCFCFE; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf1.setGeometry(20, 93, 970, 1680)
        source_label = QLabel("Face Swap Using Hard Drive Videos",
                              self.widget1)
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(250, 113, 600, 35)

        qq = u'\u2190'
        bb = QPushButton(qq + ' Back', self.widget1)
        bb.setGeometry(20, 3, 85, 58)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(18)
        bb.setFont(font)
        bb.setStyleSheet((
            "QPushButton{background-color:white; color: black;border-style: ridge;border-width:0px;border-radius: 0px;border-color: white;}"
        ))
        #bb.clicked.connect(self.bb_onClick)
        self.epf = QLabel("", self.widget1)
        #self.epf.setFont(QFont('Arial', 18))
        effect = QGraphicsDropShadowEffect(self.epf)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf.setGraphicsEffect(effect)
        self.epf.setStyleSheet((
            "QLabel{background-color:white; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf.setGeometry(50, 163, 900, 420)
        source_label = QLabel("Add Source Videos", self.widget1)
        source_label.setStyleSheet('background-color:white;')
        source_label.setFont(QFont('Arial', 21))
        source_label.setGeometry(100, 175, 600, 30)
        self.add_svideo = QPushButton('+', self.widget1)
        self.add_svideo.setGeometry(850, 213, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(18)
        self.add_svideo.setFont(font)
        self.add_svideo.setStyleSheet((
            "QPushButton{background-color:red; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.add_svideo.clicked.connect(self.add_svideo_onClick)

        self.del_svideo = QPushButton('-', self.widget1)
        self.del_svideo.setGeometry(800, 213, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(28)
        self.del_svideo.setFont(font)
        self.del_svideo.setStyleSheet((
            "QPushButton{background-color:blue; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.del_svideo.clicked.connect(self.del_svideo_onClick)

        self.dataView = QTreeWidget(self.widget1)
        self.dataView.setRootIsDecorated(False)
        self.dataView.setHeaderLabels(['Ref No', 'Source Videos'])
        self.dataView.header().setStyleSheet(
            'padding-top:-2px;background-color:white;font-size:21pt; font-family: Arial;border-width:1px;border-style:outset;border-color:black; '
        )
        self.dataView.setColumnCount(2)
        self.dataView.setColumnWidth(0, 100)
        self.dataView.setColumnWidth(1, 100)

        self.dataView.setStyleSheet('background-color:white;color: black;')
        self.dataView.setFont(QFont('Times New Roman', 22))

        self.dataView.setGeometry(100, 260, 800, 265)
        #self.dataView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        QScroller.grabGesture(self.dataView.viewport(), QScroller.TouchGesture)
        #self.dataView.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
        #self.dataView.itemClicked.connect(self.onItemClicked)

        self.epf = QLabel("", self.widget1)
        #self.epf.setFont(QFont('Arial', 18))
        effect = QGraphicsDropShadowEffect(self.epf)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.epf.setGraphicsEffect(effect)
        self.epf.setStyleSheet((
            "QLabel{background-color:white; color: white;padding-left:8px;border-style: ridge;border-width:0px;border-radius: 10px;border-color: #008CBA;}"
        ))
        #self.epf.setStyleSheet('background-color:#4299ff;padding-left:10px;')
        self.epf.setGeometry(50, 603, 900, 420)
        source_label = QLabel("Add Destination Videos", self.widget1)
        source_label.setStyleSheet('background-color:white;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(100, 613, 600, 30)
        self.add_dvideo = QPushButton('+', self.widget1)
        self.add_dvideo.setGeometry(850, 653, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(18)
        self.add_dvideo.setFont(font)
        self.add_dvideo.setStyleSheet((
            "QPushButton{background-color:red; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.add_dvideo.clicked.connect(self.add_dvideo_onClick)

        self.del_dvideo = QPushButton('-', self.widget1)
        self.del_dvideo.setGeometry(800, 653, 40, 40)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(28)
        self.del_dvideo.setFont(font)
        self.del_dvideo.setStyleSheet((
            "QPushButton{background-color:blue; color: black;border-style: ridge;border-width:0px;border-radius: 20px;border-color: white;}"
        ))
        self.del_dvideo.clicked.connect(self.del_dvideo_onClick)

        self.dataView1 = QTreeWidget(self.widget1)
        self.dataView1.setRootIsDecorated(False)
        self.dataView1.setHeaderLabels(['Ref No', 'Destination Videos'])
        self.dataView1.header().setStyleSheet(
            'padding-top:-2px;background-color:white;font-size:21pt; font-family: Arial;border-width:1px;border-style:outset;border-color:black; '
        )
        self.dataView1.setColumnCount(2)
        self.dataView1.setColumnWidth(0, 100)
        self.dataView1.setColumnWidth(1, 100)

        self.dataView1.setStyleSheet('background-color:white;color: black;')
        self.dataView1.setFont(QFont('Times New Roman', 22))

        self.dataView1.setGeometry(100, 700, 800, 265)

        source_label = QLabel("Picture of Person In Source Video",
                              self.widget1)
        source_label.setFont(QFont('Arial', 22))
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setGeometry(100, 1113, 600, 30)
        self.lineEdit3 = QLineEdit(self.widget1)
        self.lineEdit3.setEnabled(False)
        self.lineEdit3.setFont(QFont('Arial', 11))
        self.lineEdit3.setGeometry(100, 1160, 650, 40)
        self.lineEdit3.setStyleSheet("background-color:white;color:black;")
        self.lineEdit3.setObjectName("lineEdit3")

        self.srcvideo_b = QPushButton('Select File', self.widget1)
        self.srcvideo_b.setGeometry(790, 1155, 120, 50)
        effect = QGraphicsDropShadowEffect(self.srcvideo_b)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.srcvideo_b.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.srcvideo_b.setFont(font)
        self.srcvideo_b.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.srcvideo_b.clicked.connect(self.srcvideo_b_onClick)

        source_label = QLabel("Picture of Person In Destination Video",
                              self.widget1)
        source_label.setFont(QFont('Arial', 22))
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setGeometry(100, 1213, 600, 30)
        self.lineEdit4 = QLineEdit(self.widget1)
        self.lineEdit4.setEnabled(False)
        self.lineEdit4.setFont(QFont('Arial', 11))
        self.lineEdit4.setGeometry(100, 1260, 650, 40)
        self.lineEdit4.setStyleSheet("background-color:white;color:black;")
        self.lineEdit4.setObjectName("lineEdit4")

        self.dstvideo_b = QPushButton('Select File', self.widget1)
        self.dstvideo_b.setGeometry(790, 1255, 120, 50)
        effect = QGraphicsDropShadowEffect(self.dstvideo_b)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.dstvideo_b.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.dstvideo_b.setFont(font)
        self.dstvideo_b.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.dstvideo_b.clicked.connect(self.dstvideo_b_onClick)

        source_label = QLabel("Output Video in which face is to be replaced",
                              self.widget1)
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(100, 1313, 600, 30)
        self.lineEdit5 = QLineEdit(self.widget1)
        self.lineEdit5.setEnabled(False)
        self.lineEdit5.setFont(QFont('Arial', 11))
        self.lineEdit5.setGeometry(100, 1360, 650, 40)
        self.lineEdit5.setStyleSheet("background-color:white;color:black;")
        self.lineEdit5.setObjectName("lineEdit5")

        self.output_v = QPushButton('Select File', self.widget1)
        self.output_v.setGeometry(790, 1355, 120, 50)
        effect = QGraphicsDropShadowEffect(self.output_v)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.output_v.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.output_v.setFont(font)
        self.output_v.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.output_v.clicked.connect(self.output_v_onClick)

        source_label = QLabel("Output Directory", self.widget1)
        source_label.setStyleSheet('background-color:#FCFCFE;')
        source_label.setFont(QFont('Arial', 22))
        source_label.setGeometry(100, 1413, 600, 30)
        self.lineEdit6 = QLineEdit(self.widget1)
        self.lineEdit6.setEnabled(False)
        self.lineEdit6.setFont(QFont('Arial', 11))
        self.lineEdit6.setGeometry(100, 1460, 650, 40)
        self.lineEdit6.setStyleSheet("background-color:white;color:black;")
        self.lineEdit6.setObjectName("lineEdit6")

        self.output_d = QPushButton('Select Folder', self.widget1)
        self.output_d.setGeometry(790, 1455, 120, 50)
        effect = QGraphicsDropShadowEffect(self.output_d)
        effect.setOffset(0, 0)
        effect.setBlurRadius(20)
        self.output_d.setGraphicsEffect(effect)
        font = QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(50)
        font.setPointSize(13)
        self.output_d.setFont(font)
        self.output_d.setStyleSheet((
            "QPushButton{background-color:#333335; color: white;border-style: ridge;border-width:0px;border-radius: 3px;border-color: #008CBA;}"
        ))
        self.output_d.clicked.connect(self.output_d_onClick)

        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.widget1)
        #self.scroll.setWidget(self.widget2)
        # self.scroll.setGeometry(0,0,1024,768)

        self.buttonWindow4 = QPushButton('Start', self.widget1)
        self.buttonWindow4.setGeometry(440, 1570, 215, 85)
        self.effect = QGraphicsDropShadowEffect(self.buttonWindow4)
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.buttonWindow4.setGraphicsEffect(self.effect)
        self.font = QFont()
        self.font.setFamily("Arial")
        self.font.setBold(True)
        self.font.setWeight(50)
        self.font.setPointSize(18)
        self.buttonWindow4.setFont(self.font)
        self.buttonWindow4.setStyleSheet((
            "QPushButton{background-color:#3C81F8; color: black;border-style: ridge;border-width:1px;border-radius: 10px;border-color: black;}"
        ))

        self.buttonWindow4.clicked.connect(self.start)

        self.setCentralWidget(self.scroll)
        self.setWindowTitle('Face Swap')

        self.dataView.itemClicked.connect(self.onItemClicked)
        self.dataView1.itemClicked.connect(self.onItemClicked1)
        self.show()
class MainWindow(QMainWindow):

    """Voice Changer main window."""

    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
        self.setWindowTitle(__doc__)
        self.setMinimumSize(240, 240)
        self.setMaximumSize(480, 480)
        self.resize(self.minimumSize())
        self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
        self.tray = QSystemTrayIcon(self)
        self.center()
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
        self.menuBar().addMenu("Sound").addAction(
            "STOP !", lambda: call("killall rec", shell=True)
        )
        windowMenu = self.menuBar().addMenu("&Window")
        windowMenu.addAction("Hide", lambda: self.hide())
        windowMenu.addAction("Minimize", lambda: self.showMinimized())
        windowMenu.addAction("Maximize", lambda: self.showMaximized())
        windowMenu.addAction("Restore", lambda: self.showNormal())
        windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
        windowMenu.addAction("Center", lambda: self.center())
        windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
        windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
        # widgets
        group0 = QGroupBox("Voice Deformation")
        self.setCentralWidget(group0)
        self.process = QProcess(self)
        self.process.error.connect(
            lambda: self.statusBar().showMessage("Info: Process Killed", 5000)
        )
        self.control = QDial()
        self.control.setRange(-10, 20)
        self.control.setSingleStep(5)
        self.control.setValue(0)
        self.control.setCursor(QCursor(Qt.OpenHandCursor))
        self.control.sliderPressed.connect(
            lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor))
        )
        self.control.sliderReleased.connect(
            lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor))
        )
        self.control.valueChanged.connect(
            lambda: self.control.setToolTip(f"<b>{self.control.value()}")
        )
        self.control.valueChanged.connect(
            lambda: self.statusBar().showMessage(
                f"Voice deformation: {self.control.value()}", 5000
            )
        )
        self.control.valueChanged.connect(self.run)
        self.control.valueChanged.connect(lambda: self.process.kill())
        # Graphic effect
        self.glow = QGraphicsDropShadowEffect(self)
        self.glow.setOffset(0)
        self.glow.setBlurRadius(99)
        self.glow.setColor(QColor(99, 255, 255))
        self.control.setGraphicsEffect(self.glow)
        self.glow.setEnabled(False)
        # Timer to start
        self.slider_timer = QTimer(self)
        self.slider_timer.setSingleShot(True)
        self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
        # an icon and set focus
        QLabel(self.control).setPixmap(
            QIcon.fromTheme("audio-input-microphone").pixmap(32)
        )
        self.control.setFocus()
        QVBoxLayout(group0).addWidget(self.control)
        self.menu = QMenu(__doc__)
        self.menu.addAction(__doc__).setDisabled(True)
        self.menu.setIcon(self.windowIcon())
        self.menu.addSeparator()
        self.menu.addAction(
            "Show / Hide",
            lambda: self.hide() if self.isVisible() else self.showNormal(),
        )
        self.menu.addAction("STOP !", lambda: call("killall rec", shell=True))
        self.menu.addSeparator()
        self.menu.addAction("Quit", lambda: exit())
        self.tray.setContextMenu(self.menu)
        self.make_trayicon()

    def run(self):
        """Run/Stop the QTimer."""
        if self.slider_timer.isActive():
            self.slider_timer.stop()
        self.glow.setEnabled(True)
        call("killall rec ; killall play", shell=True)
        self.slider_timer.start(3000)

    def on_slider_timer_timeout(self):
        """Run subprocess to deform voice."""
        self.glow.setEnabled(False)
        value = int(self.control.value()) * 100
        command = f'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {value} "'
        print(f"Voice Deformation Value: {value}")
        print(f"Voice Deformation Command: {command}")
        self.process.start(command)
        if self.isVisible():
            self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
            print("Minimizing Main Window to System TrayIcon now...")
            sleep(3)
            self.hide()

    def center(self):
        """Center Window on the Current Screen,with Multi-Monitor support."""
        window_geometry = self.frameGeometry()
        mousepointer_position = QApplication.desktop().cursor().pos()
        screen = QApplication.desktop().screenNumber(mousepointer_position)
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        window_geometry.moveCenter(centerPoint)
        self.move(window_geometry.topLeft())

    def move_to_mouse_position(self):
        """Center the Window on the Current Mouse position."""
        window_geometry = self.frameGeometry()
        window_geometry.moveCenter(QApplication.desktop().cursor().pos())
        self.move(window_geometry.topLeft())

    def make_trayicon(self):
        """Make a Tray Icon."""
        if self.windowIcon() and __doc__:
            self.tray.setIcon(self.windowIcon())
            self.tray.setToolTip(__doc__)
            self.tray.activated.connect(
                lambda: self.hide() if self.isVisible() else self.showNormal()
            )
            return self.tray.show()
Esempio n. 22
0
class UILogin(form):
    def __init__(self):
        super(UILogin, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setupUi()

    def setupUi(self):
        Login = self
        Login.setObjectName("Login")
        Login.resize(427, 548)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Login.sizePolicy().hasHeightForWidth())
        Login.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Noto Serif")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        Login.setFont(font)
        Login.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/source/img/if_16_1751363.ico"),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Login.setWindowIcon(icon)
        Login.setStyleSheet("background-color: rgb(255, 255, 255);")
        Login.setInputMethodHints(QtCore.Qt.ImhSensitiveData)
        self.MainFrame = QtWidgets.QFrame(Login)
        self.MainFrame.setGeometry(QtCore.QRect(10, 10, 411, 531))
        self.MainFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.MainFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.MainFrame.setObjectName("MainFrame")
        self.shadow = QGraphicsDropShadowEffect()
        self.shadow.setBlurRadius(4)
        self.shadow.setOffset(2)
        self.MainFrame.setGraphicsEffect(self.shadow)
        self.label_3 = QtWidgets.QLabel(self.MainFrame)
        self.label_3.setGeometry(QtCore.QRect(310, 20, 71, 71))
        self.label_3.setStyleSheet("background-color: rgb(65, 105, 225);")
        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap(":/source/img/iiie.png"))
        self.label_3.setObjectName("label_3")
        self.label = QtWidgets.QLabel(self.MainFrame)
        self.label.setGeometry(QtCore.QRect(10, 5, 81, 101))
        self.label.setStyleSheet("background-color: rgb(65, 105, 225);")
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap(":/source/img/logo.png"))
        self.label.setObjectName("label")
        self.frame_2 = QtWidgets.QFrame(self.MainFrame)
        self.frame_2.setGeometry(QtCore.QRect(40, 190, 321, 311))
        self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.frame_2.setObjectName("frame_2")
        self.label_6 = QtWidgets.QLabel(self.frame_2)
        self.label_6.setGeometry(QtCore.QRect(40, 50, 41, 41))
        self.label_6.setText("")
        self.label_6.setPixmap(QtGui.QPixmap(":/source/img/Usuario.png"))
        self.label_6.setObjectName("label_6")
        self.txtUsuario = QtWidgets.QLineEdit(self.frame_2)
        self.txtUsuario.setGeometry(QtCore.QRect(100, 70, 141, 21))
        self.txtUsuario.setStyleSheet(
            "border-bottom:1px solid black;border-top:none;")
        self.txtUsuario.setObjectName("txtUsuario")
        self.label_7 = QtWidgets.QLabel(self.frame_2)
        self.label_7.setGeometry(QtCore.QRect(40, 110, 51, 51))
        self.label_7.setText("")
        self.label_7.setPixmap(QtGui.QPixmap(":/source/img/Password.png"))
        self.label_7.setObjectName("label_7")
        self.txtPassword = QtWidgets.QLineEdit(self.frame_2)
        self.txtPassword.setGeometry(QtCore.QRect(100, 130, 141, 21))
        self.txtPassword.setStyleSheet(
            "border-bottom:1px solid black;border-top:none;")
        self.txtPassword.setEchoMode(QtWidgets.QLineEdit.Password)
        self.txtPassword.setObjectName("txtPassword")
        self.lblForgottenPass = QtWidgets.QLabel(self.frame_2)
        self.lblForgottenPass.setGeometry(QtCore.QRect(90, 190, 161, 16))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.lblForgottenPass.setFont(font)
        self.lblForgottenPass.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.lblForgottenPass.setStyleSheet(
            "QLabel{color: rgb(0, 0, 255); }lblForgottenPass:hover{color:rgb(0,0,125);}"
        )
        self.lblForgottenPass.setTextInteractionFlags(
            QtCore.Qt.TextBrowserInteraction)
        self.lblForgottenPass.setObjectName("lblForgottenPass")
        self.btnAceptar = QtWidgets.QPushButton(self.frame_2)
        self.btnAceptar.setGeometry(QtCore.QRect(90, 240, 131, 41))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.btnAceptar.setFont(font)
        self.btnAceptar.setStyleSheet("border:1px solid green;")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/source/img/OK.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btnAceptar.setIcon(icon1)
        self.btnAceptar.setIconSize(QtCore.QSize(24, 24))
        self.btnAceptar.setShortcut("")
        self.btnAceptar.setCheckable(False)
        self.btnAceptar.setFlat(True)
        self.btnAceptar.setObjectName("btnAceptar")
        self.label_4 = QtWidgets.QLabel(self.MainFrame)
        self.label_4.setGeometry(QtCore.QRect(130, 140, 151, 25))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(14)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.MainFrame)
        self.label_5.setGeometry(QtCore.QRect(50, 180, 91, 15))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(11)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.label_2 = QtWidgets.QLabel(self.MainFrame)
        self.label_2.setGeometry(QtCore.QRect(90, 40, 111, 31))
        font = QtGui.QFont()
        font.setPointSize(21)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAutoFillBackground(False)
        self.label_2.setStyleSheet(
            "color: rgb(255, 255, 0);background-color: rgb(65, 105, 225);")
        self.label_2.setObjectName("label_2")
        self.btnExit = QtWidgets.QPushButton(self.MainFrame)
        self.btnExit.setGeometry(QtCore.QRect(385, 5, 24, 24))
        self.btnExit.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/source/img/Cancelar.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btnExit.setIcon(icon2)
        self.btnExit.setIconSize(QtCore.QSize(24, 24))
        self.btnExit.setFlat(True)
        self.btnExit.setObjectName("btnExit")
        self.graphicsView = QtWidgets.QGraphicsView(self.MainFrame)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 411, 116))
        self.graphicsView.setAutoFillBackground(True)
        self.graphicsView.setStyleSheet("background-color: rgb(65, 105, 225);")
        self.graphicsView.setObjectName("graphicsView")
        self.frame_2.raise_()
        self.label_4.raise_()
        self.label_5.raise_()
        self.graphicsView.raise_()
        self.label.raise_()
        self.label_2.raise_()
        self.label_3.raise_()
        self.btnExit.raise_()
        self.center()
        self.retranslateUi(Login)
        QtCore.QMetaObject.connectSlotsByName(Login)

        # shorcut

        self.shortcut = QShortcut(Qt.Key_Return, self)
        self.shortcut.activated.connect(self.btnAceptar_Click)

        # movie

        self.movie = QMovie(":/source/img/Cargando.gif")  # 80 ,200
        self.lblmovie = QtWidgets.QLabel(self.frame_2)
        self.lblmovie.setGeometry(QtCore.QRect(135, 235, 48, 48))
        self.lblmovie.setMovie(self.movie)
        self.lblmovie.hide()
        self.movie.setScaledSize(QtCore.QSize(48, 48))

        # listener

        self.btnAceptar.clicked.connect(self.btnAceptar_Click)
        self.lblForgottenPass.mousePressEvent = self.mousePress_Click
        self.btnExit.clicked.connect(self.exit)

        # end

    def mousePress_Click(self, evt):
        if evt.buttons() == Qt.LeftButton:
            UI = UIRecuperarModal(self)
            UI.show()

    def btnAceptar_Click(self):
        if (self.txtUsuario.text() == "" or self.txtPassword.text() == ""):
            QMessageBox.warning(self, "¡Advertencia!",
                                "Rellene los campos solicitados")
            self.lblmovie.hide()
            self.btnAceptar.show()
            return
        self.btnAceptar.hide()
        self.lblmovie.show()
        self.movie.start()
        worker = Worker(
            Logica.IniciarSesion, **{
                "Usuario": self.txtUsuario.text(),
                "Password": self.txtPassword.text()
            })
        worker.signals.finished.connect(self.btnAceptar_CallBack)
        self.threadpool.start(worker)

    def btnAceptar_CallBack(self, s):
        self.lblmovie.hide()
        self.btnAceptar.show()
        if isinstance(s, Exception):
            QMessageBox.information(self, "¡Error!", str(s))
            return
        if (s.id is None):  # If returns None, API is online, but mongodb isnt
            QMessageBox.warning(self, "¡Error!", "No se pudo iniciar sesion")
            return
        if (s.id == ""):  # If returns an empty string, credentials are bad
            QMessageBox.warning(self, "¡Error!",
                                "Usuario y/o contraseña incorrectos")
            return
        if (s.id != "" and s.enabled
                == False):  # If Enabled is false, then cannot login
            QMessageBox.warning(self, "¡Advertencia!",
                                "Usuario no tiene permitido iniciar sesion")
            return
        self.txtUsuario.setText("")
        self.txtPassword.setText("")
        self.btnAceptar.clicked.disconnect(self.btnAceptar_Click)
        self.btnExit.clicked.disconnect(self.exit)
        self.signals.login.emit(s)
        self.close()

    def mousePressEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.dragPos = event.globalPos()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(self.pos() + event.globalPos() - self.dragPos)
            self.dragPos = event.globalPos()
            event.accept()

    def retranslateUi(self, Login):
        _translate = QtCore.QCoreApplication.translate
        Login.setWindowTitle(_translate("Login", "Sistema SCADA"))
        self.lblForgottenPass.setText(
            _translate("Login", "¿Olvidaste tu contraseña?"))
        self.btnAceptar.setText(_translate("Login", "Iniciar Sesión"))
        self.label_4.setText(_translate("Login", "Iniciar Sesión"))
        self.label_5.setText(_translate("Login", "Credenciales"))
        self.label_2.setText(_translate("Login", "SCADA"))
Esempio n. 23
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip("Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Close |
            QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
Esempio n. 24
0
class BasicPlaylistPanel(QWidget):
    """ 播放列表面板基类 """
    def __init__(self, parent=None):
        super().__init__(parent)
        # 创建小部件
        self.__createWidgets()
        # 初始化
        self.__initWidget()

    def __createWidgets(self):
        """ 创建小部件 """
        self.iconPic = QLabel(self)
        self.lineEdit = LineEdit(parent=self)
        self.cancelLabel = ClickableLabel("取消", self)
        self.button = PerspectivePushButton(parent=self)
        self.playlistExistedLabel = QLabel("此名称已经存在。请尝试其他名称。", self)

    def __initWidget(self):
        """ 初始化小部件 """
        self.resize(586, 644)
        self.button.resize(313, 48)
        self.setAttribute(Qt.WA_StyledBackground)
        self.setShadowEffect()
        self.playlistExistedLabel.hide()
        self.iconPic.setPixmap(
            QPixmap(
                r"app\resource\images\createPlaylistPanel\playList_icon.png"))
        # 分配ID
        self.setObjectName("basicPlaylistPanel")
        self.cancelLabel.setObjectName("cancelLabel")
        # 信号连接到槽函数
        self.cancelLabel.clicked.connect(self.parent().deleteLater)

    def setShadowEffect(self):
        """ 添加阴影 """
        self.shadowEffect = QGraphicsDropShadowEffect(self)
        self.shadowEffect.setBlurRadius(60)
        self.shadowEffect.setOffset(0, 5)
        self.setGraphicsEffect(self.shadowEffect)

    def paintEvent(self, e):
        """ 绘制边框 """
        pen = QPen(QColor(172, 172, 172))
        pen.setWidth(2)
        painter = QPainter(self)
        painter.setPen(pen)
        painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

    def _setQss(self):
        """ 设置层叠样式 """
        with open("app\\resource\\css\\playlistPanel.qss",
                  encoding="utf-8") as f:
            self.setStyleSheet(f.read())

    def _isPlaylistExist(self, playlistName) -> bool:
        """ 检测播放列表是否已经存在,如果已存在就显示提示标签 """
        # 扫描播放列表文件夹下的播放列表名字
        if not os.path.exists("app\\Playlists"):
            os.mkdir("app\\Playlists")
        playlistName_list = [
            os.path.splitext(i)[0] for i in os.listdir("app\\Playlists")
        ]
        isExist = playlistName in playlistName_list
        # 如果播放列表名字已存在显示提示标签
        self.playlistExistedLabel.setVisible(isExist)
        self.button.setEnabled(not isExist)
        return isExist
Esempio n. 25
0
    def __init__(self, parent=None):
        super(ImageViewerWidget, self).__init__(parent)
        self.setupUi(self)

        self.image_viewer = ImageViewer()
        # self.image_viewer.scene().itemAdded.connect(self._scene_item_added)
        # self.image_viewer.key_press_sgn.connect(self.viewer_keyPressEvent)
        self.image_viewer.points_selection_sgn.connect(self.extreme_points_selection_done_slot)
        self.center_layout.addWidget(self.image_viewer, 0, 0)

        self._class_label = QLabel()
        self._class_label.setVisible(False)
        self._class_label.setMargin(5)
        self._class_label.setStyleSheet('''
            QLabel{
            font: 12pt;
            border-radius: 25px;
            margin: 10px;
            color: black; 
            background-color: #FFFFDC;
            }
        ''')
        shadow = QGraphicsDropShadowEffect(self)
        shadow.setBlurRadius(8)
        shadow.setColor(QtGui.QColor(94, 93, 90).lighter())
        shadow.setOffset(2)
        self._class_label.setGraphicsEffect(shadow)
        self.center_layout.addWidget(self._class_label, 0, 0, QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)

        self.actions_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignHCenter)
        self.actions_layout.setContentsMargins(0, 5, 0, 0)
        self.images_list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.images_list_widget.currentItemChanged.connect(self.image_list_sel_changed_slot)
        self.images_list_widget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.images_list_widget.customContextMenuRequested.connect(self.image_list_context_menu)
        self.images_list_widget.setCursor(QtCore.Qt.PointingHandCursor)

        self.treeview_models = ModelsTreeview()
        self.treeview_models.setColumnWidth(0, 300)
        self.tree_view_models_layout.addWidget(self.treeview_models)
        self.treeview_models.action_click.connect(self.trv_models_action_click_slot)

        self.treeview_labels = LabelsTableView()
        self.treeview_labels.action_click.connect(self.trv_labels_action_click_slot)
        self.tree_view_labels_layout.addWidget(self.treeview_labels)
        self.treeview_labels.selectionModel().selectionChanged.connect(self.default_label_changed_slot)

        # image adjustment controls
        img_adjust_controls_layout = QFormLayout()
        self.img_adjust_page.setLayout(img_adjust_controls_layout)
        self._brightness_slider = DoubleSlider()
        self._brightness_slider.setMinimum(0.0)
        self._brightness_slider.setMaximum(100.0)
        self._brightness_slider.setSingleStep(0.5)
        self._brightness_slider.setValue(self.image_viewer.img_brightness)
        self._brightness_slider.setOrientation(QtCore.Qt.Horizontal)

        self._contrast_slider = DoubleSlider()
        self._contrast_slider.setMinimum(1.0)
        self._contrast_slider.setMaximum(3.0)
        self._contrast_slider.setSingleStep(0.1)
        self._contrast_slider.setValue(self.image_viewer.img_contrast)
        self._contrast_slider.setOrientation(QtCore.Qt.Horizontal)

        self._gamma_slider = DoubleSlider()
        self._gamma_slider.setMinimum(1.0)
        self._gamma_slider.setMaximum(5.0)
        self._gamma_slider.setSingleStep(0.1)
        self._gamma_slider.setValue(self.image_viewer.img_gamma)
        self._gamma_slider.setOrientation(QtCore.Qt.Horizontal)
        self._number_of_clusters_spin = QSpinBox()
        self._number_of_clusters_spin.setMinimum(2)
        self._number_of_clusters_spin.setValue(5)

        self._contrast_slider.doubleValueChanged.connect(self._update_contrast_slot)
        self._brightness_slider.doubleValueChanged.connect(self._update_brightness_slot)
        self._gamma_slider.doubleValueChanged.connect(self._update_gamma_slot)

        img_adjust_controls_layout.addRow(QLabel("Brightness:"), self._brightness_slider)
        img_adjust_controls_layout.addRow(QLabel("Contrast:"), self._contrast_slider)
        img_adjust_controls_layout.addRow(QLabel("Gamma:"), self._gamma_slider)
        img_adjust_controls_layout.addRow(QLabel("Clusters:"), self._number_of_clusters_spin)

        self.img_adjust_page.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.img_adjust_page.customContextMenuRequested.connect(self._image_processing_tools_ctx_menu)

        self._ds_dao = DatasetDao()
        self._hub_dao = HubDao()
        self._labels_dao = LabelDao()
        self._ann_dao = AnnotaDao()
        self._thread_pool = QThreadPool()
        self._loading_dialog = QLoadingDialog()
        self._tag = None
        self._curr_channel = 0
        self._channels = []
        self._toolbox = ImageViewerToolBox()
        self._toolbox.onAction.connect(self.on_action_toolbox_slot)
        self.actions_layout.addWidget(self._toolbox)
Esempio n. 26
0
    def __init__(self, item):
        print(item)
        super().__init__()
        self.item = item
        #             sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #             sizePolicy.setHorizontalStretch(0)
        #             sizePolicy.setVerticalStretch(0)
        #             sizePolicy.setHeightForWidth(self.session_bt_size_policy().hasHeightForWidth())
        #             self.setSizePolicy(sizePolicy)

        #             self.setMinimumSize(QSize(200, 100))
        item_size = get_option_int("item_size")
        self.setFixedSize(QSize(item_size, item_size))

        self.pushButton = QPushButton(self)
        #             允许拖放
        if item["type"] == 3:
            self.setAcceptDrops(True)
#             self.pushButton.setAcceptDrops(True)
#             self.setDragEnabled(True)
        if not item["ico"]:
            self.set_icon(get_file_realpath('data/image/firefox64.png'))
        else:
            self.check_icon_path(item)
            self.set_icon(item["ico"])
        self.pushButton.setIconSize(QSize(item_size * 0.4, item_size * 0.4))
        self.pushButton.clicked.connect(self.on_clicked)
        #             self.pushButton.setAttribute(Qt.WA_TranslucentBackground,True )
        #             self.pushButton.setAutoFillBackground(True)
        self.pushButton.setStyleSheet("border: 0px;")
        op = QGraphicsOpacityEffect()
        op.setOpacity(0.5)
        #             self.pushButton.setGraphicsEffect(op)

        self.label = QLabel(self)
        #             self.label.setSizePolicy(sizePolicy)
        self.label.setFont(QFont("sans", 10, QFont.Normal))
        self.label.setAttribute(Qt.WA_TranslucentBackground)
        pe = QPalette()
        self.label.setAutoFillBackground(True)
        pe.setColor(QPalette.WindowText, Qt.white)
        self.label.setPalette(pe)

        dse = QGraphicsDropShadowEffect(self.label)
        dse.setBlurRadius(10)
        dse.setColor(QPalette().color(QPalette.Shadow))
        dse.setOffset(0, 0)
        self.label.setGraphicsEffect(dse)

        #             self.label.setAlignment(Qt.AlignCenter)
        #             sizePolicy=QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding);
        #             sizePolicy.setHorizontalStretch(0);
        #             sizePolicy.setVerticalStretch(0);
        #             sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth());
        #             self.label.setSizePolicy(sizePolicy);
        #             self.label.setAlignment(Qt.AlignTop)
        self.label.setWordWrap(True)
        #             self.label.adjustSize()
        #             self.label.setScaledContents(True)
        if len(item["name"]) > 9:
            self.label.setText(item["name"][:9] + "\n" + item["name"][9:])
        else:
            self.label.setText(item["name"] + " \n ")

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.addWidget(self.pushButton, 5, Qt.AlignCenter)
        self.verticalLayout.addWidget(self.label, 1, Qt.AlignCenter)

        self.item_popup_menu = QMenu()
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested[QPoint].connect(self.handle_pop_menu)
        self.menu_item = [QAction("修改"), QAction("删除")]
Esempio n. 27
0
    def __init__(self,
                 title,
                 message,
                 item,
                 *args,
                 ntype=0,
                 callback=None,
                 **kwargs):
        super(NotificationItem, self).__init__(*args, **kwargs)
        self.item = item
        self.callback = callback
        layout = QHBoxLayout(self, spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.bgWidget = QWidget(self)  # 背景控件, 用于支持动画效果
        layout.addWidget(self.bgWidget)

        layout = QGridLayout(self.bgWidget)
        layout.setHorizontalSpacing(15)
        layout.setVerticalSpacing(10)

        # 标题左边图标
        layout.addWidget(QLabel(self, pixmap=NotificationIcon.icon(ntype)), 0,
                         0)

        # 标题
        self.labelTitle = QLabel(title, self)
        font = self.labelTitle.font()
        font.setBold(True)
        font.setPixelSize(22)
        self.labelTitle.setFont(font)

        # 关闭按钮
        self.labelClose = QLabel(
            self,
            cursor=Qt.PointingHandCursor,
            pixmap=NotificationIcon.icon(NotificationIcon.Close),
        )

        # 消息内容
        self.labelMessage = QLabel(
            message,
            self,
            cursor=Qt.PointingHandCursor,
            wordWrap=True,
            alignment=Qt.AlignLeft | Qt.AlignTop,
        )
        font = self.labelMessage.font()
        font.setPixelSize(20)
        self.labelMessage.setFont(font)
        self.labelMessage.adjustSize()

        # 添加到布局
        layout.addWidget(self.labelTitle, 0, 1)
        layout.addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum), 0,
            2)
        layout.addWidget(self.labelClose, 0, 3)
        layout.addWidget(self.labelMessage, 1, 1, 1, 2)

        # 边框阴影
        effect = QGraphicsDropShadowEffect(self)
        effect.setBlurRadius(12)
        effect.setColor(QColor(0, 0, 0, 25))
        effect.setOffset(0, 2)
        self.setGraphicsEffect(effect)

        self.adjustSize()

        # 5秒自动关闭
        self._timer = QTimer(self, timeout=self.doClose)
        self._timer.setSingleShot(True)  # 只触发一次
        self._timer.start(5000)
Esempio n. 28
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        ti = TrayIcon(self)
        ti.show()
        self.handler = Handle(self)
        self.m_flag = None
        self.m_Position = None
        self.setupUi(self)
        self.init_ui()
        self.click_handler()
        self.shadow = QGraphicsDropShadowEffect()
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QColor(0, 0, 0, 255))
        self.shadow.setOffset(0, 0)
        self.shadow1 = QGraphicsDropShadowEffect()
        self.shadow1.setBlurRadius(15)
        self.shadow1.setOffset(0, 0)
        self.shadow1.setColor(QColor(0, 0, 0, 255))
        self.shadow2 = QGraphicsDropShadowEffect()
        self.shadow2.setBlurRadius(15)
        self.shadow2.setOffset(0, 0)
        self.shadow2.setColor(QColor(0, 0, 0, 255))
        self.widget_2.setGraphicsEffect(self.shadow)
        self.widget.setGraphicsEffect(self.shadow1)  # 加阴影,更立体

    def init_ui(self):
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 去边框
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.centralwidget.setAttribute(
            QtCore.Qt.WA_TranslucentBackground)  # 设置pyqt自动生成的centralwidget背景透明
        self.centralwidget.setAutoFillBackground(True)
        self.pushButton.setFixedSize(QSize(BUTTON_WIDTH,
                                           BUTTON_HEIGHT))  # 设置按钮大小
        self.pushButton_2.setFixedSize(QSize(BUTTON_WIDTH,
                                             BUTTON_HEIGHT))  # 设置按钮大小
        btn_close_normal = resource_path(join("img", "btn_close_normal.png"))
        btn_close_down2 = resource_path(join("img", "btn_close_down2.png"))
        btn_close_down = resource_path(join("img", "btn_close_down.png"))
        btn_set_normal = resource_path(join("img", "btn_set_normal.png"))
        btn_min_normal = resource_path(join("img", "btn_min_normal.png"))
        Qss = 'QWidget#widget_2{background-color: %s;}' % BACKGROUND_COLOR
        Qss += 'QWidget#widget{background-color: %s;border-top-right-radius:5 ;border-top-left-radius:5 ;}' % TITLE_COLOR
        Qss += 'QWidget#widget_3{background-color: %s;}' % TITLE_COLOR
        Qss += 'QPushButton#pushButton{margin-top:6;background-color: %s;border-image:url(%s);border-top-right-radius:5 ;}' % (
            TITLE_COLOR, btn_close_normal)
        Qss += 'QPushButton#pushButton:hover{border-image:url(%s); border-top-right-radius:5 ;}' % btn_close_down2
        Qss += 'QPushButton#pushButton:pressed{border-image:url(%s);border-top-right-radius:5 ;}' % btn_close_down
        Qss += 'QPushButton#pushButton_2{margin-top:8;background-color: %s;border-image:url(%s);}' % (
            TITLE_COLOR, btn_min_normal)
        Qss += 'QPushButton#pushButton_2:hover{background-color: %s;border-image:url(%s);}' % (
            BACKGROUND_COLOR, btn_min_normal)
        Qss += 'QPushButton#pushButton_2:pressed{background-color: %s;border-top-left-radius:5 ;}' % BACKGROUND_COLOR
        Qss += 'QPushButton#pushButton_3{border-image:url(%s);background-color: %s;border-top-left-radius:5}' % (
            btn_set_normal, TITLE_COLOR)
        Qss += '#label{background-color:rbga(0,0,0,0);color:#111111;}'
        self.setStyleSheet(Qss)  # 边框部分qss重载
        self.setWindowIcon(QIcon(resource_path("icon.ico")))
        self.setWindowTitle('神秘鸭')
        self.textBrowser.append("欢迎使用神秘鸭 smya.cn")
        self.read_login_info()
        _thread.start_new_thread(self.handler.ad, ())
        _translate = QtCore.QCoreApplication.translate
        self.label.setText(
            _translate("MainWindow", "神秘鸭 v{}".format(APP_VERSION)))
        self.progressBar.setHidden(True)
        self.handler.app_update()

    def click_handler(self):
        """
        按钮点击事件
        :return:
        """
        self.pushButton.clicked.connect(self.exit_app)  # 关闭
        self.pushButton_2.clicked.connect(self.ButtonMinSlot)  # 最小化
        self.login.clicked.connect(self.handler.login)
        self.video_script.clicked.connect(self.start_script)
        self.ad1.mousePressEvent = self.handler.jump_ad
        self.checkBox.stateChanged.connect(self.select)
        _thread.start_new_thread(self.info_window_scroll, ())

    def select(self):
        with open(join(os.path.expanduser('~'), 'smya_mode.ini'), "w") as F:
            F.write("{}".format(self.checkBox.isChecked()))

    def exit_app(self):
        box = QMessageBox(QMessageBox.Information, "提示!", "你是要退出还是最小化?")
        yes = box.addButton(self.tr("退出"), QMessageBox.YesRole)
        no = box.addButton(self.tr("最小化"), QMessageBox.NoRole)
        box.exec_()
        if box.clickedButton() == yes:
            self.close()
        else:
            self.hide()

    def read_login_info(self):
        login_file = join(os.path.expanduser('~'), 'smya.json')
        _thread.start_new_thread(self.check_old_script, ())
        try:
            if exists(login_file) is True:
                with open(login_file, 'r') as f:
                    info = json.loads(f.readline())
                    device_id = info['device_id']
                    safe_code = info['safe_code']

                    if len(device_id) and len(safe_code) > 5:
                        self.device_id.setText(device_id)
                        self.safe_code.setText(safe_code)
                        self.handler.login()
        except:
            pass

    def check_old_script(self):
        """下个版本可以删掉"""
        new_path = os.path.join(os.path.expanduser('~'), 'smyascript')
        old_path = resource_path('scripts')
        if os.path.exists(new_path) is False and os.path.exists(
                old_path) is True:
            shutil.copytree(old_path, new_path)

    def send_key_event(self, data):
        self.show()

    def start_script(self):
        try:
            old_tools_path = os.path.join(
                os.path.expanduser('~'),
                'smyatoolsv{}'.format(APP_TOOLS_VERSION - 1))
            if os.path.exists(old_tools_path) is True:
                delete_file(old_tools_path)
            tools_path = os.path.join(os.path.expanduser('~'),
                                      'smyatoolsv{}'.format(APP_TOOLS_VERSION))
            if os.path.exists(join(tools_path, "smyatools.exe")) is True:
                _thread.start_new_thread(subprocess.Popen,
                                         (join(tools_path, "smyatools.exe"), ))
            else:
                if os.path.exists(tools_path) is True:
                    os.rmdir(tools_path)
                box = QMessageBox(QMessageBox.Warning, "提示!",
                                  "神秘鸭录制工具未安装或需要更新,现在是否安装!")
                yes = box.addButton(self.tr("安装"), QMessageBox.YesRole)
                no = box.addButton(self.tr("取消"), QMessageBox.NoRole)
                box.exec_()
                if box.clickedButton() == yes:
                    self.progressBar.setHidden(False)
                    self.progressBar.setValue(0)
                    f = requests.get(
                        "https://cdn.monyuan.com/smya/smyatoolsv{}.zip".format(
                            APP_TOOLS_VERSION),
                        stream=True)
                    length = float(f.headers['content-length'])
                    count = 0
                    time1 = time.time()
                    down_file = join(
                        tools_path,
                        "smyatoolsv{}.zip".format(APP_TOOLS_VERSION))
                    os.mkdir(tools_path)
                    with open(down_file, "wb") as F:
                        for chunk in f.iter_content(chunk_size=1024):
                            if chunk:
                                F.write(chunk)
                                count += len(chunk)
                                p = int(count / length * 100)
                                self.progressBar.setValue(p)
                                if p == 100:
                                    self.progressBar.setHidden(True)
                    F.close()
                    zipFile = zipfile.ZipFile(down_file)
                    for file in zipFile.namelist():
                        zipFile.extract(file, os.path.expanduser('~'))
                    zipFile.close()
                    os.remove(down_file)
                    QMessageBox.information(self, '提示!', '你已下载完成,可以使用啦!')
        except Exception as E:
            self.textBrowser.append(
                '<span style="color: red">{} {}</span>'.format(
                    datetime.strftime(datetime.now(), '%H:%M:%S'), E))
            # 下个版本删除
            self.textBrowser.append(
                '<span style="color: red">{} {}</span>'.format(
                    datetime.strftime(datetime.now(), '%H:%M:%S'),
                    "请重启电脑然后安装!"))
            QMessageBox.warning(self, '错误!', '出现问题,请看运行日志!')

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(QtCore.Qt.OpenHandCursor))

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = False
            self.setCursor(QCursor(QtCore.Qt.ArrowCursor))

    def mouseMoveEvent(self, event):
        """
        拖动事件
        :param event:
        :return:
        """
        if QtCore.Qt.LeftButton and self.m_flag:
            self.move(event.globalPos() - self.m_Position)  # 更改窗口位置
            event.accept()

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == QtCore.Qt.Key_Escape:
            self.hide()

    def ButtonMinSlot(self):
        self.showMinimized()

    def info_window_scroll(self):
        sleep(3.5)
        while True:
            self.textBrowser.moveCursor(self.textBrowser.textCursor().End)
            sleep(0.5)
Esempio n. 29
0
 def __init__(self, parent=None):
     """Init class."""
     super(MainWindow, self).__init__()
     self.setWindowTitle(__doc__.strip().capitalize())
     self.statusBar().showMessage(" Choose one App and move the sliders !")
     self.setMinimumSize(480, 240)
     self.setMaximumSize(640, 2048)
     self.setWindowIcon(QIcon.fromTheme("preferences-system"))
     self.center()
     QShortcut("Ctrl+q", self, activated=lambda: self.close())
     self.menuBar().addMenu("&File").addAction("Exit", exit)
     windowMenu = self.menuBar().addMenu("&Window")
     windowMenu.addAction("Minimize", lambda: self.showMinimized())
     windowMenu.addAction("Maximize", lambda: self.showMaximized())
     windowMenu.addAction("Restore", lambda: self.showNormal())
     windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
     windowMenu.addAction("Center", lambda: self.center())
     windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
     windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
     windowMenu.addSeparator()
     windowMenu.addAction(
         "Increase size", lambda:
         self.resize(self.size().width() * 1.4, self.size().height() * 1.4))
     windowMenu.addAction("Decrease size", lambda: self.resize(
         self.size().width() // 1.4, self.size().height() // 1.4))
     windowMenu.addAction("Minimum size", lambda:
                          self.resize(self.minimumSize()))
     windowMenu.addAction("Maximum size", lambda:
                          self.resize(self.maximumSize()))
     windowMenu.addAction("Horizontal Wide", lambda: self.resize(
         self.maximumSize().width(), self.minimumSize().height()))
     windowMenu.addAction("Vertical Tall", lambda: self.resize(
         self.minimumSize().width(), self.maximumSize().height()))
     windowMenu.addSeparator()
     windowMenu.addAction("Disable Resize", lambda:
                          self.setFixedSize(self.size()))
     windowMenu.addAction("Set Interface Font...", lambda:
                          self.setFont(QFontDialog.getFont()[0]))
     helpMenu = self.menuBar().addMenu("&Help")
     helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self))
     helpMenu.addAction("About Python 3",
                        lambda: open_new_tab('https://www.python.org'))
     helpMenu.addAction("About" + __doc__,
                        lambda: QMessageBox.about(self, __doc__, HELP))
     helpMenu.addSeparator()
     helpMenu.addAction(
         "Keyboard Shortcut",
         lambda: QMessageBox.information(self, __doc__, "<b>Quit = CTRL+Q"))
     helpMenu.addAction("View Source Code",
                        lambda: call('xdg-open ' + __file__, shell=True))
     helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__))
     helpMenu.addAction("Report Bugs", lambda: open_new_tab(
         'https://github.com/juancarlospaco/pyority/issues?state=open'))
     helpMenu.addAction("Check Updates", lambda: Downloader(self))
     container, child_container = QWidget(), QWidget()
     container_layout = QVBoxLayout(container)
     child_layout = QHBoxLayout(child_container)
     self.setCentralWidget(container)
     # widgets
     group0 = QGroupBox("My Apps")
     group1, group2 = QGroupBox("CPU Priority"), QGroupBox("HDD Priority")
     child_layout.addWidget(group0)
     child_layout.addWidget(group1)
     child_layout.addWidget(group2)
     container_layout.addWidget(child_container)
     # table
     self.table = QTableWidget()
     self.table.setColumnCount(1)
     self.table.verticalHeader().setVisible(True)
     self.table.horizontalHeader().setVisible(False)
     self.table.setShowGrid(False)
     self.table.setAlternatingRowColors(True)
     self.table.setIconSize(QSize(64, 64))
     self.table.setSelectionMode(QAbstractItemView.SingleSelection)
     self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
     # Graphic effect
     glow = QGraphicsDropShadowEffect(self)
     glow.setOffset(0)
     glow.setBlurRadius(9)
     glow.setColor(QColor(99, 255, 255))
     self.table.setGraphicsEffect(glow)
     glow.setEnabled(True)
     processes = self.generate_process_list()
     self.table.setRowCount(len(processes))
     for index, process in enumerate(processes):
         item = QTableWidgetItem(
             QIcon.fromTheme(process.name().split()[0].split('/')[0]),
             process.name().split()[0].split('/')[0].strip())
         item.setData(Qt.UserRole, process)
         item.setToolTip("{}, {}, {}, {}".format(
             process.name(), process.nice(),
             process.ionice()[1], process.pid))
         self.table.setItem(index, 0, item)
     self.table.clicked.connect(lambda: self.sliderhdd.setDisabled(False))
     self.table.clicked.connect(lambda: self.slidercpu.setDisabled(False))
     self.table.clicked.connect(lambda: self.slidercpu.setValue(
         int(tuple(self.table.currentItem().toolTip().split(","))[1])))
     self.table.clicked.connect(lambda: self.sliderhdd.setValue(
         int(tuple(self.table.currentItem().toolTip().split(","))[2])))
     self.table.resizeColumnsToContents()
     # self.table.resizeRowsToContents()
     # sliders
     self.slidercpu = QSlider()
     self.slidercpu.setRange(0, 19)
     self.slidercpu.setSingleStep(1)
     self.slidercpu.setTickPosition(3)
     self.slidercpu.setDisabled(True)
     self.slidercpu.setInvertedAppearance(True)
     self.slidercpu.setInvertedControls(True)
     self.slidercpu.valueChanged.connect(self.set_cpu_value)
     self.slidercpu.valueChanged.connect(
         lambda: self.slidercpu.setToolTip(str(self.slidercpu.value())))
     # Timer to start
     self.slidercpu_timer = QTimer(self)
     self.slidercpu_timer.setSingleShot(True)
     self.slidercpu_timer.timeout.connect(self.on_slidercpu_timer_timeout)
     QLabel(self.slidercpu).setPixmap(
         QIcon.fromTheme("list-add").pixmap(16))
     QVBoxLayout(group1).addWidget(self.slidercpu)
     self.sliderhdd = QSlider()
     self.sliderhdd.setRange(0, 7)
     self.sliderhdd.setSingleStep(1)
     self.sliderhdd.setTickPosition(3)
     self.sliderhdd.setDisabled(True)
     self.sliderhdd.setInvertedAppearance(True)
     self.sliderhdd.setInvertedControls(True)
     self.sliderhdd.valueChanged.connect(self.set_hdd_value)
     self.sliderhdd.valueChanged.connect(
         lambda: self.sliderhdd.setToolTip(str(self.sliderhdd.value())))
     # Timer to start
     self.sliderhdd_timer = QTimer(self)
     self.sliderhdd_timer.setSingleShot(True)
     self.sliderhdd_timer.timeout.connect(self.on_sliderhdd_timer_timeout)
     QLabel(self.sliderhdd).setPixmap(
         QIcon.fromTheme("list-add").pixmap(16))
     QVBoxLayout(group2).addWidget(self.sliderhdd)
     QVBoxLayout(group0).addWidget(self.table)
Esempio n. 30
0
 def __init__(self, title, *args, **kwargs):
     super(Title, self).__init__(title, *args, **kwargs)
     shadow = QGraphicsDropShadowEffect()
     shadow.setBlurRadius(8)
     shadow.setOffset(2.5, 2.5)
     self.setGraphicsEffect(shadow)