コード例 #1
0
    def show_reasons(self):

        reasons = self.get_reasons()
        for reason, fails in reasons.items():
            if hasattr(reason, "friendly"):
                self.layout.addWidget(QLabel("<b>%s</b>" % reason.friendly))
            else:
                self.layout.addWidget(QLabel("<b>%s</b>" % str(reason)))

            if hasattr(reason, "info"):
                self.layout.addWidget(QLabel("<em>%s</em>" % reason.info))

            table = QListWidget()
            for fail in fails:
                item = QListWidgetItem("")
                table.addItem(item)

                item_widget = FailedListWidgetItemWidget(
                    self.get_specified_field_or_first_non_empty(
                        fail.card,
                        self.config.get_note_type_specific_config_object(
                            "searchField",
                            fail.card.note_type()["id"]).value), fail.card,
                    self.mw, self.parent, fail.reason.specific_info if hasattr(
                        fail.reason, "specific_info") else None)

                item.setSizeHint(item_widget.minimumSizeHint())
                table.setItemWidget(item, item_widget)
            table.setSelectionMode(QAbstractItemView.NoSelection)
            table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
            table.adjustSize()
            self.layout.addWidget(table)
        self.adjustSize()
コード例 #2
0
class PortSelectionPopup(QDialog):
    def __init__(self, parent, ports, *args, **kwargs):
        super(PortSelectionPopup, self).__init__(*args, **kwargs)
        self.parent = parent
        self.ports = ports
        self.selected = False

        self.setWindowTitle('Select an Arduino to connect to')
        self.setModal(True)
        self.port_selection = QListWidget(self)
        self.port_selection.move(10, 10)
        for port in ports:
            self.port_selection.addItem(port.description)
        self.port_selection.adjustSize()
        description_to_port = {port.description: port.device for port in ports}

        # Double-click
        def port_selected(item):
            port = description_to_port[item.text()]
            self.accept()

            # Show connecting popup
            popup = QMessageBox(parent)
            popup.setWindowModality(QtCore.Qt.WindowModal)
            popup.setIcon(QMessageBox.Information)
            popup.setStandardButtons(QMessageBox.Abort)
            popup.setWindowTitle('Please wait')
            popup.setText(f'Connecting to Arduino at port:\n{port}')
            t = UiThread(parent.initialize, port)
            t.success.connect(partial(popup.done, 0))
            t.start()
            result = popup.exec_()
            if result == QMessageBox.Abort:
                if t.isRunning():
                    t.terminate()
                parent.show_error_popup('Connect canceled', exit=True)

        self.port_selection.itemDoubleClicked.connect(port_selected)
        self.rejected.connect(
            partial(parent.show_error_popup, 'No port selected', exit=True))
コード例 #3
0
ファイル: test2.py プロジェクト: lroberto68/TestPyQt
class MainWindow(QMainWindow):
    window_titles = ['finestra1', 'finestra2', 'finestra3', 'finito']

    def __init__(self):
        super(MainWindow, self).__init__()

        self.num_time = 0
        print("ciao a tutti")

        self.setWindowTitle("My app")
        self.windowTitleChanged.connect(self.the_window_title_is_changed)
        self.setGeometry(0, 0, 400, 400)

        self.cmBox = QComboBox(self)
        self.cmBox.move(30, 100)
        self.cmBox.setInsertPolicy(QComboBox.InsertAlphabetically)
        self.cmBox.addItems(['Roberto', 'Federica', 'Roberta'])

        self.lsWidget = QListWidget(self)
        self.lsWidget.move(30, 150)
        self.lsWidget.addItems(self.window_titles)
        self.lsWidget.adjustSize()

        self.pbClick = QPushButton("Click", self)
        self.pbClick.clicked.connect(self.window_title_change)

        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignVCenter)
        self.label.move(30, 20)

        self.chBox = QCheckBox("Test", self)
        self.chBox.setTristate(True)
        self.chBox.setChecked(Qt.PartiallyChecked)
        self.chBox.move(30, 60)
        self.chBox.stateChanged.connect(self.show_state)

        self.lnEdit = QLineEdit(self)
        self.lnEdit.move(200, 100)
        self.lnEdit.setText(self.cmBox.currentText())

        self.cmBox.currentTextChanged.connect(self.lnEdit.setText)
        self.lsWidget.currentTextChanged.connect(self.text_change)

    def window_title_change(self):
        new_window_title = choice(self.window_titles)
        self.setWindowTitle(new_window_title)
        self.cmBox.addItem(self.lnEdit.text())

    def the_window_title_is_changed(self, window_title):
        self.num_time += 1
        print(
            f"The new window title is {window_title}, cambiato {self.num_time} volte"
        )
        self.label.setText(f"{self.num_time}")

        if window_title == 'finito':
            self.pbClick.setEnabled(False)

    def show_state(self, s):
        print(s == Qt.Checked)
        print(s)

    def text_change(self, s):
        print(f"Valore = {s}")
コード例 #4
0
class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.user_interface()

    def item_click(self, item):
        number = self.view.currentRow()
        if self.shuffled == False:
            self.playlist.setCurrentIndex(number)
            self.player.play()
        elif self.shuffled == True:
            pass

    def item_doubleclick(self, item):
        self.current_item_song = item
        menu = QtWidgets.QMenu()
        createPlaylist = QAction('Create New Playlist')
        createPlaylist.triggered.connect(self.create_playlist)
        menu.addAction(createPlaylist)
        addToPlaylist = QAction('Add To Playlist')
        addToPlaylist.triggered.connect(self.add_to_playlist)
        menu.addAction(addToPlaylist)
        menu.exec_()

    def user_interface(self):
        self.all_song_button = QtWidgets.QPushButton("All songs")
        self.play_button = QtWidgets.QPushButton()
        self.play_button.setIcon(self.style().standardIcon(
            QStyle.SP_MediaPlay))
        self.next_button = QtWidgets.QPushButton()
        self.next_button.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekForward))
        self.prev_button = QtWidgets.QPushButton()
        self.prev_button.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekBackward))
        self.shuffle_button = QtWidgets.QPushButton("🔀")
        self.min_volumn = QtWidgets.QLabel("🔈")
        self.max_volumn = QtWidgets.QLabel("🔊")
        self.l_playlists = QtWidgets.QLabel("Playlists:")
        self.l_current_song = QtWidgets.QLabel("Current song:")

        self.songs = QtWidgets.QLabel("Songs:\n")

        self.view = QListWidget()
        self.viewPlaylists = QListWidget()
        self.all_songs = self.load_songs()
        self.all_playlists = self.load_playlists()
        self.viewPlaylists.adjustSize()

        self.view.adjustSize()
        self.view.itemClicked.connect(self.item_click)
        self.view.itemDoubleClicked.connect(self.item_doubleclick)

        self.view.installEventFilter(self)

        self.set_playlist()

        self.line_edit = QtWidgets.QLineEdit()
        self.line_edit.setText("")
        self.search_button = QtWidgets.QPushButton("search")

        # scroll are for list of songs
        self.songs_scroll_area = QtWidgets.QScrollArea()
        self.songs_scroll_area.setWidget(self.view)
        self.songs_scroll_area.setWidgetResizable(True)

        # scroll area for list of playlists
        self.playlists_scroll_area = QtWidgets.QScrollArea()
        self.playlists_scroll_area.setWidget(self.viewPlaylists)
        self.playlists_scroll_area.setWidgetResizable(True)
        # self.playlists_scroll_bar = QtWidgets.QScrollBar()
        # self.playlists_scroll_area.setVerticalScrollBar(self.playlists_scroll_bar)
        # self.playlists_scroll_area.setVerticalScrollBarPolicy(C.Qt.ScrollBarAlwaysOn)

        # set area for current song box
        self.current_song_area = QtWidgets.QScrollArea()
        self.current_song_area.setWidget(self.l_current_song)

        # set volumn slider
        self.volumn_slider = QtWidgets.QSlider(C.Qt.Horizontal)
        self.volumn_slider.setMaximum(100)
        self.volumn_slider.setMinimum(0)
        self.volumn_slider.setValue(50)
        self.volumn_slider.setTickPosition(QtWidgets.QSlider.TicksRight)
        self.volumn_slider.setTickInterval(10)

        self.seekSlider = QtWidgets.QSlider()
        self.seekSlider.setMinimum(0)
        self.seekSlider.setMaximum(100)
        self.seekSlider.setRange(0, self.player.duration() / 1000)
        self.seekSlider.setOrientation(C.Qt.Horizontal)
        self.seekSlider.setTracking(False)
        seekSliderLabel1 = QtWidgets.QLabel('0.00')
        seekSliderLabel2 = QtWidgets.QLabel('0.00')

        self.set_playlist()
        self.volume_change()

        # self.list_view = QtWidgets.QListView(self.all_songs)

        h_box = QtWidgets.QHBoxLayout()
        v_box = QtWidgets.QVBoxLayout()
        self.h_box4 = QtWidgets.QHBoxLayout()

        # h_box.addWidget(backGround)

        v_box.addWidget(self.all_song_button)
        v_box.addWidget(self.playlists_scroll_area)
        v_box.addWidget(self.current_song_area)

        self.h_box4.addWidget(seekSliderLabel1)
        self.h_box4.addWidget(self.seekSlider)
        self.h_box4.addWidget(seekSliderLabel2)

        h_box.addLayout(v_box)

        v_box1 = QtWidgets.QVBoxLayout()
        v_box1.addWidget(self.line_edit)

        v_box2 = QtWidgets.QVBoxLayout()
        v_box2.addWidget(self.songs_scroll_area)

        h_box.addLayout(v_box1)

        h_box1 = QtWidgets.QHBoxLayout()
        h_box1.addWidget(self.shuffle_button)
        h_box1.addWidget(self.prev_button)
        h_box1.addWidget(self.play_button)
        h_box1.addWidget(self.next_button)

        h_box3 = QtWidgets.QHBoxLayout()
        h_box3.addWidget(self.min_volumn)
        h_box3.addWidget(self.volumn_slider)
        h_box3.addWidget(self.max_volumn)

        h_box2 = QtWidgets.QHBoxLayout()
        h_box2.addWidget(self.search_button)

        v_box1.addLayout(h_box2)
        v_box1.addLayout(v_box2)
        v_box1.addLayout(self.h_box4)
        v_box1.addLayout(h_box1)
        v_box1.addLayout(h_box3)

        self.setLayout(h_box)

        self.setWindowTitle("Music Player")
        self.setGeometry(100, 100, 800, 600)
        self.show()

        self.play_button.setShortcut(' ')
        self.next_button.setShortcut('Alt+Right')
        self.prev_button.setShortcut('Alt+Left')
        self.search_button.setShortcut('Return')
        self.play_button.clicked.connect(self.play)
        self.next_button.clicked.connect(self.next)
        self.prev_button.clicked.connect(self.back)
        self.shuffle_button.clicked.connect(self.shuffle)
        self.search_button.clicked.connect(self.search)
        self.volumn_slider.valueChanged.connect(self.volume_change)
        self.all_song_button.clicked.connect(self.load_songs)
        self.player.currentMediaChanged.connect(self.current_song)
        self.player.positionChanged.connect(self.qmp_positionChanged)
        self.player.durationChanged.connect(self.change_duration)
        self.all_song_button.clicked.connect(self.show_all_songs)

        self.shuffled = False

    def add_to_playlist(self):
        menu = QtWidgets.QMenu()
        for item in self.all_playlists:
            menuItemTask = menu.addAction(item)
            menuItemTask.triggered.connect(self.picked_playlist)
            menu.addAction(menuItemTask)
        menu.exec_()

    def picked_playlist(self):
        print(self.current_item_song)
        # file = open(item, 'w')
        # file.write(self.current_item)
        # file.close()

    def create_playlist(self):
        root = C.QFileInfo(__file__).absolutePath()
        spot = (root + '/songs/')
        playlistName = self.getText()
        completeName = os.path.join(spot, f'{playlistName}.m3u')
        file = open(completeName, 'w')
        file.close()
        self.all_playlists.clear()
        self.playlists_scroll_area.update()
        self.all_playlists = self.load_playlists()
        self.playlists_scroll_area.update()

    def getText(self):
        text, okPressed = QInputDialog.getText(self, "New Playlist",
                                               "Playlist Name:",
                                               QLineEdit.Normal, "")
        if okPressed and text != '':
            return text

    def load_playlists(self):
        playlists = []
        root = C.QFileInfo(__file__).absolutePath()
        songs = os.listdir(root + "/songs")
        for item in songs:
            if str(item[-4:]) == '.m3u':
                self.viewPlaylists.addItem(item[:-4])
                print(root + "/songs" + item)
                playlists.append(root + "/songs" + item)
        return playlists

    def show_all_songs(self):
        self.view.clear()
        self.playlist.clear()
        root = C.QFileInfo(__file__).absolutePath()
        songs = os.listdir(root + "/songs")
        s = "Songs:\n"
        for item in songs:
            if item.endswith('.mp3'):
                url = C.QUrl.fromLocalFile(item)
                content = M.QMediaContent(url)
                s = (str(item[:-4]))
                self.view.addItem(s)
                self.playlist.addMedia(content)

    def current_song(self, media):
        name = media.canonicalUrl()
        name = name.toString()
        name = name.split('/')
        url = name[-1]
        url = url[:-4]
        self.l_current_song.setText('Current Song:\n\n' + url)
        self.l_current_song.adjustSize()

    def change_duration(self):
        self.seekSlider.setRange(0, self.player.duration() / 1000)

    def qmp_positionChanged(self, position):
        if self.shuffled == False:
            sliderLayout = self.h_box4.layout()
            sliderLayout.itemAt(0).widget().setText(
                '%d:%02d' % (int(position / 60000), int(
                    (position / 1000) % 60)))
            self.seekSlider.setValue(position / 1000)
            sliderLayout.itemAt(2).widget().setText(
                '%d:%02d' % (int(self.player.duration() / 60000),
                             int((self.player.duration() / 1000) % 60)))
        elif self.shuffled == True:
            sliderLayout = self.h_box4.layout()
            sliderLayout.itemAt(0).widget().setText(
                '%d:%02d' % (int(position / 60000), int(
                    (position / 1000) % 60)))
            self.seekSlider.setValue(position / 1000)
            sliderLayout.itemAt(2).widget().setText(
                '%d:%02d' % (int(self.player.duration() / 60000),
                             int((self.player.duration() / 1000) % 60)))

    def load_songs(self):
        songList = []
        s = 'Songs:\n\n'
        root = C.QFileInfo(__file__).absolutePath()
        songs = os.listdir(root + "/songs")
        for item in songs:
            if item.endswith('.mp3'):
                s += (str(item[:-4]) + '\n')
                self.view.addItem(str(item[:-4]))
                song = (root + '/songs/' + item + '\n')
                songList.append(song)
        self.songs.setText(s)
        return songList

    def set_playlist(self):
        self.player = M.QMediaPlayer(self)
        self.player2 = M.QMediaPlayer(self)
        self.playlist = M.QMediaPlaylist(self.player)
        self.playlist2 = M.QMediaPlaylist(self.player2)
        for song in self.all_songs:
            url = C.QUrl.fromLocalFile(song[:-1])
            content = M.QMediaContent(url)
            self.playlist.addMedia(content)
            self.playlist2.addMedia(content)
        self.playlist.setCurrentIndex(0)
        self.playlist2.shuffle()
        self.playlist2.setCurrentIndex(0)
        self.player.setPlaylist(self.playlist)
        self.player2.setPlaylist(self.playlist2)

    def play(self):
        if self.shuffled == False:
            if self.player.state() == 0 or self.player.state() == 2:
                self.play_button.setIcon(self.style().standardIcon(
                    QStyle.SP_MediaPause))
                self.player.play()
            else:
                self.player.pause()
                self.play_button.setIcon(self.style().standardIcon(
                    QStyle.SP_MediaPlay))
        else:
            if self.player2.state() == 0 or self.player2.state() == 2:
                self.play_button.setIcon(self.style().standardIcon(
                    QStyle.SP_MediaPause))
                self.player2.play()
            else:
                self.player2.pause()
                self.play_button.setIcon(self.style().standardIcon(
                    QStyle.SP_MediaPlay))

    def next(self):
        if self.shuffled == False:
            numb = self.playlist.currentIndex()
            self.playlist.setCurrentIndex(numb + 1)
            self.player.play()
        else:
            numb = self.playlist2.currentIndex()
            self.playlist2.setCurrentIndex(numb + 1)
            self.player2.play()

    def back(self):
        if self.shuffled == False:
            numb = self.playlist.currentIndex()
            self.playlist.setCurrentIndex(numb - 1)
            self.player.play()
        else:
            numb = self.playlist2.currentIndex()
            self.playlist2.setCurrentIndex(numb - 1)
            self.player2.play()

    def shuffle(self):
        if self.shuffled == False:
            self.player.stop()
            self.playlist2.shuffle()
            self.playlist2.setCurrentIndex(0)
            self.player2.play()
            self.shuffled = True
        elif self.shuffled == True:
            self.player2.stop()
            self.playlist.setCurrentIndex(0)
            self.player.play()
            self.shuffled = False

    def volume_change(self):
        numb = self.volumn_slider.value()
        self.player.setVolume(numb)
        self.player2.setVolume(numb)

    def display_song_list(self, list_of_songs):
        self.view.clear()
        if self.shuffled == False:
            self.playlist.clear()
        else:
            self.playlist2.clear()
        s = 'Songs:\n\n'
        for item in list_of_songs:
            url = C.QUrl.fromLocalFile(item)
            content = M.QMediaContent(url)
            if self.shuffled == False:
                self.playlist.addMedia(content)
            else:
                self.playlist2.addMedia(content)
            s += (str(item[:-4]) + '\n')
            self.view.addItem(s)

    def search(self):
        s_term = self.line_edit.text()
        filtered_list_of_songs = []
        root = C.QFileInfo(__file__).absolutePath()
        songs = os.listdir(root + "/songs")
        # search through each song in all_songs...if it matches add to filtered_list_of_songs
        for song in songs:
            if song.lower().find(s_term.lower()) > -1:
                filtered_list_of_songs.append(song)
        self.display_song_list(filtered_list_of_songs)
コード例 #5
0
ファイル: imxsb-qtui.py プロジェクト: molejar/imxsb
class MainWindow(QFrame):

    smx_file = core.SmxFile()
    hotplug = core.HotPlug()
    devices = []
    target = None
    worker = None

    def __init__(self):
        super().__init__()
        self.setWindowTitle('i.MX Smart-Boot Tool')
        self.setMinimumSize(600, 400)
        self.center()

        # create main box
        layout = QVBoxLayout()

        # --------------------------------------------------------------------------------------------------------------
        # Device selection drop-box with scan button
        # --------------------------------------------------------------------------------------------------------------
        box = QHBoxLayout()
        self.deviceBox = QComboBox()
        box.addWidget(self.deviceBox)

        self.scanButton = QPushButton("  Scan")
        self.scanButton.setFixedWidth(80)
        self.scanButton.setIcon(QIcon.fromTheme("view-refresh"))
        self.scanButton.clicked.connect(self.on_scan_button_clicked)
        box.addWidget(self.scanButton)
        layout.addLayout(box)

        # --------------------------------------------------------------------------------------------------------------
        # SMX File inbox with open button
        # --------------------------------------------------------------------------------------------------------------
        box = QHBoxLayout()
        self.smxEdit = QLineEdit()
        self.smxEdit.setReadOnly(True)
        box.addWidget(self.smxEdit)

        self.openButton = QPushButton(" Open")
        self.openButton.setFixedWidth(80)
        self.openButton.setIcon(QIcon.fromTheme("document-open"))
        self.openButton.clicked.connect(self.on_open_button_clicked)
        box.addWidget(self.openButton)
        layout.addLayout(box)

        # --------------------------------------------------------------------------------------------------------------
        # Body
        # --------------------------------------------------------------------------------------------------------------
        self.splitter = QSplitter()
        self.splitter.setHandleWidth(5)
        self.splitter.setMidLineWidth(0)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setOpaqueResize(True)
        self.splitter.setChildrenCollapsible(False)

        self.scriptsList = QListWidget(self.splitter)
        self.scriptsList.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)
        self.scriptsList.setMinimumHeight(60)

        self.textEdit = QTextEdit(self.splitter)
        self.textEdit.setReadOnly(True)
        self.textEdit.setMinimumHeight(100)
        layout.addWidget(self.splitter)

        # Progress Bar
        self.pgTask = QProgressBar()
        self.pgTask.setRange(0, PGRANGE)
        self.pgTask.setFixedHeight(16)
        self.pgTask.setTextVisible(False)
        layout.addWidget(self.pgTask)

        # --------------------------------------------------------------------------------------------------------------
        # Buttons
        # --------------------------------------------------------------------------------------------------------------
        box = QHBoxLayout()
        box.setContentsMargins(-1, 5, -1, -1)

        # About Button
        self.aboutButton = QPushButton(" About")
        self.aboutButton.setMinimumSize(100, 40)
        self.aboutButton.setIcon(QIcon.fromTheme("help-contents"))
        self.aboutButton.clicked.connect(self.on_about_button_clicked)
        box.addWidget(self.aboutButton)

        # Device Info Button
        self.devInfoButton = QPushButton(" DevInfo")
        self.devInfoButton.setEnabled(False)
        self.devInfoButton.setMinimumSize(100, 40)
        self.devInfoButton.setIcon(QIcon.fromTheme("help-about"))
        self.devInfoButton.clicked.connect(self.on_info_button_clicked)
        box.addWidget(self.devInfoButton)

        # Spacer
        box.addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))

        # Start Button
        self.startButton = QPushButton(" Start")
        self.startButton.setEnabled(False)
        self.startButton.setMinimumSize(100, 40)
        self.startButton.setIcon(QIcon.fromTheme("media-playback-start"))
        self.startButton.clicked.connect(self.on_start_button_clicked)
        box.addWidget(self.startButton)

        # Start Button
        self.exitButton = QPushButton(" Exit")
        self.exitButton.setMinimumSize(100, 40)
        self.exitButton.setIcon(QIcon.fromTheme("application-exit"))
        self.exitButton.clicked.connect(self.on_exit_button_clicked)
        box.addWidget(self.exitButton)

        layout.addLayout(box)
        self.setLayout(layout)

        # USB hot-plug (Linux only)
        # self.hotplug.attach(self.scan_usb)
        # self.hotplug.start()
        # TODO: Fix USB hot-plug
        self.scan_usb()

    def center(self):
        # center point of screen
        cp = QDesktopWidget().availableGeometry().center()
        # move rectangle's center point to screen's center point
        qr = self.frameGeometry()
        qr.moveCenter(cp)
        # top left of rectangle becomes top left of window centering it
        self.move(qr.topLeft())

    ####################################################################################################################
    # Helper methods
    ####################################################################################################################
    def scan_usb(self, obj=None):
        self.devices = imx.sdp.scan_usb(self.target)
        self.deviceBox.clear()
        if self.devices:
            for dev in self.devices:
                self.deviceBox.addItem(dev.usbd.info())
            self.deviceBox.setCurrentIndex(0)
            self.deviceBox.setEnabled(True)
            self.devInfoButton.setEnabled(True)
            self.startButton.setEnabled(False if self.target is None else True)
        else:
            self.deviceBox.setEnabled(False)
            self.devInfoButton.setEnabled(False)
            self.startButton.setEnabled(False)

    def Logger(self, msg, clear):
        if clear:
            self.textEdit.clear()
        if msg:
            self.textEdit.append(msg)

    def ProgressBar(self, value):
        self.pgTask.setValue(min(value, PGRANGE))

    def ShowMesageBox(self, title, message, icon=QMessageBox.Warning):
        alert = QMessageBox()
        alert.setWindowTitle(title)
        alert.setText(message)
        alert.setIcon(icon)
        alert.exec_()

    ####################################################################################################################
    # Buttons callback methods
    ####################################################################################################################
    def on_scan_button_clicked(self):
        self.scan_usb()

    def on_open_button_clicked(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Choose a SmartBoot script file",
            BASEDIR,
            "i.MX SmartBoot Files (*.smx)",
            options=options)
        if fileName:
            self.smxEdit.clear()
            self.scriptsList.clear()
            try:
                self.smx_file.open(fileName, True)
            except Exception as e:
                self.ShowMesageBox("SMX File Open Error", str(e),
                                   QMessageBox.Warning)
                self.target = None
                self.startButton.setEnabled(False)
            else:
                self.target = self.smx_file.platform
                self.smxEdit.setText(fileName)
                for i, item in enumerate(self.smx_file.scripts):
                    self.scriptsList.addItem("{}.  {}  ({})".format(
                        i, item.name, item.description))
                self.scriptsList.setCurrentRow(0)
                self.scriptsList.adjustSize()
                # update usb device list
                self.scan_usb()

    def on_about_button_clicked(self):
        text = "<b>i.MX SmartBoot Tool</b> v {}".format(core.__version__)
        text += "<p>{}".format(core.DESCRIPTION)
        text += "<p>Copyright &copy; 2018 Martin Olejar."
        text += "<p>License: {}".format(core.__license__)
        text += "<p>Sources: <a href='https://github.com/molejar/imxsb'>https://github.com/molejar/imxsb</a>"
        QMessageBox.about(self, "About", text)

    def on_info_button_clicked(self):
        device = self.devices[self.deviceBox.currentIndex()]
        device.open()
        self.textEdit.clear()
        self.textEdit.append("Device: {} \n".format(device.device_name))
        device.close()

    def on_start_button_clicked(self):
        if self.startButton.text().endswith("Start"):
            try:
                device = self.devices[self.deviceBox.currentIndex()]
                script = self.smx_file.get_script(
                    self.scriptsList.currentRow())
            except Exception as e:
                self.ShowMesageBox("Script Load Error", str(e),
                                   QMessageBox.Warning)
            else:
                # Start Worker
                self.worker = Worker(device, script)
                self.worker.logger.connect(self.Logger)
                self.worker.finish.connect(self.on_finish)
                self.worker.prgbar.connect(self.ProgressBar)
                self.worker.daemon = True
                self.worker.start()

                self.startButton.setText(" Stop")
                self.startButton.setIcon(
                    QIcon.fromTheme("media-playback-stop"))
                self.scanButton.setEnabled(False)
                self.openButton.setEnabled(False)
                self.deviceBox.setEnabled(False)
                self.scriptsList.setEnabled(False)
                self.devInfoButton.setEnabled(False)
        else:
            # Stop Worker
            self.worker.stop()

    def on_finish(self, msg, done):
        self.textEdit.append(msg)
        self.startButton.setText(" Start")
        self.startButton.setIcon(QIcon.fromTheme("media-playback-start"))
        self.scanButton.setEnabled(True)
        self.scriptsList.setEnabled(True)
        self.openButton.setEnabled(True)
        if done:
            self.deviceBox.clear()
            self.startButton.setEnabled(False)
        else:
            self.scan_usb()

    def on_exit_button_clicked(self):
        self.close()
コード例 #6
-2
class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle("Tranquility Music Player")
        self.setWindowIcon(QIcon('Images/music.ico'))
        self.setGeometry(300, 300, 500, 400)

        # Create the menubar
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('File')
        playlistMenu = mainMenu.addMenu('Playlist')
        viewMenu = mainMenu.addMenu('View')
        helpMenu = mainMenu.addMenu('Help')

        openFile = QAction('Open File', self)
        createPlaylist = QAction('Create Playlist', self)
        savePlaylist = QAction('Save Playlist', self)
        toggleTheme = QAction('Toggle Black/White Theme', self)
        colorTheme = QAction('Toggle Red/ Purple Theme', self)
        about = QAction('About Tranquility MP', self)

        # Establish Context Menu actions
        self.playlistAdd = QAction('Add to Playlist', self)
        self.playlistDel = QAction('Remove from Playlist', self)
        self.delPlaylist = QAction('Delete Playlist', self)

        fileMenu.addAction(openFile)
        playlistMenu.addAction(createPlaylist)
        playlistMenu.addAction(savePlaylist)
        viewMenu.addAction(toggleTheme)
        viewMenu.addAction(colorTheme)
        helpMenu.addAction(about)

        openFile.triggered.connect(self.open_file)
        createPlaylist.triggered.connect(self.createPlaylist)
        savePlaylist.triggered.connect(self.savePlaylist)
        colorTheme.triggered.connect(self.toggleColor)
        toggleTheme.triggered.connect(self.toggleTheme)
        about.triggered.connect(self.about)
        self.playlistAdd.triggered.connect(self.open_file)
        self.playlistDel.triggered.connect(self.removeFromPlaylist)
        self.delPlaylist.triggered.connect(self.deletePlaylist)

        self.show()

    def establishLayout(self):
        cWid = QWidget()
        self.setCentralWidget(cWid)

        self.currentPlaylist = QListWidget()
        self.currentPlaylist.setFocusPolicy(Qt.NoFocus)
        self.currentPlaylist.itemDoubleClicked.connect(self.currentSelection)
        self.currentPlaylist.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.currentPlaylist.addAction(self.playlistAdd)
        self.currentPlaylist.addAction(self.playlistDel)

        self.playlistView = QListWidget()
        self.playlistView.adjustSize()
        self.playlistView.setMaximumWidth(100)
        self.playlistView.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.playlistView.addAction(self.delPlaylist)
        self.playlistView.itemDoubleClicked.connect(self.parsePlaylist)

        self.seekSlider = QSlider(Qt.Horizontal)
        self.currentTimeLabel = QLabel('00:00')
        self.totalTimeLabel = QLabel('00:00')
        self.seekSlider.setRange(0, self.mediaPlayer.duration() / 1000)
        self.seekSlider.sliderMoved.connect(self.seek)
        self.seekSlider.valueChanged.connect(self.mediaPlayer.setPosition)

        # Set up splitter layout to hold the display widgets
        displaySplitter = QSplitter()
        displaySplitter.addWidget(self.playlistView)
        displaySplitter.addWidget(self.currentPlaylist)

        # Set up layout to hold the splitter layout
        displayLayout = QHBoxLayout()
        displayLayout.addWidget(displaySplitter)

        # Set up layout for Playlist Controls
        controls = PlaylistControls()
        controls.setState(self.mediaPlayer.state())
        controls.setVolume(self.mediaPlayer.volume())
        controls.setMuted(self.mediaPlayer.isMuted())
        controls.play.connect(self.mediaPlayer.play)
        controls.pause.connect(self.mediaPlayer.pause)
        controls.stop.connect(self.mediaPlayer.stop)
        controls.next.connect(self.playlist.next)
        controls.previous.connect(self.previousMedia)
        controls.changeVolume.connect(self.mediaPlayer.setVolume)
        controls.muteVolume.connect(self.mediaPlayer.setMuted)
        controls.shuffle.connect(self.playlist.shuffle)
        controls.repeatAll.connect(self.setRepeatAll)
        controls.repeatOne.connect(self.setRepeatOne)

        self.mediaPlayer.stateChanged.connect(controls.setState)
        self.mediaPlayer.volumeChanged.connect(controls.setVolume)
        self.mediaPlayer.mutedChanged.connect(controls.setMuted)

        controlLayout = QHBoxLayout()
        controlLayout.addWidget(controls)

        # Set up layout for Seek controls
        seekLayout = QHBoxLayout()
        seekLayout.addWidget(self.currentTimeLabel)
        seekLayout.addWidget(self.seekSlider)
        seekLayout.addWidget(self.totalTimeLabel)

        mainLayout = QVBoxLayout()
        layoutHelp(mainLayout, (displayLayout, seekLayout, controlLayout))
        mainLayout.setSpacing(0)

        self.setLayout(mainLayout)
        cWid.setLayout(mainLayout)

        if not self.mediaPlayer.isAvailable():
            QMessageBox.warning(self, "Service not available")

            controls.setEnabled(False)
            self.currentPlaylist.setEnabled(False)

        self.metaDataChanged()
        self.statusBar()

    def open_file(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files",
                                                    "C:\\Users\\dchtk\\Music",
                                                    'All Files(*.*)')
        self.addToPlaylist(fileNames)

    def currentSelection(self):
        currentSelection = self.currentPlaylist.currentRow()
        self.playlist.setCurrentIndex(currentSelection)
        self.mediaPlayer.play()

    def removeFromPlaylist(self):
        selectedTrack = self.currentPlaylist.currentRow()
        self.playlist.setCurrentIndex(selectedTrack)
        self.currentPlaylist.takeItem(selectedTrack)
        self.playlist.removeMedia(selectedTrack)

    def deletePlaylist(self):
        selectedPlaylist = self.playlistView.currentRow()
        self.playlistView.takeItem(selectedPlaylist)

    def parsePlaylist(self, lines=None):
        path = "C:\\Users\dchtk\\Music\\Playlists"
        arr = os.listdir(path)
        for x in arr:
            xpath = os.path.join(path, x)
            if self.playlistView.selectedItems()[0].text() in xpath:
                item = xpath
                plFile = open(item, 'r')
                if plFile.mode == "r":
                    songs = plFile.read()
                    if self.currentPlaylist.count() > 0:
                        self.currentPlaylist.clear()
                        self.currentPlaylist.addItem(songs)
                    else:
                        self.currentPlaylist.addItem(songs)

    def about(self):
        QMessageBox.information(
            self, "About Tranquility MP",
            "Tranquility Media Player Version 1.0,\n\n"
            "Developed by: D. Chaitkin")