Exemplo n.º 1
0
class ListContainer(QGroupBox):
    def __init__(self, functions):
        super().__init__()
        self.functions = functions
        self.setTitle("Liste des sujets")
        mainLayout = QHBoxLayout()
        self.listWidget = QListWidget()
        self.listWidget.itemChanged.connect(self.hasChanged)
        mainLayout.addWidget(self.listWidget)
        mainLayout.addWidget(self.toolBar())
        self.setLayout(mainLayout)
    def toolBar(self):
        toolBar = QToolBar()
        toolBar.setOrientation(Qt.Vertical)
        toolBar.addAction("Sujet supplémentaire").triggered.connect(self.addItem)
        toolBar.addAction("Supprimer sujet").triggered.connect(self.removeItem)
        return toolBar
    def addItem(self):
        title = "Sujet {:d}".format(self.listWidget.count()+1)
        item = QListWidgetItem(title)
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self.listWidget.addItem(item)
        self.functions.addSubject(title)
    def removeItem(self):
        i = self.listWidget.currentRow()
        if i >= 0:
            self.listWidget.takeItem(i)
            self.functions.removeSubject(i)
    def hasChanged(self):
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).text() != self.functions.subjectsNames[i]:
                self.functions.changeSubject(i, self.listWidget.item(i).text())
    def sizeHint(self):
        return QSize(400, 150)
Exemplo n.º 2
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.pic_label = QLabel(self)
        self.pic_label.setPixmap(QPixmap('arrow.png'))

        self.listwidget_1 = QListWidget(self)  #实例化列表控件
        self.listwidget_2 = QListWidget(self)
        self.listwidget_1.doubleClicked.connect(
            lambda: self.change_func(self.listwidget_1))
        #双击列表控件时发出信号
        self.listwidget_2.doubleClicked.connect(
            lambda: self.change_func(self.listwidget_2))

        for i in range(6):
            text = 'Item {}'.format(i)
            self.item = QListWidgetItem(text)  #把字符串转化为QListWidgetItem项目对象
            self.listwidget_1.addItem(self.item)  #添加项目

        self.item_6 = QListWidgetItem('Item 6', self.listwidget_1)  # 实例化后直接添加

        self.listwidget_1.addItem(
            'Item 7')  #直接添加项目,不用QListWidgetItem对象,【功能可能不全】
        str_list = ['Item 9', 'Item 10']
        self.listwidget_1.addItems(str_list)  #添加项目-列表

        self.item_8 = QListWidgetItem('Item 8')
        self.listwidget_1.insertItem(8, self.item_8)  #插入项目。参数1:索引号,参数2:项目
        # self.listwidget_1.insertItem(8, 'Item 8')

        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.listwidget_1)
        self.h_layout.addWidget(self.pic_label)
        self.h_layout.addWidget(self.listwidget_2)
        self.setLayout(self.h_layout)

        self.listwidget_1.itemClicked.connect(self.d)  #单击列表控件时发出信号
        self.listwidget_1.currentItemChanged.connect(self.g)  #当前项目发生变化时发出信号
        self.listwidget_1.addItem('Item_11')

    def g(self):
        print('项目总数发生了改变')

    def d(self):
        print('你单击了列表控件')

    def change_func(self, listwidget):
        if listwidget == self.listwidget_1:
            item = QListWidgetItem(
                self.listwidget_1.currentItem())  #转化为QListWidgetItem对象
            # self.listwidget_1.currentItem()   返回当前项目。是个对象。<PyQt5.QtWidgets.QListWidgetItem object at 0x0000008425463A68>
            self.listwidget_2.addItem(item)  #添加项目。参数是QListWidgetItem对象
            print(self.listwidget_2.count())  #返回项目总数

        else:
            self.listwidget_2.takeItem(
                self.listwidget_2.currentRow())  #删除指定索引号的项目
            #self.listwidget_2.currentRow()    返回当前项目的行索引号
            print(self.listwidget_2.count())
Exemplo n.º 3
0
class MetricsWindowTab(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.name = self.tr("Metrics Window")

        self.inputTextLabel = QLabel(self.tr("Default text:"), self)
        self.inputTextList = QListWidget(self)
        self.inputTextList.setDragDropMode(QAbstractItemView.InternalMove)
        self.addItemButton = QPushButton(self)
        self.addItemButton.setIcon(icons.i_plus())
        self.addItemButton.clicked.connect(self.addItem)
        self.removeItemButton = QPushButton(self)
        self.removeItemButton.setIcon(icons.i_minus())
        self.removeItemButton.clicked.connect(self.removeItem)

        buttonsLayout = QHBoxLayout()
        buttonsLayout.addWidget(self.addItemButton)
        buttonsLayout.addWidget(self.removeItemButton)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        buttonsLayout.addWidget(spacer)

        layout = QVBoxLayout(self)
        layout.addWidget(self.inputTextLabel)
        layout.addWidget(self.inputTextList)
        layout.addLayout(buttonsLayout)
        self.setLayout(layout)

        self.readSettings()

    def addItem(self):
        item = QListWidgetItem(self.inputTextList)
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self.inputTextList.setCurrentItem(item)
        self.inputTextList.editItem(item)
        self.removeItemButton.setEnabled(True)

    def removeItem(self):
        i = self.inputTextList.currentRow()
        self.inputTextList.takeItem(i)
        if not self.inputTextList.count():
            self.removeItemButton.setEnabled(False)

    def readSettings(self):
        self.inputTextList.clear()
        entries = settings.metricsWindowComboBoxItems()
        for entry in entries:
            item = QListWidgetItem(entry, self.inputTextList)
            item.setFlags(item.flags() | Qt.ItemIsEditable)
        if not len(entries):
            self.removeItemButton.setEnabled(False)

    def writeSettings(self):
        entries = []
        for i in range(self.inputTextList.count()):
            item = self.inputTextList.item(i)
            entries.append(item.text())
        settings.setMetricsWindowComboBoxItems(entries)
Exemplo n.º 4
0
class GanttConfigure(QDialog):
    def __init__(self, sim, start, end):
        QDialog.__init__(self)
        #self.setCaption("Gantt configuration")
        self.layout = QVBoxLayout(self)

#        self._slider = QxtSpanSliderWidget(
#            sim.observe_window[0] // sim.cycles_per_ms,
#            min(sim.now(), sim.observe_window[1]) // sim.cycles_per_ms,
#            self)
        self._slider = QxtSpanSliderWidget(
            0,
            min(sim.now(), sim.duration) // sim.cycles_per_ms,
            self)
        self._slider.setSpan(start, end)
        self.layout.addWidget(self._slider)

        self._list_elements = QListWidget(self)
        for processor in sim.processors:
            item = QListWidgetItem(processor.name, self._list_elements)
            item.setData(Qt.UserRole, processor)
            self._list_elements.addItem(item)
        for task in sim.task_list:
            item = QListWidgetItem(task.name, self._list_elements)
            item.setData(Qt.UserRole, task)
            self._list_elements.addItem(item)
        #self._list_elements.setDragDropMode(QListWidget.InternalMove)
        for row in range(0, self._list_elements.count()):
            self._list_elements.item(row).setCheckState(Qt.Checked)
        self.layout.addWidget(self._list_elements)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)

    def get_start_date(self):
        return self._slider.lowerValue

    def get_end_date(self):
        return self._slider.upperValue

    def get_selected_items(self):
        res = []
        for row in range(0, self._list_elements.count()):
            if self._list_elements.item(row).checkState() == Qt.Checked:
                data = self._list_elements.item(row).data(Qt.UserRole)
                res.append(data)
        return res
Exemplo n.º 5
0
class AnaWidget(QWidget):
    """
        用于打开测试记录
    """
    def __init__(self, filename):
        super(AnaWidget, self).__init__()
        self.setWindowTitle("测试结果分析")

        self.MainLayout = QVBoxLayout()

        self.DirPath = filename.replace(".res", "")

        self.ResultList = QListWidget()
        self.ResultList.currentRowChanged.connect(self.setResLabel)
        self.ResultLabel = QLabel("结果图片")
        self.ResultLabel.resize(200, 200)

        self.TotalResLabel = QLabel("死亡x次   生成x个   错误x次")

        self.MainLayout.addWidget(self.ResultList)
        self.MainLayout.addWidget(self.TotalResLabel)
        self.MainLayout.addWidget(self.ResultLabel)

        f = open(filename)
        r = f.read()
        strlist = r.splitlines()

        sc = 0
        de = 0
        er = 0
        # 统计信息
        for s in strlist:
            if s.find("生成") >= 0: sc = sc + 1
            if s.find("死亡") >= 0: de = de + 1
            if s.find("!") >= 0: er = er + 1
            self.ResultList.addItem(s)
            if s.find("!") >= 0:
                self.ResultList.item(self.ResultList.count() -
                                     1).setBackground(QColor('red'))

        self.ResultList.setCurrentRow(self.ResultList.count() - 1)
        self.TotalResLabel.setText("死亡" + str(de) + "次   生成" + str(sc) +
                                   "个   错误" + str(er) + "次")

        self.setLayout(self.MainLayout)

    def setResLabel(self):
        """
            设置图片
        """
        if self.ResultList.currentRow() == -1:
            return
        self.ResultLabel.setPixmap(
            QPixmap(self.DirPath + str(self.ResultList.currentRow()) +
                    ".png").scaled(self.ResultLabel.width(),
                                   self.ResultLabel.width()))
Exemplo n.º 6
0
class Navigator(QWidget):
    selection_changed = pyqtSignal(int)

    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)

        # set up widgets
        self.btn_prev = QPushButton(QIcon('../icons/previous.png'), '')
        self.btn_next = QPushButton(QIcon('../icons/next.png'), '')
        self.chk_auto_jump = QCheckBox('Auto jump to new spectrum')
        self.file_list = QListWidget()

        # set up layout
        l1 = QHBoxLayout()
        for w in [self.btn_prev, self.btn_next]:
            l1.addWidget(w)
        l2 = QVBoxLayout()
        l2.addLayout(l1)
        l2.addWidget(self.file_list)
        l2.addWidget(self.chk_auto_jump)
        self.setLayout(l2)

        # set up connections
        self.btn_next.clicked.connect(self.next_item)
        self.btn_prev.clicked.connect(self.prev_item)
        self.file_list.currentRowChanged.connect(self.selection_changed)

    def update_file_list(self, flist):
        self.file_list.clear()
        for f in flist:
            self.file_list.addItem(f)
        self.file_list.setCurrentRow(0)

    @pyqtSlot(str)
    def new_file_in_dataset(self, filename):
        self.file_list.addItem(filename)
        if self.chk_auto_jump.isChecked():
            self.file_list.setCurrentRow(self.file_list.count() - 1)

    def next_item(self):
        i = self.file_list.currentRow() + 1
        if i >= self.file_list.count():
            self.file_list.setCurrentRow(0)
        else:
            self.file_list.setCurrentRow(i)

    def prev_item(self):
        i = self.file_list.currentRow() - 1
        if i < 0:
            self.file_list.setCurrentRow(self.file_list.count() - 1)
        else:
            self.file_list.setCurrentRow(i)

    def clear(self):
        self.file_list.clear()
Exemplo n.º 7
0
class GanttConfigure(QDialog):
    def __init__(self, sim, start, end):
        QDialog.__init__(self)
        #self.setCaption("Gantt configuration")
        self.layout = QVBoxLayout(self)

        #        self._slider = QxtSpanSliderWidget(
        #            sim.observe_window[0] // sim.cycles_per_ms,
        #            min(sim.now(), sim.observe_window[1]) // sim.cycles_per_ms,
        #            self)
        self._slider = QxtSpanSliderWidget(
            0,
            min(sim.now(), sim.duration) // sim.cycles_per_ms, self)
        self._slider.setSpan(start, end)
        self.layout.addWidget(self._slider)

        self._list_elements = QListWidget(self)
        for processor in sim.processors:
            item = QListWidgetItem(processor.name, self._list_elements)
            item.setData(Qt.UserRole, processor)
            self._list_elements.addItem(item)
        for task in sim.task_list:
            item = QListWidgetItem(task.name, self._list_elements)
            item.setData(Qt.UserRole, task)
            self._list_elements.addItem(item)
        #self._list_elements.setDragDropMode(QListWidget.InternalMove)
        for row in range(0, self._list_elements.count()):
            self._list_elements.item(row).setCheckState(Qt.Checked)
        self.layout.addWidget(self._list_elements)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)

    def get_start_date(self):
        return self._slider.lowerValue

    def get_end_date(self):
        return self._slider.upperValue

    def get_selected_items(self):
        res = []
        for row in range(0, self._list_elements.count()):
            if self._list_elements.item(row).checkState() == Qt.Checked:
                data = self._list_elements.item(row).data(Qt.UserRole)
                res.append(data)
        return res
Exemplo n.º 8
0
class MetricsWindowTab(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.name = self.tr("Metrics Window")

        self.inputTextLabel = QLabel(self.tr("Default text:"), self)
        self.inputTextList = QListWidget(self)
        self.inputTextList.setDragDropMode(QAbstractItemView.InternalMove)
        self.addItemButton = QPushButton("+", self)
        self.addItemButton.clicked.connect(self.addItem)
        self.removeItemButton = QPushButton("−", self)
        self.removeItemButton.clicked.connect(self.removeItem)

        layout = QGridLayout(self)
        l = 0
        layout.addWidget(self.inputTextLabel, l, 0, 1, 3)
        l += 1
        layout.addWidget(self.inputTextList, l, 0, 1, 3)
        l += 1
        layout.addWidget(self.addItemButton, l, 0)
        layout.addWidget(self.removeItemButton, l, 1)
        self.setLayout(layout)

        self.readSettings()

    def addItem(self):
        item = QListWidgetItem(self.inputTextList)
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self.inputTextList.setCurrentItem(item)
        self.inputTextList.editItem(item)
        self.removeItemButton.setEnabled(True)

    def removeItem(self):
        i = self.inputTextList.currentRow()
        self.inputTextList.takeItem(i)
        if not self.inputTextList.count():
            self.removeItemButton.setEnabled(False)

    def readSettings(self):
        self.inputTextList.clear()
        entries = settings.metricsWindowComboBoxItems()
        for entry in entries:
            item = QListWidgetItem(entry, self.inputTextList)
            item.setFlags(item.flags() | Qt.ItemIsEditable)
        if not len(entries):
            self.removeItemButton.setEnabled(False)

    def writeSettings(self):
        entries = []
        for i in range(self.inputTextList.count()):
            item = self.inputTextList.item(i)
            entries.append(item.text())
        settings.setMetricsWindowComboBoxItems(entries)
Exemplo n.º 9
0
def flush(list: QListWidget) -> None:
    for entry in [
            str(list.item(i).text()) for i in range(list.count())
            if list.item(i).checkState() == Qt.Checked
    ]:
        print(entry)
    sys.exit()
Exemplo n.º 10
0
def get_checked_items(list_widget: QListWidget) -> List[QListWidgetItem]:
    checked_items = []
    for i in range(list_widget.count()):
        item: QListWidgetItem = list_widget.item(i)
        if item.checkState() == Qt.Checked:
            checked_items.append(item)
    return checked_items
Exemplo n.º 11
0
class CheckListGui(Param):
    """A GUI for List-Parameters"""
    def __init__(self,
                 project,
                 param_name,
                 param_alias=None,
                 hint=None,
                 options=None,
                 default=None):
        super().__init__(project, param_name, param_alias, default)
        self.param_name = param_name
        self.options_mapping = options or {}
        self.param_value = dict()
        self.param_widget = QListWidget()
        if hint:
            self.param_widget.setToolTip(hint)
        self.param_widget.itemChanged.connect(self.get_param)
        self.read_param()
        self.set_param()
        self.save_param()
        self.init_v_layout()

    def set_param(self):
        self.param_widget.clear()
        if len(self.param_value) > 0:
            for name in self.param_value:
                if name in self.options_mapping:
                    list_item = QListWidgetItem(str(
                        self.options_mapping[name]))
                else:
                    list_item = QListWidgetItem(str(name))
                list_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                   | Qt.ItemIsUserCheckable)
                if self.param_value[name]:
                    list_item.setCheckState(Qt.Checked)
                else:
                    list_item.setCheckState(Qt.Unchecked)
                self.param_widget.addItem(list_item)

    def get_param(self):
        param_dict = {}
        for idx in range(self.param_widget.count()):
            item = self.param_widget.item(idx)
            if item.text() in self.options_mapping.values():
                # Get Dict-Key
                param_text = [
                    it for it in self.options_mapping.items()
                    if item.text() in it
                ][0][0]
            else:
                param_text = item.text()

            if item.checkState() == Qt.Checked:
                param_dict.update({param_text: 1})
            else:
                param_dict.update({param_text: 0})
        self.param_value = param_dict
        self.save_param()

        return self.param_value
Exemplo n.º 12
0
def get_items(list_widget: QtWidgets.QListWidget):
    """Returns the items in a QListWidget.
    """
    return [
        list_widget.item(i).data(QtCore.Qt.UserRole)
        for i in range(list_widget.count())
    ]
Exemplo n.º 13
0
class PickChannelsDialog(QDialog):
    def __init__(self, parent, channels, selected=[], title="Pick channels"):
        super().__init__(parent)
        self.setWindowTitle(title)
        self.initial_selection = selected
        vbox = QVBoxLayout(self)
        self.channels = QListWidget()
        self.channels.insertItems(0, channels)
        self.channels.setSelectionMode(QListWidget.ExtendedSelection)
        for i in range(self.channels.count()):
            if self.channels.item(i).data(0) in selected:
                self.channels.item(i).setSelected(True)
        vbox.addWidget(self.channels)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        vbox.addWidget(self.buttonbox)
        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)
        self.channels.itemSelectionChanged.connect(self.toggle_buttons)
        self.toggle_buttons()  # initialize OK button state

    @pyqtSlot()
    def toggle_buttons(self):
        """Toggle OK button.
        """
        selected = [item.data(0) for item in self.channels.selectedItems()]
        if selected != self.initial_selection:
            self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(True)
        else:
            self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)
Exemplo n.º 14
0
class PyQtWindow(QWidget):
    def __init__(self, action_send):
        super().__init__()
        self.action = action_send
        self.initUI()

    def initUI(self):
        grid = QGridLayout()

        self.list = QListWidget(self)
        self.list.addItem('Hello')
        grid.addWidget(self.list, 0, 0, 3, 4)

        self.user_input = QLineEdit()
        grid.addWidget(self.user_input, 3, 0, 1, 3)

        self.send_button = QPushButton()
        self.send_button.setText("Send")
        self.send_button.clicked.connect(self.button_clicked)
        grid.addWidget(self.send_button, 3, 3)

        self.setLayout(grid)
        self.setGeometry(100, 100, 400, 400)

    def button_clicked(self):
        text = self.user_input.text()
        self.user_input.clear()
        self.action(bytes(text, 'utf-8'))

    def add_input(self, value):
        self.list.insertItem(self.list.count(), value)
Exemplo n.º 15
0
    def _select(self, choices):
        if not choices:
            return []

        dialog = QDialog(mw)
        layout = QVBoxLayout()
        listWidget = QListWidget()
        listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)

        for c in choices:
            item = QListWidgetItem(c['text'])
            item.setData(Qt.UserRole, c['data'])
            listWidget.addItem(item)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Close
                                     | QDialogButtonBox.Save)
        buttonBox.accepted.connect(dialog.accept)
        buttonBox.rejected.connect(dialog.reject)
        buttonBox.setOrientation(Qt.Horizontal)

        layout.addWidget(listWidget)
        layout.addWidget(buttonBox)

        dialog.setLayout(layout)
        dialog.setWindowModality(Qt.WindowModal)
        dialog.resize(500, 500)
        choice = dialog.exec_()

        if choice == 1:
            return [
                listWidget.item(i).data(Qt.UserRole)
                for i in range(listWidget.count())
                if listWidget.item(i).isSelected()
            ]
        return []
Exemplo n.º 16
0
class EpochingDialog(QDialog):
    def __init__(self, parent, events, raw, title="Epoching..."):
        super().__init__(parent)
        self.setWindowTitle(title)
        selected = None
        event_labels = unique(events[:, 2]).astype(str)
        self.events = events
        grid = QGridLayout(self)
        grid.addWidget(QLabel("Choose Marker"), 1, 0, 1, 1)
        self.labels = QListWidget()
        self.labels.insertItems(0, event_labels)
        self.labels.setSelectionMode(QListWidget.ExtendedSelection)
        if selected is not None:
            for i in range(self.labels.count()):
                if self.labels.item(i).data(0) == selected:
                    self.labels.item(i).setSelected(True)
        grid.addWidget(self.labels, 1, 1, 1, 2)
        grid.addWidget(QLabel("Interval around event"), 2, 0, 1, 1)
        self.tmin = QLineEdit(self)
        self.tmax = QLineEdit(self)
        grid.addWidget(self.tmin, 2, 1, 1, 1)
        grid.addWidget(self.tmax, 2, 2, 1, 1)
        self.baseline = QCheckBox("&Baseline Correction")
        grid.addWidget(self.baseline, 3, 0, 1, 1)
        self.a = QLineEdit(self)
        self.b = QLineEdit(self)
        grid.addWidget(self.a, 3, 1, 1, 1)
        grid.addWidget(self.b, 3, 2, 1, 1)
        buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        buttonbox.accepted.connect(self.accept)
        buttonbox.rejected.connect(self.reject)
        grid.addWidget(buttonbox, 5, 2, 2, 2)
Exemplo n.º 17
0
    def __init__(self, datasets: QtWidgets.QListWidget, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.setWindowIcon(QIcon("../resources/model-add.png"))

        self.createModelButton.setDisabled(True)

        num_items = datasets.count()
        for i in range(num_items):
            item = datasets.item(i)
            widget = datasets.itemWidget(item).clone()

            new_item = QtWidgets.QListWidgetItem()
            new_item.setSizeHint(widget.sizeHint())
            self.datasetsChooseList.addItem(new_item)
            self.datasetsChooseList.setItemWidget(new_item, widget)

        self.infoStyle = 'QLabel { color: black; font: "Segoe UI"; font-size: 13px }'
        self.warningStyle = 'QLabel { color: black; font: italic "Segoe UI"; font-size: 13px }'

        # SIGNAL TO INFER PARAMS
        self.datasetsChooseList.itemDoubleClicked.connect(self.inferVocabSize)

        # CHANGED OUTPUT NAME
        self.outputModelName.textChanged.connect(self.checkModelOverwrite)
        self.outputModelName.textChanged.connect(self.enableButtonOnNameFilled)

        # COMMIT CREATE
        self.createModelButton.clicked.connect(self.onModelCreateClicked)
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Drag & Drop')

        # Даем разрешение на Drop
        self.setAcceptDrops(True)

        self.list_files = QListWidget()
        self.label_total_files = QLabel()

        model = QFileSystemModel()
        model.setRootPath(QDir.currentPath())
        model.setReadOnly(False)

        self.tree = QTreeView()
        self.tree.setModel(model)
        self.tree.setRootIndex(model.index(QDir.currentPath()))
        self.tree.setSelectionMode(QTreeView.SingleSelection)
        self.tree.setDragDropMode(QTreeView.InternalMove)

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.tree)
        main_layout.addWidget(QLabel('Перетащите файл:'))
        main_layout.addWidget(self.list_files)
        main_layout.addWidget(self.label_total_files)

        central_widget = QWidget()
        central_widget.setLayout(main_layout)

        self.setCentralWidget(central_widget)

        self._update_states()

    def _update_states(self):
        self.label_total_files.setText('Files: {}'.format(
            self.list_files.count()))

    def dragEnterEvent(self, event):
        # Тут выполняются проверки и дается (или нет) разрешение на Drop

        mime = event.mimeData()

        # Если перемещаются ссылки
        if mime.hasUrls():
            # Разрешаем
            event.acceptProposedAction()

    def dropEvent(self, event):
        # Обработка события Drop

        for url in event.mimeData().urls():
            file_name = url.toLocalFile()
            self.list_files.addItem(file_name)

        self._update_states()

        return super().dropEvent(event)
Exemplo n.º 19
0
def gen_items_in_list(list_widget: QListWidget):
    """
    list_widget 안의 모든 원소를 순서대로 반환하는 제너레이터입니다.
    메모리가 빡세다면 이 함수를 이용하면 됩니다.
    :parameter list_widget: 아이템을 순서대로 보고 싶은 QListWidget 객체입니다. 
    """
    for i in range(list_widget.count()):
        yield list_widget.item(i)
Exemplo n.º 20
0
class startupView(QWidget):
    addProject = pyqtSignal(str)
    openSavedProject = pyqtSignal(str)
    removeSavedProject = pyqtSignal(str)

    def __init__(self, global_config, file_manager):
        super().__init__()
        self.global_config = global_config
        self.fileManager = file_manager
        self.projectList = self.fileManager.getSavedProjects()
        self.newProjectWindow = None
        self.setupWidgets()
        self.connectSlots()

    def setupWidgets(self):
        self.list = QListWidget()
        self.list.addItems(self.projectList)
        self.layout = QVBoxLayout()
        self.bottomLayout = QHBoxLayout()

        self.buttons = {
            'open': QPushButton("Open Project"),
            'remove': QPushButton("Remove Project"),
            'new': QPushButton("New Project")
        }

        for name, button in self.buttons.items():
            self.bottomLayout.addWidget(button)

        self.layout.addWidget(self.list)
        self.layout.addLayout(self.bottomLayout)
        self.setLayout(self.layout)

    def connectSlots(self):
        self.buttons['open'].clicked.connect(self.openProject)
        self.buttons['remove'].clicked.connect(self.removeProject)
        self.buttons['new'].clicked.connect(self.newProject)

    def newProject(self):
        if self.newProjectWindow is None:
            self.newProjectWindow = newProjectWindow()
            self.newProjectWindow.cancel.connect(self.show)
            self.newProjectWindow.createProject.connect(
                lambda x: self.addProject.emit(x))
        self.hide()
        self.newProjectWindow.show()

    def removeProject(self):
        name = self.list.currentItem()
        index = self.list.currentRow()
        self.list.takeItem(index)
        self.removeSavedProject.emit(name.text())
        self.update()

    def openProject(self):
        if self.list.count():
            selected = self.list.currentItem().text()
            self.openSavedProject.emit(selected)
Exemplo n.º 21
0
def check_all(list_widget: QListWidget) -> None:
    check_state = Qt.Checked

    if is_all_checked(list_widget):
        check_state = Qt.Unchecked

    for i in range(list_widget.count()):
        item: QListWidgetItem = list_widget.item(i)
        item.setCheckState(check_state)
Exemplo n.º 22
0
class QueuedAnalysesFrame(QScrollArea):
    def __init__(self, parent: AnalysisSettingsDock):
        super().__init__()
        self.parent = parent
        self.listWidget = QListWidget()
        self.setWidget(self.listWidget)
        self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.listWidget.customContextMenuRequested.connect(
            self.showContextMenu)
        self.listWidget.setMinimumHeight(30)
        self.setWidgetResizable(True)
        self.listWidget.itemDoubleClicked.connect(self.displayItemSettings)
        self.listWidget.itemClicked.connect(self.highlightAssociatedCells)

    @property
    def analyses(self) -> List[AbstractRuntimeAnalysisSettings]:
        return [
            self.listWidget.item(i).settings
            for i in range(self.listWidget.count())
        ]

    def addAnalysis(self, settings: AbstractRuntimeAnalysisSettings):
        item = AnalysisListItem(
            settings, self.listWidget
        )  # the item is automatically added to the list here.

    def showContextMenu(self, point: QPoint):
        menu = QMenu("ContextMenu", self)
        deleteAction = QAction("Delete", self)
        deleteAction.triggered.connect(self.deleteSelected)
        menu.addAction(deleteAction)
        deleteAllAction = QAction("Delete All", self)
        deleteAllAction.triggered.connect(self.deleteAll)
        menu.addAction(deleteAllAction)
        menu.exec(self.mapToGlobal(point))

    def deleteSelected(self):
        for i in self.listWidget.selectedItems():
            self.listWidget.takeItem(self.listWidget.row(i))

    def deleteAll(self):
        self.listWidget.clear()

    def highlightAssociatedCells(self, item: AnalysisListItem):
        # Highlight relevant cells
        cellAcq = [
            cell.acquisitionDirectory for cell in item.settings.cellMetadata
        ]
        refAcq = item.settings.referenceMetadata.acquisitionDirectory
        self.parent._selector.setHighlightedCells(cellAcq)
        self.parent._selector.setHighlightedReference(refAcq)

    def displayItemSettings(self, item: AnalysisListItem):
        # Open a dialog
        message = QMessageBox.information(
            self, item.settings.analysisName,
            item.settings.settings.toJsonString())
Exemplo n.º 23
0
class LayerActionsDialog(QDialog):

    def __init__(self, currentGlyph, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Layer actions…"))
        self._workableLayers = []
        for layer in currentGlyph.layerSet:
            if layer != currentGlyph.layer:
                self._workableLayers.append(layer)

        layout = QGridLayout(self)

        copyBox = QRadioButton(self.tr("Copy"), self)
        moveBox = QRadioButton(self.tr("Move"), self)
        swapBox = QRadioButton(self.tr("Swap"), self)
        self.otherCheckBoxes = (moveBox, swapBox)
        copyBox.setChecked(True)

        self.layersList = QListWidget(self)
        self.layersList.addItems(
            layer.name for layer in self._workableLayers)
        if self.layersList.count():
            self.layersList.setCurrentRow(0)
        self.layersList.itemDoubleClicked.connect(self.accept)

        buttonBox = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        l = 0
        layout.addWidget(copyBox, l, 0, 1, 2)
        layout.addWidget(moveBox, l, 2, 1, 2)
        layout.addWidget(swapBox, l, 4, 1, 2)
        l += 1
        layout.addWidget(self.layersList, l, 0, 1, 6)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 6)
        self.setLayout(layout)

    @classmethod
    def getLayerAndAction(cls, parent, currentGlyph):
        dialog = cls(currentGlyph, parent)
        result = dialog.exec_()
        currentItem = dialog.layersList.currentItem()
        newLayer = None
        if currentItem is not None:
            newLayerName = currentItem.text()
            for layer in dialog._workableLayers:
                if layer.name == newLayerName:
                    newLayer = layer
        action = "Copy"
        for checkBox in dialog.otherCheckBoxes:
            if checkBox.isChecked():
                action = checkBox.text()
        return (newLayer, action, result)
Exemplo n.º 24
0
class LayerActionsDialog(QDialog):

    def __init__(self, currentGlyph, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Layer actions…"))
        self._workableLayers = []
        for layer in currentGlyph.layerSet:
            if layer != currentGlyph.layer:
                self._workableLayers.append(layer)

        copyBox = QRadioButton(self.tr("Copy"), self)
        moveBox = QRadioButton(self.tr("Move"), self)
        swapBox = QRadioButton(self.tr("Swap"), self)
        self.otherCheckBoxes = (moveBox, swapBox)
        copyBox.setChecked(True)

        self.layersList = QListWidget(self)
        self.layersList.addItems(
            layer.name for layer in self._workableLayers)
        if self.layersList.count():
            self.layersList.setCurrentRow(0)
        self.layersList.itemDoubleClicked.connect(self.accept)

        buttonBox = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QGridLayout(self)
        l = 0
        layout.addWidget(copyBox, l, 0, 1, 2)
        layout.addWidget(moveBox, l, 2, 1, 2)
        layout.addWidget(swapBox, l, 4, 1, 2)
        l += 1
        layout.addWidget(self.layersList, l, 0, 1, 6)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 6)
        self.setLayout(layout)

    @classmethod
    def getLayerAndAction(cls, parent, currentGlyph):
        dialog = cls(currentGlyph, parent)
        result = dialog.exec_()
        currentItem = dialog.layersList.currentItem()
        newLayer = None
        if currentItem is not None:
            newLayerName = currentItem.text()
            for layer in dialog._workableLayers:
                if layer.name == newLayerName:
                    newLayer = layer
        action = "Copy"
        for checkBox in dialog.otherCheckBoxes:
            if checkBox.isChecked():
                action = checkBox.text()
        return (newLayer, action, result)
 def click_on_list_widget_entry(i_list_widget: QtWidgets.QListWidget,
                                i_text_for_entry_to_click: str):
     # -this assumes that the list widget has a custom qlwi set for each of the rows
     for i in range(0, i_list_widget.count()):
         qlwi = i_list_widget.item(i)
         custom_qll = i_list_widget.itemWidget(qlwi)
         if custom_qll.text() == i_text_for_entry_to_click:
             QtTest.QTest.mouseClick(custom_qll, QtCore.Qt.LeftButton)
             return True
     return False
Exemplo n.º 26
0
class MessageBoxWithList(QMessageBox):
    def __init__(self, parent = None):
        super().__init__(parent)
        self._listWidget = QListWidget(self)
        self.layout().addWidget(self._listWidget, 3, 1)
        self._listWidget.hide()

    def addToList(self, val):
        self._listWidget.addItem(val)

    def listCount(self):
        return self._listWidget.count()

    def exec(self):
        if self._listWidget.count() > 0:
            self._listWidget.show()
        else:
            self._listWidget.hide()
        super().exec()
Exemplo n.º 27
0
 def select(self, list_widget: QListWidget, type_: str):
     for i in range(list_widget.count()):
         item = list_widget.item(i)
         if type_ == 'all':
             item.setCheckState(Qt.Checked)
         elif type_ == 'none':
             item.setCheckState(Qt.Unchecked)
         elif type_ == 'invert':
             item.setCheckState(Qt.Checked if item.checkState() ==
                                Qt.Unchecked else Qt.Unchecked)
Exemplo n.º 28
0
 def _add_line(self,listWidget:QtWidgets.QListWidget,stackedWidget,lines:list,line=None):
     index = listWidget.count()
     if line is None:
         line = Line(name='新建线路')
     item = QtWidgets.QListWidgetItem(f"{index+1} {line.name}")
     lines.append(line)
     widget = LineWidget(line)
     stackedWidget.addWidget(widget)
     listWidget.addItem(item)
     listWidget.setCurrentRow(index)  #这一步切换的时候会自动初始化数据。如果提前初始化,会造成重复。
Exemplo n.º 29
0
class PatchesPage(QtWidgets.QWizardPage):
    def __init__(self, Wizard, parent=None):
        super(PatchesPage, self).__init__(parent)

        self.base = Wizard.base

        self.setTitle(self.tr("Patches page"))
        self.setSubTitle(self.tr("Select patches"))

        self.addButton = QPushButton("+")
        self.removeButton = QPushButton("-")
        patchesLabel = QLabel("Patches")
        self.listPatches = QListWidget()
        self.addButton.setMaximumWidth(68)
        self.addButton.setMaximumHeight(60)
        self.addButton.clicked.connect(self.openPatchesPageFileDialog)
        self.removeButton.setMaximumWidth(68)
        self.removeButton.setMaximumHeight(60)
        self.removeButton.clicked.connect(self.removeItemFromListWidget)

        grid = QGridLayout()
        grid.addWidget(patchesLabel, 0, 0)
        grid.addWidget(
            self.addButton,
            0,
            1,
        )
        grid.addWidget(self.removeButton, 0, 2)
        grid.addWidget(self.listPatches, 1, 0, 1, 0)

        self.setLayout(grid)

    def removeItemFromListWidget(self):
        self.item = self.listPatches.takeItem(self.listPatches.currentRow())
        self.item = None

    def openPatchesPageFileDialog(self):
        brows = QFileDialog()
        self.getPath = brows.getOpenFileName(self, "Choose patches", "/home",
                                             "All files (*)")
        self.newPath = self.getPath[0]
        self.listPatches.addItem(self.newPath)

    def validatePage(self):
        self.itemsCount = self.listPatches.count()
        self.pathes = []
        for i in range(0, self.itemsCount):
            self.pathes.append(self.listPatches.item(i).text())

        self.base.apply_patches(self.pathes)
        self.base.run_patched_sources_analysis()
        return True

    def nextId(self):
        return Wizard.PageScripts
Exemplo n.º 30
0
class PickChannelsDialog(QDialog):
    """
    Defines the Dialog for selected channels for different cases (picked, excluded, filter...)
    """

    signal_paramChanged = pyqtSignal(list)

    # ----------------------------------------------------------------------
    def __init__(self, channels, selected=[], title="Pick channels"):
        """
        Constructor.
        """
        super().__init__()

        self.setWindowTitle(title)
        self.selection = selected
        vbox = QVBoxLayout(self)
        self.channels = QListWidget()
        self.channels.insertItems(0, channels)
        self.channels.setSelectionMode(QListWidget.ExtendedSelection)

        for i in range(self.channels.count()):
            if self.channels.item(i).data(0) in selected:
                self.channels.item(i).setSelected(True)

        vbox.addWidget(self.channels)
        self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        vbox.addWidget(self.buttonbox)

        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)
        self.buttonbox.accepted.connect(self.on_modify)

        self.channels.itemSelectionChanged.connect(self.toggle_buttons)
        self.toggle_buttons()  # initialize OK button state

    @pyqtSlot()
    # ----------------------------------------------------------------------
    def toggle_buttons(self):
        """
        Toggle OK button.
        """
        selected = [item.data(0) for item in self.channels.selectedItems()]

        if selected != self.selection:
            self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(True)
            self.selected = selected
        else:
            self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)

    # ----------------------------------------------------------------------
    def on_modify(self):
        """"""
        self.signal_paramChanged[list].emit(self.selected)
Exemplo n.º 31
0
class export_GUI(QWidget):

    # Displayed when citations should be exported

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

        # Setting up the side GUI
        self.setFixedSize(wh[0], wh[1])
        self.setWindowTitle(TITLE_EXPORT)
        self.setWindowIcon(QIcon(LOGO_PATH))

        grid = QGridLayout()
        grid.setSpacing(30)
        self.exp_cit_widget = QListWidget()

        # Initialize buttons
        self.copy_button = QPushButton('Copy')
        self.export_button = QPushButton('Export to BibTex')
        self.push_right = QPushButton("->")
        self.push_left = QPushButton("<-")

        # Setting the widgets up on the GUI
        grid.addWidget(self.exp_cit_widget, 0, 1, 4, 2)
        grid.addWidget(self.push_right, 1, 0)
        grid.addWidget(self.push_left, 2, 0)
        grid.addWidget(self.copy_button, 4, 1)
        grid.addWidget(self.export_button, 4, 2)

        grid.setColumnStretch(1, 2)
        grid.setColumnStretch(2, 2)

        self.setLayout(grid)
        self.show()

    def relocate(self, x, y):
        """Relocates the export GUI to the coordinate x and y.
        :param x: horizontal coordinate
        :param y: vertical coordinate
        :return: Nothing
        """
        self.move(x, y)

    def list_of_indices(self) -> list:
        """Generates a list of all indices of the articles that were selected to be exported.
        :return: List of all indices of the articles that were selected to be exported.
        """
        return [self.exp_cit_widget.item(i).text()[0]
                for i in range(self.exp_cit_widget.count())]

    def get_savefile_dialog(self) -> str:
        """Opens a file dialog window to determine the directory the BibTex file is saved in.
        :return: Path of the BibTex file as string
        """
        return QFileDialog.getSaveFileName(self, "Save articles in BibTex")[0]
Exemplo n.º 32
0
Arquivo: v9.py Projeto: PJweng/PyQt5_v
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.pic_label = QLabel(self)  # 1
        self.pic_label.setPixmap(QPixmap('arrow.png'))

        self.listwidget_1 = QListWidget(self)  # 2
        self.listwidget_2 = QListWidget(self)
        self.listwidget_1.doubleClicked.connect(
            lambda: self.change_func(self.listwidget_1))
        self.listwidget_2.doubleClicked.connect(
            lambda: self.change_func(self.listwidget_2))

        for i in range(6):  # 3
            text = 'Item {}'.format(i)
            self.item = QListWidgetItem(text)
            self.listwidget_1.addItem(self.item)

        self.item_6 = QListWidgetItem('Item 6', self.listwidget_1)  # 4

        self.listwidget_1.addItem('Item 7')  # 5
        str_list = ['Item 9', 'Item 10']
        self.listwidget_1.addItems(str_list)

        self.item_8 = QListWidgetItem('Item 8')  # 6
        self.listwidget_1.insertItem(8, self.item_8)
        # self.listwidget_1.insertItem(8, 'Item 8')

        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.listwidget_1)
        self.h_layout.addWidget(self.pic_label)
        self.h_layout.addWidget(self.listwidget_2)
        self.setLayout(self.h_layout)

    def change_func(self, listwidget):  # 7
        if listwidget == self.listwidget_1:
            item = QListWidgetItem(self.listwidget_1.currentItem())
            self.listwidget_2.addItem(item)
            print(self.listwidget_2.count())
        else:
            self.listwidget_2.takeItem(self.listwidget_2.currentRow())
            print(self.listwidget_2.count())
Exemplo n.º 33
0
class itemList():
    def __init__(self):
        self.add_btn = QPushButton('Add ID')
        self.remove_btn = QPushButton('Remove Selection')
        self.item_input = QLineEdit()
        self.list = QListWidget()
        settings = QSettings('Bobcat Engineering', 'Treadmill')
        try:
            self.list.addItems(settings.value('Animal List'))
        except:
            pass

        self.groupbox = QGroupBox('Animal IDs')
        self.layout = QGridLayout()
        self.layout.addWidget(self.item_input, 0, 0)
        self.layout.addWidget(self.add_btn, 0, 1)
        self.layout.addWidget(self.list, 1, 0, 1, 2)
        self.layout.addWidget(self.remove_btn, 2, 0, 1, 2)
        self.groupbox.setLayout(self.layout)

        self.add_btn.clicked.connect(self.addItem)
        self.item_input.returnPressed.connect(self.addItem)
        self.remove_btn.clicked.connect(self.removeItem)

    def addItem(self):
        itemList = self.getListOfItems()
        newItem = self.item_input.text()
        if newItem != '' and newItem not in itemList:
            self.list.addItem(self.item_input.text())
        self.list.sortItems()
        self.item_input.clear()

    def removeItem(self):
        if self.list.count() > 0:
            self.list.takeItem(self.list.currentRow())

    def getListOfItems(self):
        tempList = []
        for i in range(self.list.count()):
            tempList.append(self.list.item(i).text())
        return tempList
Exemplo n.º 34
0
Arquivo: wizard.py Projeto: khuno/rpg
class PatchesPage(QtWidgets.QWizardPage):
    def __init__(self, Wizard, parent=None):
        super(PatchesPage, self).__init__(parent)

        self.base = Wizard.base

        self.setTitle(self.tr("Patches page"))
        self.setSubTitle(self.tr("Select patches"))

        self.addButton = QPushButton("+")
        self.removeButton = QPushButton("-")
        patchesLabel = QLabel("Patches")
        self.listPatches = QListWidget()
        self.addButton.setMaximumWidth(68)
        self.addButton.setMaximumHeight(60)
        self.addButton.clicked.connect(self.openPatchesPageFileDialog)
        self.removeButton.setMaximumWidth(68)
        self.removeButton.setMaximumHeight(60)
        self.removeButton.clicked.connect(self.removeItemFromListWidget)

        grid = QGridLayout()
        grid.addWidget(patchesLabel, 0, 0)
        grid.addWidget(self.addButton, 0, 1,)
        grid.addWidget(self.removeButton, 0, 2)
        grid.addWidget(self.listPatches, 1, 0, 1, 0)

        self.setLayout(grid)

    def removeItemFromListWidget(self):
        self.item = self.listPatches.takeItem(self.listPatches.currentRow())
        self.item = None

    def openPatchesPageFileDialog(self):
        brows = QFileDialog()
        self.getPath = brows.getOpenFileName(self,
                                             "Choose patches",
                                             "/home",
                                             "All files (*)")
        self.newPath = self.getPath[0]
        self.listPatches.addItem(self.newPath)

    def validatePage(self):
        self.itemsCount = self.listPatches.count()
        self.pathes = []
        for i in range(0, self.itemsCount):
            self.pathes.append(self.listPatches.item(i).text())

        self.base.apply_patches(self.pathes)
        self.base.run_patched_sources_analysis()
        return True

    def nextId(self):
        return Wizard.PageScripts
Exemplo n.º 35
0
class ShoppingList(QWidget):
    def __init__(self):
        super().__init__()

        self.grid = QGridLayout()
        self.grid.setSpacing(15)

        self.recipe_list_label = QLabel('Current shopping list:')
        self.list_of_recipes = QListWidget()
        self.list_of_recipes.setMaximumWidth(300)
        #self.list_of_recipes.setSelectionMode(QAbstractItemView.MultiSelection)

        self.remove_button = QPushButton('Remove')
        self.remove_button.setMaximumWidth(120)
        self.remove_button.clicked.connect(lambda: self.remove_item())
        self.remove_button.setStatusTip('Remove Selected Recipe(s).')

        self.email_list_button = QPushButton('Email Shopping List')
        self.email_list_button.setMaximumWidth(120)
        self.email_list_button.clicked.connect(lambda: self.email_shopping_list())
        self.email_list_button.setStatusTip('Email Ingredient List.')

        self.grid.addWidget(self.recipe_list_label, 0, 0)
        self.grid.addWidget(self.list_of_recipes, 1, 0, 8, 1)
        self.grid.addWidget(self.remove_button, 1, 1)
        self.grid.addWidget(self.email_list_button, 2, 1)

        self.setLayout(self.grid)

    def add_recipe(self, list_item):
        self.list_of_recipes.addItem(list_item)

    def remove_item(self):
        selected_items = self.list_of_recipes.selectedItems()
        for item in selected_items:
            self.list_of_recipes.takeItem(self.list_of_recipes.row(item))

    def email_shopping_list(self):
        shopping_items = []
        for pos in range(self.list_of_recipes.count()):
            shopping_items.append(self.list_of_recipes.item(pos).text())

        email_body = ''

        for name in shopping_items:
            recipe_title, recipe_ingredients, recipe_instructions = SQL_reader.recipe_data(name)
            email_body += '\n-- {}\n\n- Ingredients:\n'.format(name)

            for ingredient in recipe_ingredients:
                email_body += ('    {}\n'.format(ingredient))

        emailBot.emailMe(email_body)
Exemplo n.º 36
0
class JavaScriptExceptionsPanel(SettingsPanel):
    def __init__(self, parent=None):
        super(JavaScriptExceptionsPanel, self).__init__(parent)

        domainEntryRow = custom_widgets.LineEditRow(tr("Add domain:"), self)
        self.domainEntry = domainEntryRow.lineEdit
        self.domainEntry.returnPressed.connect(self.addDomain)
        self.layout().addWidget(domainEntryRow)

        self.addDomainButton = QPushButton(tr("Add"))
        self.addDomainButton.clicked.connect(self.addDomain)
        domainEntryRow.layout().addWidget(self.addDomainButton)

        self.domainList = QListWidget(self)
        self.layout().addWidget(self.domainList)

        self.removeDomainButton = QPushButton(tr("Remove"))
        self.removeDomainButton.clicked.connect(lambda: self.removeDomain(True))
        self.layout().addWidget(self.removeDomainButton)

        self.removeAction = QAction(self)
        self.removeAction.setShortcut("Del")
        self.removeAction.triggered.connect(self.removeDomain)
        self.addAction(self.removeAction)

    def removeDomain(self, forceFocus=False):
        if self.domainList.hasFocus() or forceFocus:
            self.domainList.takeItem(self.domainList.row(self.domainList.currentItem()))

    def addDomain(self):
        self.domainList.addItem(self.domainEntry.text())
        self.domainEntry.clear()

    def loadSettings(self):
        settings.js_exceptions = settings.setting_to_list("content/JavaScriptExceptions")
        self.domainList.clear()
        for f in settings.js_exceptions:
            self.domainList.addItem(f)

    def saveSettings(self):
        settings.js_exceptions = [self.domainList.item(f).text() for f in range(0, self.domainList.count())]
        settings.settings.setValue("content/JavaScriptExceptions", settings.js_exceptions)
        settings.settings.sync()
Exemplo n.º 37
0
class GrubList(QDialog):
    """Classe représentant la liste des répertoires GRUB"""
    
    scanner = Scanner("/", "*/grub/grub.cfg")
    newCurrentItem = pyqtSignal(str)
    
    def __init__(self, parent=None, text="Choisissez un répertoire GRUB", allowNone=True):
        QDialog.__init__(self, parent)
        
        # Création des éléments
        # Labels
        label = QLabel(text)
        label.setAlignment(Qt.AlignHCenter)
        self.scanText = QLabel("No scan running")
        self.scanText.setAlignment(Qt.AlignHCenter)
        # List View
        self.grub_list = QListWidget()
        self.grub_list.setSelectionMode(QAbstractItemView.SingleSelection)
        # Buttons
        self.scanButton = QPushButton("Scanner")
        self.add = QPushButton("Ajouter")
        self.scanButton.clicked.connect(self.scan)
        self.add.clicked.connect(self.openSelectionDialog)
        self.scanButton.setToolTip("Cette opération peut être <b>très</b> longue !")
        if allowNone:
            buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
            buttonBox.rejected.connect(self.reject)
        else:
            buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.accept)
        # Progressbar
        self.progressbar = QProgressBar()
        self.progressbar.setEnabled(False)
        
        # Création des Layouts
        # Horizontal
        hbox = QHBoxLayout()
        hbox.addWidget(self.scanButton)
        hbox.addWidget(self.add)
        # Vertical
        vbox = QVBoxLayout()
        vbox.addWidget(label)
        vbox.addWidget(self.grub_list)
        vbox.addLayout(hbox)
        vbox.addWidget(self.scanText)
        vbox.addWidget(self.progressbar)
        vbox.addWidget(buttonBox)
        
        # Affichage de l'interface
        self.setLayout(vbox)
        
        #Signals
        self.scanner.found_rep.connect(self.add_items)
        self.scanner.started.connect(self._scan_started)
        self.scanner.finished.connect(self._scan_finished)
        self.scanner.max_changed.connect(self.progressbar.setMaximum)
        self.scanner.value_changed.connect(self.progressbar.setValue)
        self.scanner.dir_scanned.connect(self._setScanText)
        
        # Ajout de /boot/grub s'il existe
        if path.Path("/boot/grub/grub.cfg").exists():
            self.add_item("/boot/grub")
    
    def selectGrubRep(self):
        self.setModal(True)
        result = self.exec_()
        if result == QDialog.Accepted:
            grubRep = self.getGrubRep()
            return grubRep
        else:
            return False
    
    def scan(self):
        warning = QMessageBox(self)
        msg =  ("Cette opération peut être très longue.\n"
                "Le logiciel va analyser toute votre arborescence de fichier "
                "pour chercher un éventuel dossier contenant la configuration de GRUB.")
        warning.setText(msg)
        warning.setInformativeText("Êtes-vous sûr de vouloir continuer ?")
        warning.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        warning.setDefaultButton(QMessageBox.No)
        warning.setWindowTitle("Attention")
        answer = warning.exec_()
        if answer == QMessageBox.Yes:
            self.scanner.start()
    
    def openSelectionDialog(self):
        dir = QFileDialog.getExistingDirectory(self,
                                               "Sélectionner un répertoire GRUB",
                                               expanduser('~'))
        if (path.Path(dir) / "grub.cfg").exists():
            self.add_item(dir)
        elif dir:
            error = QMessageBox(self)
            msg = "{} n'est pas un répertoire GRUB valide !".format(dir)
            error.setText(msg)
            error.setWindowTitle("Répertoire non valide")
            error.exec_()
    
    def getGrubRep(self):
        dir = self.grub_list.selectedItems()
        try:
            dir = dir[0].text()
        except IndexError:
            return False
        else:
            return dir
    
    @pyqtSlot(list)
    def add_items(self, items):
        for item in items:
            self.add_item(item)
        self.grub_list.setCurrentRow(0)
    
    @pyqtSlot(str)
    def add_item(self, dir):
        item = None
        for i in range(self.grub_list.count()):
            if self.grub_list.item(i).text() == dir:
                item = self.grub_list.item(i)
        if not item:
            item = QListWidgetItem(dir, self.grub_list)
        self.grub_list.setCurrentItem(item)
    
    @pyqtSlot()
    def _scan_started(self):
        self.progressbar.setEnabled(True)
        self.progressbar.setMinimum(0)
        self.scanButton.setEnabled(False)
        self.add.setEnabled(False)
    
    @pyqtSlot()
    def _scan_finished(self):
        self.progressbar.reset()
        self.progressbar.setEnabled(False)
        self.scanText.setText("No scan running")
        self.scanButton.setEnabled(True)
        self.add.setEnabled(True)
    
    @pyqtSlot(str)
    def _setScanText(self, text):
        self.scanText.setText("Scanning {}...".format(text))
Exemplo n.º 38
0
class Form(QWidget):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
 
        # Set up the first list (elements that can be used)
        elements = QListWidget()
        elements.viewport().setAcceptDrops(True)
        elements.setDragEnabled(True)
        elements.setDefaultDropAction(Qt.MoveAction)
        elements.setSelectionMode(QAbstractItemView.ExtendedSelection)
        elements.addItem(u"Last Name")
        elements.addItem(u"First Name")
        elements.addItem(u"Middle Initial")
        elements.addItem(u"Full Name")
        elements.addItem(u"DMIS ID")
        elements.addItem(u"SPIN Number")
        elements.addItem(u"SSN Prefix")
        elements.addItem(u"Social Security Number")
        elements.addItem(u"Date of Birth")
        elements.addItem(u"Gender")
        elements.addItem(u"Accession")
        elements.addItem(u"Isolation Date")
        elements.addItem(u"Culture Type")
        elements.addItem(u"Source")
        elements.addItem(u"Location Type")
        elements.addItem(u"Location")
        elements.addItem(u"Isolate Number")
        elements.addItem(u"Organism Name")
        elements.addItem(u"Alternate Organism Name")
        elements.addItem(u"Equipment")
        elements.addItem(u"Drug Info")
        elements.addItem(u"ESBL")
        elements.addItem(u"AMPC")


        # Set up the second list (elements to generate a config file from)
        self.selected_elements = QListWidget()
        self.selected_elements.viewport().setAcceptDrops(True)
        self.selected_elements.setDragEnabled(True)
        self.selected_elements.setDefaultDropAction(Qt.MoveAction)
        self.selected_elements.setSelectionMode(QAbstractItemView.ExtendedSelection)

        ok_button = QPushButton(u"OK")
        cancel_button = QPushButton(u"Cancel")
        about_button = QPushButton(u"About")
        insert_blank_line_button = QPushButton(u"Insert blank line")
        drug_validator = QIntValidator(1, 999)
        self.drugs = QLineEdit("1")
        self.drugs.setValidator(drug_validator)
        drugs_label = QLabel("Number of drugs per line")
        self.drugformat = QLineEdit("MIC,Call")
        drugformat_label = QLabel("Format of the drug information")
        self.date = QLineEdit("MM/dd/yyyy")
        date_label = QLabel("Date format")
        self.machine = QLineEdit("Machine name")
        machine_label = QLabel("Machine the file is from")
        buttons = QHBoxLayout()

        ok_button.clicked.connect(self.export_parser)
        cancel_button.clicked.connect(self.close_program)
        about_button.clicked.connect(self.about)
        insert_blank_line_button.clicked.connect(self.insert_blank_line)
        self.drugs.setMaxLength(3)

        buttons.addWidget(ok_button)
        buttons.addWidget(cancel_button)
        buttons.addWidget(about_button)
        buttons.addWidget(insert_blank_line_button)
 
        mainLayout = QGridLayout()
        mainLayout.addWidget(elements, 0, 0)
        mainLayout.addWidget(self.selected_elements, 0, 1)
        mainLayout.addLayout(buttons, 1, 0)
        mainLayout.addWidget(self.drugs, 2, 0)
        mainLayout.addWidget(drugs_label, 2, 1)
        mainLayout.addWidget(self.drugformat, 3, 0)
        mainLayout.addWidget(drugformat_label, 3, 1)
        mainLayout.addWidget(self.date, 4, 0)
        mainLayout.addWidget(date_label, 4, 1)
        mainLayout.addWidget(self.machine, 5, 0)
        mainLayout.addWidget(machine_label, 5, 1)
 
        self.setLayout(mainLayout)
        self.setWindowTitle(u"RevealerParserWizard")
        
    def export_parser(self):
        u'''
        Extract the text of the elements in selected_elements, then pass them
        to write_output so they can be fully converted and written to a parser
        file.
        '''
        extracted_elements = []
        element_num = self.selected_elements.count()
        if element_num < 1:
            no_entries = QMessageBox()
            no_entries.setIcon(QMessageBox.Warning)
            no_entries.setText(u"No elements selected!")
            no_entries.exec_()
            return
        for i in xrange(0, element_num):
            extracted_elements.append(self.selected_elements.item(i).text() + 1)
        
        # Act like a clown and get knocked down
        if int(self.drugs.text()) < 1:
            too_small = QMessageBox()
            too_small.setIcon(QMessageBox.Warning)
            too_small.setText(u"'Drugs per line' must be between 1 and 999")
            too_small.exec_()
            return
        else:
            extracted_elements.append("Drugs per line" + '\t' + self.drugs.text())
            
        if (len(self.drugformat.text()) < 1):
            too_small = QMessageBox()
            too_small.setIcon(QMessageBox.Warning)
            too_small.setText(u"'Drug Info Format' must not be empty")
            too_small.exec_()
            return
        else:
            extracted_elements.append("Drug Info Format" + '\t' + self.drugformat.text())

        extracted_elements.append("Date Format" + '\t' + self.date.text())
            
        
        if os.path.isfile(u"my_parser.txt"):
            output_exists = QMessageBox()
            output_exists.setIcon(QMessageBox.Warning)
            output_exists.setText(u"my_parser.txt already exists! Overwrite?")
            output_exists.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            overwrite = output_exists.exec_()
            if overwrite == QMessageBox.Yes:
                with open(u"my_parser.txt", u'w') as output:
                    self.write_output(output, extracted_elements)
                    return
            else:
                sys.exit()
        else:
            with open(u"my_parser.txt", u'w') as output:
                self.write_output(output, extracted_elements)
                return
            
    def write_output(self, output, elements):
        u'''
        Given a List of strings, convert them into an MDRevealer custom parser
        file and write them to my_parser.txt.
        '''
        i = 0
        for e in elements:
            if not "Drugs per" in e:
                output.write(e + u'\t' + unicode(i) + u'\n')
            else:
                output.write(e + u'\n')
            i += 1
        success = QMessageBox()
        success.setText(u"my_parser.txt written successfully.")
        success.exec_()
        sys.exit()
                
    
    def close_program(self):
        u'''
        Close the program.
        '''
        sys.exit()
        
    def about(self):
        u'''
        Provide information about the program in a QMessageBox.
        '''
        QMessageBox.information(self, u"About RevealerParserWizard", u"RevealerParserWizard 1.0b" +
         "\n" + u"A program to generate custom parser files for MDRevealer" + "\n" +
         u"Copyright (C) 2015 Sean Clifford" + "\n" + "Available under GPLv3+")
        
        
    def insert_blank_line(self):
        u'''
        Adds a blank line to selected_elements, for handling fields in the file
        to parse that Revealer doesn't read.
        '''
        self.selected_elements.addItem(u"(skip)")
Exemplo n.º 39
0
class Music(QWidget):
	def __init__(self):
		super().__init__()
		self.currentSonger = ''
		self.setWindowIcon(QIcon("image/tray.png"))
		self.setWindowTitle("SYL - 音乐盛宴")
		self.setObjectName("box")
		# 窗口无边框
		self.setWindowFlags(Qt.FramelessWindowHint)
		# 窗口居于所有窗口的顶端 
		# self.setWindowFlags(Qt.WindowOverridesSystemGestures)
		# 窗口居于所有窗口的顶端  针对部分X11
		# self.setWindowFlags(Qt.X11BypassWindowManagerHint)
		# 初始化基本UI界面
		self.initUI()
		# 初始化播放核心
		self.initplayer()
		# 显示主界面
		self.show()
		self.widget1 = index()
		self.widget1.setParent(self)

		
		
	def initUI(self):
		# 获取电脑屏幕宽高 让主界面初始化后处于屏幕中间
		wh = QApplication.desktop().screenGeometry()
		self.screen_w , self.screen_h = wh.width() ,wh.height()
		self.setGeometry(int((self.screen_w-300)/2),int((self.screen_h-600)/2),300,600)
		# self.setWindowOpacity(0.97); 

		#当前播放歌曲的封面 
		songer_img = DragLabel(self)
		# songer_img.setwinflag.connect(self.setwinflag)
		songer_img.setParent(self)
		songer_img.resize(300,200)

		self.picture = QLabel(songer_img)
		self.picture.resize(300,200)
		self.picture.setStyleSheet("QLabel{ border-image:url("+conf['pifu']+")}")

		# syl = QLabel(songer_img)
		# syl.setGeometry(15,5,34,15)
		# syl.setStyleSheet("QLabel{ border-image:url(image/newimg/logo.png);}")

		# ================================
		songinfo = QLabel(songer_img)
		songinfo.setGeometry(0,30,300,80)
		songinfo.setStyleSheet("QLabel{ background:transparent;}")

		songpic = QLabel(songinfo)
		songpic.setGeometry(10,0,80,80)
		songpic.setStyleSheet("QLabel{ border-image:url(image/newimg/user.jpg);border-radius:2px;}")

		self.songname = QLabel("老鼠爱大米 - 香香",songinfo)
		self.songname.setGeometry(105,0,210,25)
		self.songname.setStyleSheet("QLabel{ color:#EEE;font-size:15px;}")
		uploaduser = QLabel("By 张三的歌",songinfo)
		uploaduser.move(105,25)
		# uploaduser.setCursor(QCursor(Qt.PointingHandCursor))
		uploaduser.setStyleSheet("QLabel{ color:yellow;font-size:15px;} QLabel:hover{color:red}")

		fenshu = QLabel("评分 - 7.6",songinfo)
		fenshu.setGeometry(105,50,210,25)
		# self.picture.setGraphicsEffect(QGraphicsBlurEffect())
		fenshu.setStyleSheet("QLabel{ color:#EEE;font-size:15px;}")


		songtool = QLabel(songer_img)
		songtool.setGeometry(0,110,300,35)
		songtool.setStyleSheet("QLabel{ background:transparent;}")

		# 喜欢歌曲
		lovesong = QLabel(songtool)
		lovesong.setGeometry(20,10,25,25)
		lovesong.setStyleSheet("QLabel{ border-image:url(image/newimg/kg_ic_player_liked.png);}")
		# 评论
		pinglun = QLabel(songtool)
		pinglun.setGeometry(50,5,33,33)
		pinglun.setStyleSheet("QLabel{ border-image:url(image/newimg/pinglun.png);}")
		# 歌曲更多信息
		songmore = QLabel("查看这首歌的更多资料",songtool)
		songmore.move(100,10)
		# songmore.setCursor(QCursor(Qt.PointingHandCursor))
		songmore.setStyleSheet("QLabel{ color:#BBB} QLabel:hover{color:pink}")


		# ======================================

		# 顶部工具栏
		# 隐藏
		btn = QPushButton("",self)
		btn.setGeometry(270,0,15,32)
		# btn.setCursor(QCursor(Qt.PointingHandCursor))
		btn.setStyleSheet("QPushButton{ border:none;color:white;background:transparent;border-image:url(image/newimg/mini.png) } QPushButton:hover{ border-image:url(image/newimg/mini_2.png) } ")
		btn.clicked.connect(self.close)

		# 换皮肤
		btn = QPushButton("",self)
		btn.setGeometry(230,10,20,20)
		# btn.setCursor(QCursor(Qt.PointingHandCursor))
		btn.setStyleSheet("QPushButton{ border:none;color:white;background:transparent;border-image:url(image/newimg/fx_slide_menu_change_bg_2.png) } QPushButton:hover{ border-image:url(image/newimg/fx_slide_menu_change_bg.png) } ")
		btn.clicked.connect(self.huanfu)
		# 设置封面
		# btn = QPushButton("",self)
		# btn.setGeometry(230,-10,41,48)
		# btn.setCursor(QCursor(Qt.PointingHandCursor))
		# btn.setStyleSheet("QPushButton{ border:none;color:white;background:transparent;border-image:url(image/newimg/fengmian.png) } ")
		# btn.clicked.connect(self.setHeaderImg)
		# 开启/关闭歌词
		# btn = QPushButton("",self)
		# btn.setGeometry(200,0,30,30)
		# btn.setCursor(QCursor(Qt.PointingHandCursor))
		# btn.setStyleSheet("QPushButton{ border:none;color:white;background:transparent;border-image:url(image/newimg/geci.png) } ")
		# btn.clicked.connect(self.lrc)
		# 播放组件  ( 播放  前进 后退 播放时间 进度条 歌曲名 音量 )
		# 播放/暂停
		self.playBtn = QPushButton("",songer_img)
		self.playBtn.setGeometry(130,155,32,25)
		self.playBtn.setStyleSheet("QPushButton{ border-image:url(image/newimg/statusbar_btn_play.png);border:none } QPushButton:hover{ border-image:url(image/newimg/statusbar_btn_play_2.png)} ")
		# 下一首
		self.nextBtn = QPushButton("",songer_img)
		self.nextBtn.setGeometry(186,159,20,20)
		self.nextBtn.setStyleSheet("QPushButton{ border-image:url(image/newimg/statusbar_btn_next.png);border:none } QPushButton:hover{ border-image:url(image/newimg/statusbar_btn_next_2.png)}")
		# 音量调节
		self.songvolume = QPushButton("",songer_img)
		self.songvolume.setGeometry(236,159,20,20)
		self.songvolume.setStyleSheet("QPushButton{ border-image:url(image/newimg/ic_player_menu_volume.png);border:none } QPushButton:hover{ border-image:url(image/newimg/ic_player_menu_volume_2.png)}")
		self.songvolume.clicked.connect(self.setvolume)
		# 音量
		self.volslider = QSlider(Qt.Horizontal,self)
		self.volslider.setCursor(QCursor(Qt.UpArrowCursor))
		self.volslider.setGeometry(250,165,45,6)
		self.volslider.setValue(70)
		self.volslider.setRange(0,100)
		self.volslider.setStyleSheet(qss_vol)
		self.volslider.setVisible(False)

		# 上一首
		self.prevBtn = QPushButton("",songer_img)
		self.prevBtn.setGeometry(85,159,20,20)
		self.prevBtn.setStyleSheet("QPushButton{ border-image:url(image/newimg/statusbar_btn_prev.png);border:none } QPushButton:hover{ border-image:url(image/newimg/statusbar_btn_prev_2.png)}")
		# 播放模式
		self.playmodel = QPushButton("",songer_img)
		self.playmodel.setGeometry(35,156,25,25)
		self.playmodel.setStyleSheet("QPushButton{ border-image:url(image/newimg/allmodel.png);border:none } QPushButton:hover{ border-image:url(image/newimg/allmodel_2.png)}")
		self.playmodel.clicked.connect(self.moshi)

		# 当前播放时间
		self.songTime = QLabel("",self)
		self.songTime.setGeometry(240,180,80,20)
		self.songTime.setStyleSheet("QLabel{ color:#AAA;font-size:12px;}")
		self.songTime.setAlignment(Qt.AlignHCenter)
		
		# 当前歌曲名   
		self.currentMusicName = QLabel("",songer_img)
		self.currentMusicName.setGeometry(0,180,200,20)
		self.currentMusicName.setStyleSheet("QLabel{ color:white ;font-weight:100;font-size:12px;margin-left:5px;}")
		# 歌曲进度条
		self.processSlider = QSlider(Qt.Horizontal,self)
		self.processSlider.setGeometry(0,193,300,7)
		# self.processSlider.setRange(1,100)
		self.processSlider.setValue(0)
		self.processSlider.setStyleSheet(qss_process_slider)
		
		self.processSlider.setCursor(QCursor(Qt.UpArrowCursor))

		# 歌曲列表 ---------------------------
		listWgt = QWidget(self)
		listWgt.setGeometry(0, 200, 300,380)
		listWgt.setStyleSheet(qss_scrollbar)

		#列表
		self.songList = QListWidget(listWgt)
		self.songList.setGeometry(5,0,235,380)   
		self.songList.setStyleSheet(qss_songlist)	
		# 列表添加右键菜单
		# self.songList.setContextMenuPolicy(Qt.CustomContextMenu)
		# self.songList.customContextMenuRequested.connect(self.rightMenuShow)

		#歌曲列表右边的功能列表
		funcList = QListWidget(listWgt)
		funcList.setGeometry(240,0,55,380)   
		funcList.setStyleSheet(qss_menu)
		btn = QPushButton("",funcList)
		btn.clicked.connect(self.newwindow)
		btn.setGeometry(15,10,30,30)
		btn.setStyleSheet("QPushButton{ border-image:url(image/home.png)} \
			QPushButton:hover{ border-image:url(image/homehover.png) }")
		# btn.setCursor(QCursor(Qt.PointingHandCursor))
		btn = QPushButton("",funcList)
		btn.setGeometry(15,60,30,30)
		btn.setStyleSheet("QPushButton{ border-image:url(image/tuijian.png) } \
			QPushButton:hover{ border-image:url(image/tuijianhover.png) }")
		# btn.setCursor(QCursor(Qt.PointingHandCursor))
		btn = QPushButton("",funcList)
		btn.setGeometry(15,100,30,30)
		btn.setStyleSheet("QPushButton{ border-image:url(image/shoucang.png) }\QPushButton:hover{ border-image:url(image/shoucanghover.png) }")
		# btn.setCursor(QCursor(Qt.PointingHandCursor))

		btn = QPushButton("",funcList)
		btn.setGeometry(15,140,30,30)
		btn.setStyleSheet("QPushButton{ border-image:url(image/rizhi.png) }\
			QPushButton:hover{ border-image:url(image/rizhihover.png) }")
		# btn.setCursor(QCursor(Qt.PointingHandCursor))

		btn = QPushButton("",funcList)
		btn.setGeometry(17,180,30,30)
		btn.setStyleSheet("QPushButton{ border-image:url(image/mv.png) }\
			QPushButton:hover{ border-image:url(image/mvhover.png) }")
		# btn.setCursor(QCursor(Qt.PointingHandCursor))

		setbtn = QPushButton("",funcList)
		setbtn.setGeometry(15,225,33,33)
		setbtn.setStyleSheet("QPushButton{ border-image:url(image/settinghover.png) }\
			QPushButton:hover{ border-image:url(image/setting.png) }")
		setbtn.clicked.connect(self.openseting)

		#底部状态栏
		wg = QWidget(self)
		wg.setGeometry(0, 580, 300,20)
		wg.setStyleSheet("QWidget{ background:#2D2D2D; } ")
		# ql = QLabel(" <a style='color:#444;text-decoration:none;font-size:12px;'  href ='https://github.com/codeAB/music-player' >S Y L </a>",wg)
		# ql.resize(300,20)
		# ql.setAlignment(Qt.AlignRight)
		# ql.linkActivated.connect(self.openurl)

		#设置托盘图标
		tray = QSystemTrayIcon(self)
		tray.setIcon(QIcon('image/tray.png'))
		self.trayIconMenu = QMenu(self)
		self.trayIconMenu.setStyleSheet(qss_tray)
		showAction = QAction(QIcon('image/tray.png'),u"显示主面板", self,triggered=self.show)
		self.trayIconMenu.addAction(showAction)
		# self.trayIconMenu.addAction(preAction)
		# self.trayIconMenu.addAction(pauseAction)
		# self.trayIconMenu.addAction(nextAction)
		# self.trayIconMenu.addAction(quitAction)
		tray.setContextMenu(self.trayIconMenu)
		tray.show()
		tray.activated.connect(self.dbclick_tray)
	# 重写两个方法实现拖动播放器到屏幕顶端自动隐藏
	def enterEvent(self,QMouseEvent):
		if self.y() < 1 and self.size().width() == 300:
			self.setGeometry(self.x(),0,300,600) 
			# 窗口居于所有窗口的顶端 
			# self.setWindowFlags(Qt.WindowOverridesSystemGestures)
			#针对X11
			# self.setWindowFlags(Qt.X11BypassWindowManagerHint)
	def leaveEvent(self,QMouseEvent):
		if self.y() < 1 and self.size().width() == 300:
			self.setGeometry(self.x(),0,300,1)
			# 窗口居于所有窗口的顶端 
			# self.setWindowFlags(Qt.WindowOverridesSystemGestures)
			#针对X11
			# self.setWindowFlags(Qt.X11BypassWindowManagerHint)
		# else:
			# self.setWindowFlags(Qt.FramelessWindowHint)
	#加载播放核心
	def initplayer(self):
		#play_song_list用来方便的维护列表,主要用来记录当前播放列表
		# self.play_song_list = {}
		self.p = Player(self)
		# self.songList.itemDoubleClicked.connect(self.playit)
		self.playBtn.clicked.connect(self.play_or_pause)
		self.nextBtn.clicked.connect(self.nextone)
		self.prevBtn.clicked.connect(self.prevone)
		# self.lrc()
		# self.vol.valueChanged.connect(self.)
	#双击托盘图标
	def dbclick_tray(self,event):
		if event==QSystemTrayIcon.DoubleClick:
			# self.show()
			if self.isVisible():
				self.hide()
			else:
				self.show()
	#打开音乐窗
	def newwindow(self):
		if not hasattr(self,'widget1'):
			self.widget1 = index()
			self.widget1.setParent(self)

			# 获取屏幕宽高
			wh = QApplication.desktop().screenGeometry()
			self.screen_w , self.screen_h = wh.width() ,wh.height()
			self.move(int((self.screen_w-900)/2),int((self.screen_h-600)/2))
			self.widget1.show()
		else:
			if self.size().width() == 900:
				self.resize(300,600)
				self.widget1.hide()
				return True
			# wh = QApplication.desktop().screenGeometry()
			# self.screen_w , self.screen_h = wh.width() ,wh.height()
			# self.move(int((self.screen_w-900)/2),int((self.screen_h-600)/2))
			self.widget1.show()
		self.resize(900,600)
		
	#创建右键菜单
	def rightMenuShow(self,point):
		self.current_context_item = self.songList.itemAt(point)
		if self.current_context_item is None:
			return False
		rightMenu = QMenu(self.songList)
		# print(dir(rightMenu))
		rightMenu.setStyleSheet("QMenu{ width:100px;border:none;padding:5px; } QMenu::item{ background-color: transparent;width:70px;text-align:center;height:25px; margin:0px 0px;border-bottom:1px solid #EEE;padding-left:20px;color:#333 }  QMenu::item:selected{ color:red;border-bottom:1px solid pink;background:none; }") 
		loveAction = QAction(u"添加收藏", self, triggered=self.deleteSongItem)
		delAction = QAction(u"删除", self, triggered=self.deleteSongItem)    
		rateAction = QAction(u"我要打分", self, triggered=self.deleteSongItem)    
		cmAction = QAction(u"评论", self, triggered=self.deleteSongItem)  
		moreAction = QAction(u"歌曲详情", self, triggered=self.deleteSongItem)  
		moneyAction = QAction(u"打赏", self, triggered=self.deleteSongItem)  
		rightMenu.addAction(loveAction)
		rightMenu.addAction(delAction)
		rightMenu.addAction(rateAction)
		rightMenu.addAction(cmAction)
		rightMenu.addAction(moreAction)
		rightMenu.addAction(moneyAction)
		rightMenu.exec_(QCursor.pos())
	def deleteSongItem(self):
		item = self.current_context_item
		# print(dir(item))
		item.setBackground(QBrush(QColor("red")))
		return False
		# index = item.text()
		x = self.songList.row(self.current_context_item)
		self.newSort(int(x))
		# 获取当前鼠标右键点击的歌曲名
		songname = self.current_context_item.text()
		p = re.compile(r'\d+')
		r = p.findall(songname)
		item = int(r[0]) - 1;
		mp3path = conf['mp3dir']
		i = 0
		for filename in os.listdir(mp3path):
			if i == item:
				# 删除列表item
				self.songList.takeItem(self.songList.row(self.current_context_item))
				# 删除播放队列item
				self.playlist.removeMedia(item)
				# 删除文件
				os.remove(os.path.join(mp3path, filename))
				break
			i = i+1
	# 当删除或者新增歌曲时更新列表
	def newSort(self,index,flag = 'del'):
		# 删除歌曲
		if flag == 'del':
			v = self.songList.findChildren(QPushButton,'',Qt.FindChildrenRecursively)
			self.songList.removeItemWidget(self.current_context_item)
			# print(len(v))
			# v[index].parent().remove()
			# print(v[index].parent().hide())
			self.songList.update()
			print(self.songList.count())
	def openurl(self):
		QDesktopServices.openUrl(QUrl("http://sylsong.com"))
	def myclose(self):
		if hasattr(self,'widget1'):
			self.widget1.close() and self.close()
		else:
			self.close()
	def setHeaderImg(self):
		cs = self.currentSonger
		if len(cs) > 1:
			self.s = Singer(cs,self)
			self.show()
	# def lrc(self):
	# 	if hasattr(self,'lrctext'):
	# 		if self.lrctext.isVisible():
	# 			self.lrctext.setVisible(False)
	# 			self.p.showgeci(1)
	# 		else:
	# 			self.lrctext.setVisible(True)
	# 			self.p.showgeci()
	# 	else:
	# 		self.lrctext = DLabel(self)
	# 		self.p.showgeci()
	def moshi(self):
		ct = self.playmodel;
		currentModel = self.playlist.playbackMode()
		if currentModel == 1:
			self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
			self.playmodel.setStyleSheet("QPushButton{ border-image:url(image/newimg/ic_player_mode_all_default.png); } QPushButton:hover{ border-image:url(image/newimg/ic_player_mode_all_default_2.png)}")
		elif currentModel == 2:
			self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
			self.playmodel.setStyleSheet("QPushButton{ border-image:url(image/newimg/allmodel.png); } QPushButton:hover{ border-image:url(image/newimg/allmodel_2.png)}")
		elif currentModel == 3:
			self.playlist.setPlaybackMode(QMediaPlaylist.Random)
			self.playmodel.setStyleSheet("QPushButton{ border-image:url(image/newimg/ic_player_mode_random_default.png); } QPushButton:hover{ border-image:url(image/newimg/ic_player_mode_random_default_2.png)}")
		elif currentModel == 4:
			self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
			self.playmodel.setStyleSheet("QPushButton{ border-image:url(image/newimg/ic_player_mode_single_default.png); } QPushButton:hover{ border-image:url(image/newimg/ic_player_mode_single_default_2.png)}")
	def setvolume(self):
		if self.volslider.isVisible():
			self.volslider.setVisible(False)
			self.songvolume.setStyleSheet("QPushButton{ border-image:url(image/newimg/ic_player_menu_volume.png); } QPushButton:hover{ border-image:url(image/newimg/ic_player_menu_volume_2.png)}")
		else:
			self.volslider.setVisible(True)
			self.songvolume.setStyleSheet("QPushButton{ border-image:url(image/newimg/ic_player_menu_volume_click.png); } QPushButton:hover{ border-image:url(image/newimg/ic_player_menu_volume_click.png)}")
	# def setwinflag(self,index):
	# 	if index == 2:
	# 		self.setWindowFlags(Qt.X11BypassWindowManagerHint)
	# 		self.update()
	# 		self.show()
	# 	else:
	# 		self.setWindowFlags(Qt.FramelessWindowHint)
	# 		self.update()
	# 		self.show()
	def openseting(self):
		
		if not hasattr(self,'popwindow'):
			self.popwindow = popWindow(1)
		else:
			self.popwindow.show()
	def huanfu(self):
		# self.picture.setStyleSheet("QLabel{ border-image:url(image/newimg/back.jpg)}")
		fileinput = QFileDialog.getOpenFileName(self,"选择一张图片作为皮肤","/opt/music-player/","Images (*.jpg)")
		if not fileinput[0]:
			return False
		else:
			f=open("conf/conf.py","w+")
			conf['pifu'] = fileinput[0]
			f.write("conf = "+str(conf))
			f.close()
			self.picture.setStyleSheet("QLabel{ border-image:url("+fileinput[0]+")}")
Exemplo n.º 40
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")

        self.file_menu = QtWidgets.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit,
                                 QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)

        self.help_menu = QtWidgets.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)

        self.help_menu.addAction('&About', self.about)

        self.main_widget = QtWidgets.QWidget(self)

        mainLayout = QtWidgets.QVBoxLayout(self.main_widget)

        # convas
        # dc = MyDynamicMplCanvas(self.main_widget, width=8, height=4, dpi=100)
        # mainLayout.addWidget(dc)


        hBoxLayout = QtWidgets.QHBoxLayout()

        # self.tableWidget = QTableWidget(self)
        # self.tableWidget.setRowCount(1)
        # self.tableWidget.setColumnCount(100)
        # self.tableWidget.resizeRowToContents(0)
        #self.tableWidget.setItem(0,0, QTableWidgetItem("aa"))
        #self.tableWidget.insertRow(1)

        self.listWidget = QListWidget(self)
        # self.listWidget.addItem(QListWidgetItem("3"))


        self.factorValue = QLineEdit(self)
        self.factorValue.setText("0.98")
        self.factorValue.setFixedSize(100, 30)

        self.factorButton = QPushButton(self)
        self.factorButton.setText('Change emissivity')
        self.factorButton.clicked.connect(self.factorButtonOnClicked)
        self.factorButton.setFixedSize(150, 30)

        self.stopButton = QPushButton(self)
        self.stopButton.setText('Stop')
        self.stopButton.clicked.connect(self.stopButtonOnClicked)
        self.stopButton.setFixedSize(100, 30)

        self.copyData = QPushButton(self)
        self.copyData.setText('Copy')
        self.copyData.clicked.connect(self.onCopyButtonCliced)


        self.oneMeasureButton = QPushButton(self)
        self.oneMeasureButton.setText('One Measure')
        self.oneMeasureButton.clicked.connect(self.onMeasureButtonOnClicked)


        # self.oneMeasureButton.setFixedSize(5,5)

        # self.factorMenu = QMenu(self)
        # self.factorMenu.frameSize()
        # self.factorSubMenu = self.factorMenu.addMenu("material")
        # self.factorSubMenu.addAction("new")
        # self.factorSubMenu.addAction("new2")


        spacer = QSpacerItem(500, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        hBoxLayout.addItem(spacer)
        # hBoxLayout.addWidget(self.factorMenu)

        mainLayout.addWidget(self.listWidget)
        # mainLayout.addWidget(self.tableWidget)

        hBoxLayout.addWidget(self.copyData)
        hBoxLayout.addWidget(self.factorValue)
        hBoxLayout.addWidget(self.factorButton)
        hBoxLayout.addWidget(self.stopButton)
        hBoxLayout.addWidget(self.oneMeasureButton)

        mainLayout.addLayout(hBoxLayout)



        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        #self.statusBar().showMessage("All hail matplotlib!", 2000)

    def stopButtonOnClicked(self):
        print("\tStop button clicked")
        connMan = PirConnManager()
        connMan.sendStopCommand()



    def factorButtonOnClicked(self):
        print("\tChange emissivity factor button clicked")

        e = float(self.factorValue.text())

        # save only when e is in range
        if e >= 0.1 and e <= 1.0:
            connMan = PirConnManager()
            if True == connMan.saveEmissivity(e):
                print("Emmisivity changed to ", e)
            else:
                print("Error whiel saving emmisivity")
        else:
            print("Aborting. Wrong emmisivity value!")


    def onMeasureButtonOnClicked(self):
        print("\tOne Measuere button clicked")
        connMan = PirConnManager()
        temp = connMan.readOneSample("object")
        self.listWidget.addItem(str(round(temp[0],2))+ " °C")
        self.listWidget.setCurrentRow( self.listWidget.count() - 1 )

        # copy to clipboard
        # cl =  QApplication.clipboard()
        # cl.setText("TestTest")

        print(temp)

    def onCopyButtonCliced(self):
        # copy to clipboard
        cl =  QApplication.clipboard()

        items = []
        for index in range( self.listWidget.count()):
            items.append( self.listWidget.item(index).text())
            # print(self.listWidget.item(index).text())

        cl.setText(str(items))


        #cl.setText("TestTest")

    def fileQuit(self):
        self.close()

    def closeEvent(self, ce):
        print("exiting")
        self.fileQuit()

    def about(self):
        QtWidgets.QMessageBox.about(self, "")
Exemplo n.º 41
0
class ListEdit(QWidget):
    """A widget to edit a list of items (e.g. a list of directories)."""
    
    # emitted when anything changed in the listbox.
    changed = pyqtSignal()
    
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        layout = QGridLayout(self)
        self.setLayout(layout)
        
        self.addButton = QPushButton(icons.get('list-add'), '')
        self.editButton = QPushButton(icons.get('document-edit'), '')
        self.removeButton = QPushButton(icons.get('list-remove'), '')
        self.listBox = QListWidget()
        
        layout.setContentsMargins(1, 1, 1, 1)
        layout.setSpacing(0)
        layout.addWidget(self.listBox, 0, 0, 8, 1)
        layout.addWidget(self.addButton, 0, 1)
        layout.addWidget(self.editButton, 1, 1)
        layout.addWidget(self.removeButton, 2, 1)
        
        @self.addButton.clicked.connect
        def addClicked():
            item = self.createItem()
            if self.openEditor(item):
                self.addItem(item)
                
        @self.editButton.clicked.connect
        def editClicked():
            item = self.listBox.currentItem()
            item and self.editItem(item)
        
        @self.removeButton.clicked.connect
        def removeClicked():
            item = self.listBox.currentItem()
            if item:
                self.removeItem(item)
        
        @self.listBox.itemDoubleClicked.connect
        def itemDoubleClicked(item):
            item and self.editItem(item)
            
        self.listBox.model().layoutChanged.connect(self.changed)
    
        def updateSelection():
            selected = bool(self.listBox.currentItem())
            self.editButton.setEnabled(selected)
            self.removeButton.setEnabled(selected)
        
        self.changed.connect(updateSelection)
        self.listBox.itemSelectionChanged.connect(updateSelection)
        updateSelection()
        app.translateUI(self)
    
    def translateUI(self):
        self.addButton.setText(_("&Add..."))
        self.editButton.setText(_("&Edit..."))
        self.removeButton.setText(_("&Remove"))
    
    def createItem(self):
        return QListWidgetItem()
        
    def addItem(self, item):
        self.listBox.addItem(item)
        self.itemChanged(item)
        self.changed.emit()
        
    def removeItem(self, item):
        self.listBox.takeItem(self.listBox.row(item))
        self.changed.emit()
        
    def editItem(self, item):
        if self.openEditor(item):
            self.itemChanged(item)
            self.changed.emit()
            
    def setCurrentItem(self, item):
        self.listBox.setCurrentItem(item)
        
    def setCurrentRow(self, row):
        self.listBox.setCurrentRow(row)
        
    def openEditor(self, item):
        """Opens an editor (dialog) for the item.
        
        Returns True if the dialog was accepted and the item edited.
        Returns False if the dialog was cancelled (the item must be left
        unedited).
        """
        pass
    
    def itemChanged(self, item):
        """Called after an item has been added or edited.
        
        Re-implement to do something at this moment if needed, e.g. alter the
        text or display of other items.
        """
        pass
    
    def setValue(self, strings):
        """Sets the listbox to a list of strings."""
        self.listBox.clear()
        self.listBox.addItems(strings)
        self.changed.emit()
        
    def value(self):
        """Returns the list of paths in the listbox."""
        return [self.listBox.item(i).text()
            for i in range(self.listBox.count())]
    
    def setItems(self, items):
        """Sets the listbox to a list of items."""
        self.listBox.clear()
        for item in items:
            self.listBox.addItem(item)
            self.itemChanged(item)
        self.changed.emit()
    
    def items(self):
        """Returns the list of items in the listbox."""
        return [self.listBox.item(i)
            for i in range(self.listBox.count())]
        
    def clear(self):
        """Clears the listbox."""
        self.listBox.clear()
        self.changed.emit()
Exemplo n.º 42
0
class GstPipeEdit(QDialog):

    def __init__(self, pipe, preferences_mode=False, **kwargs):
        super().__init__(**kwargs)

        self.setWindowTitle('Edit Pipeline')
        self.setWindowModality(Qt.ApplicationModal)
        self.setLayout(QGridLayout())
        self.setMaximumSize(500, 400)
        self.setMinimumSize(500, 400)
        self.resize(500, 400)

        self._preferences_mode = preferences_mode

        # Input selection
        self.inputBox = QComboBox(self)
        self.layout().addWidget(self.inputBox, 0, 0, 1, 3)
        self.init_inputs(pipe)

        # Current plugins list
        self.currentList = QListWidget(self)
        self.currentList.setDragEnabled(True)
        self.currentList.setDragDropMode(QAbstractItemView.InternalMove)
        self.layout().addWidget(self.currentList, 1, 0, 3, 1)
        self.init_current_plugins(pipe)

        # Add/Remove plugins buttons
        self.pluginsLayout = QVBoxLayout(self)
        self.layout().addLayout(self.pluginsLayout, 2, 1)

        self.addButton = QPushButton(self)
        self.addButton.setIcon(QIcon.fromTheme('go-previous'))
        self.addButton.clicked.connect(self.__add_plugin)
        self.pluginsLayout.addWidget(self.addButton)
        self.pluginsLayout.setAlignment(self.addButton, Qt.AlignHCenter)

        self.delButton = QPushButton(self)
        self.delButton.setIcon(QIcon.fromTheme('go-next'))
        self.delButton.clicked.connect(self.__remove_plugin)
        self.pluginsLayout.addWidget(self.delButton)
        self.pluginsLayout.setAlignment(self.delButton, Qt.AlignHCenter)

        # Available plugins list
        self.availableList = QListWidget(self)
        self.layout().addWidget(self.availableList, 1, 2, 3, 1)
        self.init_available_plugins(pipe)

        # Output selection
        self.outputBox = QComboBox(self)
        self.layout().addWidget(self.outputBox, 4, 0, 1, 3)
        self.init_outputs(pipe)

        # Confirm/Cancel buttons
        self.dialogButtons = QDialogButtonBox(self)
        self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel |
                                              QDialogButtonBox.Ok)
        self.layout().addWidget(self.dialogButtons, 5, 0, 1, 3)

        self.dialogButtons.accepted.connect(self.accept)
        self.dialogButtons.rejected.connect(self.reject)

    def init_inputs(self, pipe):
        if self._preferences_mode:
            self.inputBox.setEnabled(False)
        else:
            inputs = sorted(elements.inputs())
            self.inputBox.addItems(inputs)
            self.inputBox.setEnabled(len(inputs) > 1)
            if pipe != '':
                self.inputBox.setCurrentIndex(inputs.index(pipe.split('!')[0]))

    def init_outputs(self, pipe):
        outputs = sorted(elements.outputs())
        self.outputBox.addItems(outputs)
        self.outputBox.setEnabled(len(outputs) > 1)
        if pipe != '':
            self.outputBox.setCurrentIndex(outputs.index(pipe.split('!')[-1]))

    def init_current_plugins(self, pipe):
        start = 0 if self._preferences_mode else 1
        for plugin in pipe.split('!')[start:-1]:
            self.currentList.addItem(plugin)

    def init_available_plugins(self, pipe):
        currents = pipe.split('!')
        for plugin in elements.plugins().values():
            if plugin.Name not in currents:
                self.availableList.addItem(plugin.Name)

    def get_pipe(self):
        pipe = [] if self._preferences_mode else [self.inputBox.currentText()]
        for n in range(self.currentList.count()):
            pipe.append(self.currentList.item(n).text())
        pipe.append(self.outputBox.currentText())

        return '!'.join(pipe)

    def __add_plugin(self):
        item = self.availableList.takeItem(self.availableList.currentRow())
        self.currentList.addItem(item)

    def __remove_plugin(self):
        item = self.currentList.takeItem(self.currentList.currentRow())
        self.availableList.addItem(item)
Exemplo n.º 43
0
class CreateChatDialog(QDialog):
   def __init__(self):
      super().__init__()
      self.initUI()
      self.created_chat = False
      self.participants = []
      self.chat_name = None

      for friend in config.friends:
         self.unadded_friends.addItem(QListWidgetItem(friend))

   def initUI(self):
      self.setWindowModality(Qt.ApplicationModal)
      self.setWindowTitle("Create Chat")

      self.grid = QGridLayout(self)

      self.chat_name_label = QLabel("Chat Name:")
      self.grid.addWidget(self.chat_name_label, 0, 0, 1, 1)
      self.chat_name_field = QLineEdit()
      self.grid.addWidget(self.chat_name_field, 0, 1, 1, 3)

      self.unadded_friends = QListWidget()
      self.unadded_friends.setSortingEnabled(True)
      self.grid.addWidget(self.unadded_friends, 1, 0, 4, 2)

      self.added_friends = QListWidget()
      self.added_friends.setSortingEnabled(True)
      self.grid.addWidget(self.added_friends, 1, 3, 4, 1)

      self.add_friend_button = QPushButton(">>")
      self.add_friend_button.pressed.connect(self.addFriend)
      self.grid.addWidget(self.add_friend_button, 2, 2, 1, 1)

      self.remove_friend_button = QPushButton("<<")
      self.remove_friend_button.pressed.connect(self.removeFriend)
      self.grid.addWidget(self.remove_friend_button, 3, 2, 1, 1)

      self.create_button = QPushButton("Create")
      self.create_button.pressed.connect(self.createChat)
      self.grid.addWidget(self.create_button, 5, 0, 1, 4)

      self.cancel_button = QPushButton("Cancel")
      self.cancel_button.pressed.connect(self.cancel)
      self.grid.addWidget(self.cancel_button, 6, 0, 1, 4)

   def addFriend(self):
      selected_friends = self.unadded_friends.selectedItems()
      for friend in selected_friends:
         self.unadded_friends.takeItem(self.unadded_friends.row(friend))
         self.added_friends.addItem(friend)

   def removeFriend(self):
      selected_friends = self.added_friends.selectedItems()
      for friend in selected_friends:
         self.added_friends.takeItem(self.added_friends.row(friend))
         self.unadded_friends.addItem(friend)

   def createChat(self):
      self.created_chat = True
      self.chat_name = self.chat_name_field.text()
      for i in range(self.added_friends.count()):
         self.participants.append(self.added_friends.item(i).text())
      config.chats[self.chat_name] = {"participants": self.participants}
      self.close()

   def cancel(self):
      self.close()
Exemplo n.º 44
0
class ExtensionsSettingsPanel(SettingsPanel):
    def __init__(self, parent=None):
        super(ExtensionsSettingsPanel, self).__init__(parent)

        self.thread = ExtensionsUpdateThread(self)
        self.thread.finished.connect(self.notifyFinish)
        self.thread.finished.connect(self.loadSettings)

        # List row
        listRow = custom_widgets.Row(self)
        self.layout().addWidget(listRow)

        # Extensions whitelist.
        whitelistColumn = custom_widgets.Column(self)
        listRow.addWidget(whitelistColumn)
        whitelistColumn.addWidget(QLabel(tr("Enabled extensions:"), self))
        self.whitelist = QListWidget(self)
        self.whitelist.currentTextChanged.connect(self.changeAboutText)
        self.whitelist.itemActivated.connect(self.disableExtension)
        whitelistColumn.addWidget(self.whitelist)

        # Extensions blacklist.
        blacklistColumn = custom_widgets.Column(self)
        listRow.addWidget(blacklistColumn)
        blacklistColumn.addWidget(QLabel(tr("Disabled extensions:"), self))
        self.blacklist = QListWidget(self)
        self.blacklist.currentTextChanged.connect(self.changeAboutText)
        self.blacklist.itemActivated.connect(self.enableExtension)
        blacklistColumn.addWidget(self.blacklist)

        # About text
        self.aboutText = custom_widgets.ReadOnlyTextEdit(self)
        self.aboutText.setMaximumHeight(92)
        self.layout().addWidget(self.aboutText)

        updateExtensionsButton = QPushButton(tr("&Update extensions"), self)
        updateExtensionsButton.clicked.connect(self.updateExtensions)
        self.layout().addWidget(updateExtensionsButton)

    def changeAboutText(self, name):
        aboutpath = os.path.join(settings.extensions_folder, name, "about.txt")
        try: f = open(aboutpath, "r")
        except:
            self.aboutText.setText(tr("This extension has no description."))
            return
        aboutText = f.read().replace("\n", "")
        f.close()
        self.aboutText.setText(aboutText)

    def disableExtension(self, item):
        name = item.text()
        self.blacklist.addItem(name)
        self.blacklist.sortItems(Qt.AscendingOrder)
        self.whitelist.takeItem(self.whitelist.row(item))
        self.whitelist.sortItems(Qt.AscendingOrder)

    def enableExtension(self, item):
        name = item.text()
        self.whitelist.addItem(name)
        self.whitelist.sortItems(Qt.AscendingOrder)
        self.blacklist.takeItem(self.blacklist.row(item))
        self.blacklist.sortItems(Qt.AscendingOrder)

    def notifyFinish(self):
        common.trayIcon.showMessage(tr("Extensions updated"), tr("All extensions are up to date."))

    def updateExtensions(self):
        if not self.thread.isRunning():
            common.trayIcon.showMessage(tr("Updating extensions"), tr("This may take some time."))
            self.thread.start()
        else:
            common.trayIcon.dontBeImpatient()

    def loadSettings(self):
        settings.reload_extensions()
        self.whitelist.clear()
        for extension in settings.extensions_whitelist:
            self.whitelist.addItem(extension)
        self.blacklist.clear()
        for extension in settings.extensions_blacklist:
            self.blacklist.addItem(extension)
        self.whitelist.sortItems(Qt.AscendingOrder)
        self.blacklist.sortItems(Qt.AscendingOrder)

    def saveSettings(self):
        settings.settings.setValue("extensions/Whitelist", json.dumps([self.whitelist.item(extension).text() for extension in range(0, self.whitelist.count())]))
        settings.reload_extensions()
        settings.settings.sync()
Exemplo n.º 45
0
class StringListDlg(QDialog):

    def __init__(self, name, stringlist=None, parent=None):
        super(StringListDlg, self).__init__(parent)

        self.name = name

        self.listWidget = QListWidget()
        if stringlist is not None:
            self.listWidget.addItems(stringlist)
            self.listWidget.setCurrentRow(0)
        buttonLayout = QVBoxLayout()
        for text, slot in (("&Add...", self.add),
                           ("&Edit...", self.edit),
                           ("&Remove...", self.remove),
                           ("&Up", self.up),
                           ("&Down", self.down),
                           ("&Sort", self.listWidget.sortItems),
                           ("Close", self.accept)):
            button = QPushButton(text)
            if not MAC:
                button.setFocusPolicy(Qt.NoFocus)
            if text == "Close":
                buttonLayout.addStretch()
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
#            self.connect(button, SIGNAL("clicked()"), slot)
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)
        self.setWindowTitle("Edit {0} List".format(self.name))


    def add(self):
        row = self.listWidget.currentRow()
        title = "Add {0}".format(self.name)
        string, ok = QInputDialog.getText(self, title, title)
        if ok and string is not None:
            self.listWidget.insertItem(row, string)


    def edit(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is not None:
            title = "Edit {0}".format(self.name)
            string, ok = QInputDialog.getText(self, title, title,
                    QLineEdit.Normal, item.text())
            if ok and string is not None:
                item.setText(string)


    def remove(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        reply = QMessageBox.question(self, "Remove {0}".format(
                self.name), "Remove {0} `{1}'?".format(
                self.name, unicode(item.text())),
                QMessageBox.Yes|QMessageBox.No)
        if reply == QMessageBox.Yes:
            item = self.listWidget.takeItem(row)
            del item


    def up(self):
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentItem(item)


    def down(self):
        row = self.listWidget.currentRow()
        if row < self.listWidget.count() - 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentItem(item)


    def reject(self):
        self.accept()


    def accept(self):
        self.stringlist = QStringListModel().stringList()
        for row in range(self.listWidget.count()):
            self.stringlist.append(self.listWidget.item(row).text())
        #self.stringlist.acceptedList.emit(self.stringlist)
        QDialog.accept(self)
Exemplo n.º 46
0
class CityListDlg(QDialog):
    citieslist_signal = pyqtSignal([list])

    def __init__(self, citylist, accurate_url, appid, parent=None):
        super(CityListDlg, self).__init__(parent)
        self.citylist = citylist
        self.accurate_url = accurate_url
        self.appid = appid
        self.listWidget = QListWidget()
        self.listWidget.addItems(self.citylist)
        buttonLayout = QVBoxLayout()
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.accepted.connect(self.accept)
        layoutT = QVBoxLayout()
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        for text, slot in ((self.tr("&Add..."), self.add),
                           (self.tr("&Remove..."), self.remove),
                           (self.tr("&Up"), self.up),
                           (self.tr("&Down"), self.down),
                           (self.tr("De&fault"), self.default),
                           (self.tr("&Sort"), self.listWidget.sortItems)):
            button = QPushButton(text)
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
        buttonLayout.addWidget(self.buttonBox)
        self.status = QLabel()
        layoutT.addLayout(layout)
        layoutT.addWidget(self.status)
        self.setLayout(layoutT)
        self.checklength()

    def add(self):
        self.status.setText('')
        lista = []
        newitem = ''
        self.citytoadd = ''
        self.countrytoadd = ''
        self._idtoadd = ''
        dialog = searchcity.SearchCity(self.accurate_url, self.appid, self)
        dialog.id_signal.connect(self.addcity)
        dialog.city_signal.connect(self.addcity)
        dialog.country_signal.connect(self.addcity)
        if dialog.exec_() == 1:
            newitem = (self.citytoadd + '_' + self.countrytoadd + '_' +
                       self._idtoadd)
            for row in range(self.listWidget.count()):
                lista.append(self.listWidget.item(row).text())
            if newitem in lista:
                self.status.setText(QCoreApplication.translate('Status bar message',
                                    'The city already exists in the list', 'Cities list dialogue'))
                return
            else:
                self.listWidget.addItem(newitem)
                self.checklength()

    def addcity(self, what):
        self.status.setText('')
        if what[0] == 'ID':
            self._idtoadd = what[1]
        elif what[0] == 'City':
            self.citytoadd = what[1]
        elif what[0] == 'Country':
            self.countrytoadd = what[1]

    def remove(self):
        self.status.setText('')
        if self.listWidget.count() == 0:
            self.status.setText(self.tr('The list is empty'))
            return
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        message = self.tr('The city "{0}" has been removed').format(
            self.listWidget.item(row).text())
        item = self.listWidget.takeItem(row)
        del item
        self.status.setText(message)

    def up(self):
        self.status.setText('')
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentItem(item)

    def down(self):
        self.status.setText('')
        row = self.listWidget.currentRow()
        if row < self.listWidget.count() - 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentItem(item)

    def default(self):
        self.status.setText('')
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(0, item)
            self.listWidget.setCurrentItem(item)

    def checklength(self):
        listtosend = []
        for row in range(self.listWidget.count()):
            listtosend.append(self.listWidget.item(row).text())
        if len(listtosend) == 0:
            return
        self.listWidget.setMinimumWidth(self.listWidget.sizeHintForColumn(0))

    def accept(self):
        listtosend = []
        for row in range(self.listWidget.count()):
            listtosend.append(self.listWidget.item(row).text())
        self.citieslist_signal[list].emit(listtosend)
        QDialog.accept(self)
Exemplo n.º 47
0
class UnsavedFilesDialog(QDialog):

    def __init__(self, unsaved_files, parent=None):
        super().__init__(parent)
        self._ninja = parent
        self.setWindowTitle(translations.TR_IDE_CONFIRM_EXIT_TITLE)
        vbox = QVBoxLayout(self)

        self._unsave_files_list = QListWidget()
        self._unsave_files_list.setSelectionMode(QListWidget.ExtendedSelection)
        vbox.addWidget(QLabel(translations.TR_IDE_CONFIRM_EXIT_BODY))
        vbox.addWidget(self._unsave_files_list)
        button_box = QDialogButtonBox(self)

        standard_icon = self.style().standardIcon

        btn = button_box.addButton(
            translations.TR_CANCEL, QDialogButtonBox.RejectRole)
        btn.setIcon(standard_icon(self.style().SP_DialogCloseButton))
        self._btn_save_selected = button_box.addButton(
            translations.TR_SAVE_SELECTED, QDialogButtonBox.AcceptRole)
        self._btn_save_selected.setIcon(
            standard_icon(self.style().SP_DialogSaveButton))
        btn_save_all = button_box.addButton(
            translations.TR_SAVE_ALL, QDialogButtonBox.AcceptRole)
        btn_save_all.setIcon(standard_icon(self.style().SP_DialogApplyButton))
        btn_donot_save = button_box.addButton(
            translations.TR_DONOT_SAVE, QDialogButtonBox.DestructiveRole)
        btn_donot_save.setIcon(standard_icon(self.style().SP_DialogNoButton))

        vbox.addWidget(button_box)

        for nfile in unsaved_files:
            item = QListWidgetItem(nfile.display_name)
            item.setData(Qt.UserRole, nfile)
            item.setToolTip(nfile.file_path)
            self._unsave_files_list.addItem(item)

        # Connections
        button_box.rejected.connect(self.reject)
        button_box.accepted.connect(self._save_selected)
        btn_donot_save.clicked.connect(self._discard)
        btn_save_all.clicked.connect(self._save_all)
        self._unsave_files_list.itemSelectionChanged.connect(
            self._on_selection_changed)

        self._unsave_files_list.selectAll()

    def _on_selection_changed(self):
        value = True
        if not self._unsave_files_list.selectedItems():
            value = False
        self._btn_save_selected.setEnabled(value)

    def _save_selected(self):
        logger.debug("Saving selected unsaved files")
        self.__save()

    def __save(self):
        """Collect all selected items and save"""

        items_to_save = []
        for item in self._unsave_files_list.selectedItems():
            nfile = item.data(Qt.UserRole)
            items_to_save.append(nfile)
        self._ninja._save_unsaved_files(items_to_save)
        self.accept()

    def _save_all(self):
        """Select all items in the list and save"""
        logger.debug("Saving all unsaved files")
        for index in range(self._unsave_files_list.count()):
            item = self._unsave_files_list.item(index)
            item.setSelected(True)
        self.__save()

    def _discard(self):
        logger.debug("Discarding all unsaved files")
        self.accept()
Exemplo n.º 48
0
class DataSettingsPanel(SettingsPanel):
    def __init__(self, parent=None):
        super(DataSettingsPanel, self).__init__(parent)

        # Clear history dialog.
        self.clearHistoryDialog = clear_history_dialog.ClearHistoryDialog(self)
        self.clearHistoryDialog.hide()

        self.showClearHistoryDialogButton = QPushButton(tr("Clear Data"), self)
        self.showClearHistoryDialogButton.clicked.connect(self.clearHistoryDialog.exec_)
        self.layout().addWidget(self.showClearHistoryDialogButton)

        # Remember history checkbox.
        self.rememberHistoryToggle = QCheckBox(tr("Remember &history"), self)
        self.layout().addWidget(self.rememberHistoryToggle)

        # Maximum URL length spinbox.
        self.maximumURLLengthRow = custom_widgets.SpinBoxRow(tr("Maximum URL length:"), self)
        self.maximumURLLengthRow.expander.setText(tr("characters"))
        self.maximumURLLength = self.maximumURLLengthRow.spinBox
        self.maximumURLLength.setMaximum(9999)
        self.layout().addWidget(self.maximumURLLengthRow)

        # Maximum cache size spinbox.
        # The cache is gone because it f***s Nimbus with a chainsaw.
        #self.maximumCacheSizeRow = custom_widgets.SpinBoxRow(tr("Maximum cache size:"), self)
        #self.maximumCacheSizeRow.expander.setText(tr("MB"))
        #self.maximumCacheSize = self.maximumCacheSizeRow.spinBox
        #self.maximumCacheSize.setMaximum(20000)
        #self.layout().addWidget(self.maximumCacheSizeRow)

        # Checkbox to toggle geolocation.
        self.geolocationToggle = QCheckBox(tr("Enable geo&location"), self)
        self.layout().addWidget(self.geolocationToggle)

        self.geolocationPermissionsRow = custom_widgets.Row(self)
        self.layout().addWidget(self.geolocationPermissionsRow)

        self.geolocationWhitelistColumn = custom_widgets.Column(self)
        self.geolocationPermissionsRow.addWidget(self.geolocationWhitelistColumn)

        self.geolocationWhitelistLabel = QLabel(tr("Allow these sites to track my location:"), self)
        self.geolocationWhitelistColumn.addWidget(self.geolocationWhitelistLabel)

        self.geolocationWhitelist = QListWidget(self)
        self.geolocationWhitelistColumn.addWidget(self.geolocationWhitelist)

        self.removeFromWhitelistButton = QPushButton(tr("Remove"))
        self.removeFromWhitelistButton.clicked.connect(lambda: self.geolocationWhitelist.takeItem(self.geolocationWhitelist.row(self.geolocationWhitelist.currentItem())))
        self.geolocationWhitelistColumn.addWidget(self.removeFromWhitelistButton)

        self.geolocationBlacklistColumn = custom_widgets.Column(self)
        self.geolocationPermissionsRow.addWidget(self.geolocationBlacklistColumn)

        self.geolocationBlacklistLabel = QLabel(tr("Prevent these sites from tracking my location:"), self)
        self.geolocationBlacklistColumn.addWidget(self.geolocationBlacklistLabel)

        self.geolocationBlacklist = QListWidget(self)
        self.geolocationBlacklistColumn.addWidget(self.geolocationBlacklist)

        self.removeFromBlacklistButton = QPushButton(tr("Remove"))
        self.removeFromBlacklistButton.clicked.connect(lambda: self.geolocationBlacklist.takeItem(self.geolocationBlacklist.row(self.geolocationBlacklist.currentItem())))
        self.geolocationBlacklistColumn.addWidget(self.removeFromBlacklistButton)

        self.removeAction = QAction(self)
        self.removeAction.setShortcut("Del")
        self.removeAction.triggered.connect(lambda: self.geolocationWhitelist.takeItem(self.geolocationWhitelist.row(self.geolocationWhitelist.currentItem())) if self.geolocationWhitelist.hasFocus() else self.geolocationBlacklist.takeItem(self.geolocationBlacklist.row(self.geolocationBlacklist.currentItem())))
        self.addAction(self.removeAction)

        self.layout().addWidget(custom_widgets.Expander(self))
    def loadSettings(self):
        self.maximumURLLength.setValue(settings.setting_to_int("data/MaximumURLLength"))
        #self.maximumCacheSize.setValue(settings.setting_to_int("data/MaximumCacheSize"))
        self.rememberHistoryToggle.setChecked(settings.setting_to_bool("data/RememberHistory"))
        self.geolocationToggle.setChecked(settings.setting_to_bool("network/GeolocationEnabled"))
        self.geolocationWhitelist.clear()
        for url in data.geolocation_whitelist:
            self.geolocationWhitelist.addItem(url)
        self.geolocationBlacklist.clear()
        for url in data.geolocation_blacklist:
            self.geolocationBlacklist.addItem(url)
    def saveSettings(self):
        settings.settings.setValue("data/MaximumURLLength", self.maximumURLLength.value())
        #settings.settings.setValue("data/MaximumCacheSize", self.maximumCacheSize.value())
        settings.settings.setValue("data/RememberHistory", self.rememberHistoryToggle.isChecked())
        settings.settings.setValue("network/GeolocationEnabled", self.geolocationToggle.isChecked())
        data.geolocation_whitelist = [self.geolocationWhitelist.item(authority).text() for authority in range(0, self.geolocationWhitelist.count())]
        data.geolocation_blacklist = [self.geolocationBlacklist.item(authority).text() for authority in range(0, self.geolocationBlacklist.count())]
        data.saveData()
Exemplo n.º 49
0
class TriggersSettings(SettingsSection):

    Name = 'Triggers'
    Dialog = CueListDialog()

    def __init__(self, size, cue=None, **kwargs):
        super().__init__(size, cue=None, **kwargs)
        self.setLayout(QVBoxLayout(self))

        self.list = QListWidget(self)
        self.list.setAlternatingRowColors(True)
        self.layout().addWidget(self.list)

        self.buttons = QDialogButtonBox(self)
        self.buttons.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.layout().addWidget(self.buttons)

        self.addButton = self.buttons.addButton('Add',
                                                QDialogButtonBox.ActionRole)
        self.delButton = self.buttons.addButton('Remove',
                                                QDialogButtonBox.ActionRole)

        self.addButton.clicked.connect(self._add_trigger_dialog)
        self.delButton.clicked.connect(self._remove_trigger)

        self.Dialog.reset()
        self.Dialog.add_cues(Application().layout.get_cues())

        self.duration = -1

    def _add_new_trigger(self, cue_id, action, name):
        item = QListWidgetItem()
        item.setSizeHint(QSize(200, 30))
        widget = TriggerWidget(item)
        widget.timeEdit.editingFinished.connect(self.list.sortItems)
        widget.load_trigger(cue_id, action, self.duration, name)

        self.list.addItem(item)
        self.list.setItemWidget(item, widget)

    def _add_trigger_dialog(self):
        cue = self.cue_select_dialog()
        if cue is not None:
            self._add_new_trigger(cue['id'], 'play', cue['name'])

    def _remove_trigger(self):
        widget = self.list.itemWidget(self.list.item(self.list.currentRow()))
        widget.timeEdit.editingFinished.disconnect()
        self.list.takeItem(self.list.currentRow())

    @classmethod
    def cue_select_dialog(cls):
        if cls.Dialog.exec_() == QDialog.Accepted:
            return cls.Dialog.selected_cues()[0]

    def set_configuration(self, conf):
        if conf is not None:
            self.duration = conf.get('media', {}).get('duration', -1)

            if 'triggers' in conf:
                for action, ids in conf['triggers'].items():
                    for cue_id in ids:
                        cue = Application().layout.get_cue_by_id(cue_id)
                        if cue is not None:
                            self._add_new_trigger(cue_id, action, cue['name'])

    def get_configuration(self):
        triggers = {}

        for n in range(self.list.count()):
            trigger = self.list.itemWidget(self.list.item(n))
            action, target = trigger.get_trigger()

            if action not in triggers:
                triggers[action] = [target]
            else:
                triggers[action].append(target)

        return {'triggers': triggers}
Exemplo n.º 50
0
class CodeCompletionWidget(QFrame):

    def __init__(self, editor):
        super(CodeCompletionWidget, self).__init__(
            None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self._revision = 0
        self._block = 0
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {'a': resources.IMAGES['attribute'],
                       'f': resources.IMAGES['function'],
                       'c': resources.IMAGES['class'],
                       'm': resources.IMAGES['module']}

        self.cc = code_completion.CodeCompletion()
        self._completion_results = {}
        self._prefix = ''
        self.setVisible(False)
        self.source = ''
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        self.desktop = QApplication.instance().desktop()

        self.completion_list.itemClicked['QListWidgetItem*'].connect(self.pre_key_insert_completion)
        self._editor.document().cursorPositionChanged['const QTextCursor &'].connect(self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(
                self.completion_list.count() - move)
        return True

    def update_metadata(self, cursor):
        if settings.CODE_COMPLETION:
            if self._editor.document().revision() != self._revision and \
               cursor.block().blockNumber() != self._block:
                source = self._editor.get_text()
                source = source.encode(self._editor.encoding)
                self.cc.analyze_file(self._editor.ID, source,
                                     self._editor.indent, self._editor.useTabs)
                self._revision = self._editor.document().revision()
                self._block = cursor.block().blockNumber()

    def insert_completion(self, insert, type_=ord('a')):
        if insert != self._prefix:
            closing = ''
            if type_ in (ord('f'), ord('c')):
                closing = '()'
            extra = len(self._prefix) - len(insert)
            insertion = '%s%s' % (insert[extra:], closing)
            self._editor.textCursor().insertText(insertion)
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        desktop_geometry = self.desktop.availableGeometry(self._editor)
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        #Check new position according desktop geometry
        width = (self.completion_list.sizeHintForColumn(0) +
                 self.completion_list.verticalScrollBar().sizeHint().width() +
                 10)
        height = 200
        orientation = (point.y() + height) < desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(
                    QIcon(
                        self._icons.get(p[0], resources.IMAGES['attribute'])),
                    p[1], type=ord(p[0])))

    def set_completion_prefix(self, prefix, valid=True):
        self._prefix = prefix
        proposals = []
        proposals += [('m', item)
                      for item in self._completion_results.get('modules', [])
                      if item.startswith(prefix)]
        proposals += [('c', item)
                      for item in self._completion_results.get('classes', [])
                      if item.startswith(prefix)]
        proposals += [('a', item)
                      for item in self._completion_results.get(
                          'attributes', [])
                      if item.startswith(prefix)]
        proposals += [('f', item)
                      for item in self._completion_results.get('functions', [])
                      if item.startswith(prefix)]
        if proposals and valid:
            self.complete(proposals)
        else:
            self.hide_completer()

    def _invalid_completion_position(self):
        result = False
        cursor = self._editor.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine,
                            QTextCursor.KeepAnchor)
        selection = cursor.selectedText()[:-1].split(' ')
        if len(selection) == 0 or selection[-1] == '' or \
           selection[-1].isdigit():
            result = True
        return result

    def fill_completer(self, force_completion=False):
        if not force_completion and (self._editor.cursor_inside_string() or
           self._editor.cursor_inside_comment() or
           self._invalid_completion_position()):
            return
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self._completion_results = results
        if force_completion:
            cursor = self._editor.textCursor()
            cursor.movePosition(QTextCursor.StartOfWord,
                                QTextCursor.KeepAnchor)
            prefix = cursor.selectedText()
        else:
            prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ''
        self.hide()

    def pre_key_insert_completion(self):
        type_ = ord('a')
        current = self.completion_list.currentItem()
        insert = current.text()
        if not insert.endswith(')'):
            type_ = current.type()
        self.insert_completion(insert, type_)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible() or self._editor.lang != "python":
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.get_text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix, valid = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix, valid)
            self.completion_list.setCurrentRow(0)
        force_completion = (event.key() == Qt.Key_Space and
                            event.modifiers() == Qt.ControlModifier)
        if event.key() == Qt.Key_Period or force_completion:
            self.fill_completer(force_completion)
Exemplo n.º 51
0
class Lookup(QWidget):
    MODEL_CLASS = None

    def __init__(self, parent, model):
        QWidget.__init__(self, parent, Qt.Window)
        self.model = model
        self.model.view = self
        self._setupUi()

        self.searchEdit.searchChanged.connect(self.searchChanged)
        self.searchEdit.returnPressed.connect(self.returnPressed)
        self.namesList.currentRowChanged.connect(self.currentRowChanged)
        self.namesList.itemDoubleClicked.connect(self.itemDoubleClicked)
        self._shortcutUp.activated.connect(self.upPressed)
        self._shortcutDown.activated.connect(self.downPressed)

    def _setupUi(self):
        self.setWindowTitle(tr("Lookup"))
        self.resize(314, 331)
        self.verticalLayout = QVBoxLayout(self)
        self.searchEdit = SearchEdit(self)
        self.verticalLayout.addWidget(self.searchEdit)
        self.namesList = QListWidget(self)
        self.namesList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.namesList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.namesList.setUniformItemSizes(True)
        self.namesList.setSelectionRectVisible(True)
        self.verticalLayout.addWidget(self.namesList)

        self.searchEdit.immediate = True
        self._shortcutUp = QShortcut(self.searchEdit)
        self._shortcutUp.setKey(QKeySequence(Qt.Key_Up))
        self._shortcutUp.setContext(Qt.WidgetShortcut)
        self._shortcutDown = QShortcut(self.searchEdit)
        self._shortcutDown.setKey(QKeySequence(Qt.Key_Down))
        self._shortcutDown.setContext(Qt.WidgetShortcut)

    def _restoreSelection(self):
        self.namesList.setCurrentRow(self.model.selected_index)

    #--- Event Handlers
    def returnPressed(self):
        self.model.go()

    def searchChanged(self):
        self.model.search_query = str(self.searchEdit.text())

    def currentRowChanged(self, row):
        if row >= 0:
            self.model.selected_index = row

    def itemDoubleClicked(self, item):
        self.model.go()

    def upPressed(self):
        if self.namesList.currentRow() > 0:
            self.namesList.setCurrentRow(self.namesList.currentRow()-1)

    def downPressed(self):
        if self.namesList.currentRow() < self.namesList.count()-1:
            self.namesList.setCurrentRow(self.namesList.currentRow()+1)

    #--- model --> view
    def refresh(self):
        self.namesList.clear()
        self.namesList.addItems(self.model.names)
        self._restoreSelection()
        self.searchEdit.setText(self.model.search_query)

    def show(self):
        QWidget.show(self)
        self.searchEdit.setFocus()
        # see csv_options
        self.raise_()

    def hide(self):
        QWidget.hide(self)
Exemplo n.º 52
0
class MainWindow(QMainWindow):

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

        self._suggester = suggester.Suggester()
        self._pickedfiles = []
        self._targetmidi = []
        self.inputlistview = None
        self.suggestionlistview = None
        self.target_lbl = None
        self.initUI()

    def initUI(self):

        targetButton = QPushButton('Select Target', self)
        targetButton.setToolTip('Select midi you want suggestions for')
        targetButton.resize(targetButton.sizeHint())
        targetButton.clicked.connect(self.picktargetmidi)

        self.inputlistview = QListWidget()
        self.inputlistview.itemPressed.connect(self.showmidi)

        inputlistview_lbl = QLabel(self)
        inputlistview_lbl.setText("Input MIDIs")
        inputlistview_lbl.adjustSize()

        suggestionlistview_lbl = QLabel(self)
        suggestionlistview_lbl.setText("Suggested segments")
        suggestionlistview_lbl.adjustSize()

        self.target_lbl = QLabel(self)
        self.target_lbl.setText("Please select target midi")
        self.target_lbl.adjustSize()

        self.suggestionlistview = QListWidget()

        suggestButton = QPushButton("Suggest", self)
        suggestButton.setToolTip('Suggest a continuation to target midi')
        suggestButton.clicked.connect(self.suggestmidi)
        saveButton = QPushButton("Save Suggestions", self)

        importAction = QAction(self.tr('Add MIDI file(s)'), self)
        importAction.setShortcut('Ctrl+O')
        importAction.setStatusTip('Add MIDI files to pool')
        importAction.triggered.connect(self.pickfiles)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.target_lbl)
        hbox.addWidget(targetButton)
        hbox.addWidget(suggestButton)
        hbox.addWidget(saveButton)

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(inputlistview_lbl)
        vbox.addWidget(self.inputlistview)
        vbox.addLayout(hbox)
        vbox.addWidget(suggestionlistview_lbl)
        vbox.addWidget(self.suggestionlistview)


        cwidget = QWidget()
        cwidget.setLayout(vbox)

        self.setCentralWidget(cwidget)
        self.statusBar().showMessage('Ready')

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(importAction)

        self.center()
        self.setGeometry(150,20,100,100)
        self.setWindowTitle('Gnotestic')
        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def pickfiles(self, point):
        dialog_result = QFileDialog.getOpenFileNames(self,
                                                     self.tr("Import Midi"), "", self.tr("Midi Files (*.mid *.midi)"))
        self._pickedfiles.extend(dialog_result[0])
        self.updatemidilist(dialog_result[0])

    def picktargetmidi(self, point):
        dialog_result = QFileDialog.getOpenFileName(self,
                                                    self.tr("Select Target Midi"), "", self.tr("Midi Files (*.mid *.midi)"))
        self._targetmidi = dialog_result[0]

    def updatemidilist(self, items):
        for item in items:
            witem = QListWidgetItem(item)
            self.inputlistview.addItem(witem)

    def showmidi(self, item):
        path = item.text()
        ms = converter.parse(path)
        ms.plot('pianoroll')

    def suggestmidi(self, point):
        #add midis to suggester
        if self._targetmidi and self.inputlistview.count():
            self._suggester.set_target_piece(self._targetmidi)
            for i in range(self.inputlistview.count()):
                self._suggester.add_midi(self.inputlistview.item(i).text())
        #update suggestion list
        self.suggestionlistview.clear()
        for suggestion in self._suggester.get_suggestions():
            self.suggestionlistview.addItem(QListWidgetItem(repr(suggestion)))
Exemplo n.º 53
0
class SubSheet(SimpleBlackbox):
    author = "DrLuke"
    name = "Subsheet"
    modulename = "subsheet"

    Category = ["Builtin"]

    placeable = True

    implementation = SubSheetImplementation

    def __init__(self, *args, **kwargs):
        self.ownsheet = None
        self.sheets = None
        self.selectedSheet = None
        self.listSheetItems = {}

        super(SubSheet, self).__init__(*args, **kwargs)

        self.propertiesWidget = QWidget()

        self.vlayout = QVBoxLayout()

        self.listWidget = QListWidget()
        self.listWidget.itemClicked.connect(self.listClicked)
        self.vlayout.addWidget(self.listWidget)

        self.vlayout.addItem(QSpacerItem(40, 20, QSizePolicy.Minimum, QSizePolicy.Expanding))

        self.propertiesWidget.setLayout(self.vlayout)

    def getPropertiesWidget(self):
        return self.propertiesWidget

    def updateSheets(self):
        if self.sheets is not None and self.ownsheet is not None:
            self.listSheetItems = {}
            self.listWidget.clear()
            for sheetId in self.sheets:
                if not sheetId == self.ownsheet:
                    newItem = QListWidgetItem(self.sheets[sheetId])
                    newItem.setToolTip(str(sheetId))
                    newItem.setData(Qt.UserRole, sheetId)
                    self.listSheetItems[sheetId] = newItem
                    self.listWidget.addItem(newItem)

                    if sheetId == self.selectedSheet:
                        boldFont = QFont()
                        boldFont.setBold(True)
                        newItem.setFont(boldFont)

    def listClicked(self, item):
        normalFont = QFont()
        boldFont = QFont()
        boldFont.setBold(True)

        for i in range(self.listWidget.count()):
            itemnormal = self.listWidget.item(i)
            itemnormal.setFont(normalFont)

        self.selectedSheet = item.data(Qt.UserRole)
        self.sendDataToImplementations({"subsheetid": self.selectedSheet})
        item.setFont(boldFont)

    def serialize(self):
        return {"subsheetid": self.selectedSheet}

    def deserialize(self, data):
        if data is not None:
            if "subsheetid" in data:
                self.selectedSheet = data["subsheetid"]
                self.sendDataToImplementations({"subsheetid": self.selectedSheet})

    def selectedChanged(self, state):
        if state:
            self.mainRect.setPen(QPen(Qt.red))
        else:
            self.mainRect.setPen(QPen(Qt.blue))

    def defineIO(self):
        self.addInput(execType, "execInit", "Execute Init")
        self.addInput(execType, "execLoop", "Execute Loop")

        self.addOutput(execType, "ExecInitOut", "Init Done")
        self.addOutput(execType, "ExecLoopOut", "Loop Done")
Exemplo n.º 54
0
class CollectionCueSettings(SettingsPage):
    Name = 'Edit Collection'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.setLayout(QVBoxLayout(self))

        self.cuesWidget = QListWidget(self)
        self.cuesWidget.setAlternatingRowColors(True)
        self.layout().addWidget(self.cuesWidget)

        # Buttons
        self.dialogButtons = QDialogButtonBox(self)
        self.dialogButtons.setSizePolicy(QSizePolicy.Minimum,
                                         QSizePolicy.Minimum)
        self.layout().addWidget(self.dialogButtons)

        self.addButton = self.dialogButtons.addButton('Add', QDialogButtonBox.ActionRole)
        self.addButton.clicked.connect(self._add_dialog)

        self.delButton = self.dialogButtons.addButton('Remove', QDialogButtonBox.ActionRole)
        self.delButton.clicked.connect(self._remove_selected)

        self.cue_dialog = CueListDialog(cues=Application().cue_model)
        self.cue_dialog.list.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def load_settings(self, settings):
        for target_id, action in settings.get('targets', []):
            target = Application().cue_model.get(target_id)
            if target is not None:
                self._add_cue(target, action)

    def get_settings(self):
        targets = []
        for n in range(self.cuesWidget.count()):
            widget = self.cuesWidget.itemWidget(self.cuesWidget.item(n))
            target_id, action = widget.get_target()
            targets.append((target_id, action))

        return {'targets': targets}

    def _add_cue(self, cue, action):
        item = QListWidgetItem()
        item.setSizeHint(QSize(200, 30))

        widget = CueItemWidget(cue, action, self.cue_dialog)

        self.cuesWidget.addItem(item)
        self.cuesWidget.setItemWidget(item, widget)
        self.cue_dialog.remove_cue(cue)

    def _add_dialog(self):
        if self.cue_dialog.exec_() == QDialog.Accepted:
            for target in self.cue_dialog.selected_cues():
                self._add_cue(target, tuple(target.CueActions)[0].name)

    def _remove_selected(self):
        cue = self.cuesWidget.itemWidget(self.cuesWidget.currentItem()).target

        self.cuesWidget.takeItem(self.cuesWidget.currentRow())
        self.cue_dialog.add_cue(cue)
Exemplo n.º 55
0
class SettingsDialog(QDialog):
    worker = None
    config = None
    configfile = None

    saved = QtCore.pyqtSignal()

    def __init__(self, parent, worker, config, configfile):
        QDialog.__init__(self, parent)

        self.worker = worker
        self.config = config
        self.configfile = configfile
        self.setStyleSheet("QGroupBox { font-weight: bold; } ")
        self.setWindowTitle('Settings')
        layout = QGridLayout()

        # Categories
        self.category_list = QListWidget()
        category_media = QListWidgetItem(getIcon('media-playback-start'), 'Media', self.category_list)
        category_sync = QListWidgetItem(getIcon('view-refresh'), 'Sync', self.category_list)
        category_ui = QListWidgetItem(getIcon('window-new'), 'User Interface', self.category_list)
        category_theme = QListWidgetItem(getIcon('applications-graphics'), 'Theme', self.category_list)
        self.category_list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.category_list.setCurrentRow(0)
        self.category_list.setMaximumWidth(self.category_list.sizeHintForColumn(0) + 15)
        self.category_list.setFocus()
        self.category_list.currentItemChanged.connect(self.s_switch_page)

        # Media tab
        page_media = QWidget()
        page_media_layout = QVBoxLayout()
        page_media_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Media settings
        g_media = QGroupBox('Media settings')
        g_media.setFlat(True)
        g_media_layout = QFormLayout()
        self.tracker_enabled = QCheckBox()
        self.tracker_enabled.toggled.connect(self.tracker_type_change)

        self.tracker_type = QComboBox()
        for (n, label) in utils.available_trackers:
            self.tracker_type.addItem(label, n)
        self.tracker_type.currentIndexChanged.connect(self.tracker_type_change)

        self.tracker_interval = QSpinBox()
        self.tracker_interval.setRange(5, 1000)
        self.tracker_interval.setMaximumWidth(60)
        self.tracker_process = QLineEdit()
        self.tracker_update_wait = QSpinBox()
        self.tracker_update_wait.setRange(0, 1000)
        self.tracker_update_wait.setMaximumWidth(60)
        self.tracker_update_close = QCheckBox()
        self.tracker_update_prompt = QCheckBox()
        self.tracker_not_found_prompt = QCheckBox()

        g_media_layout.addRow('Enable tracker', self.tracker_enabled)
        g_media_layout.addRow('Tracker type', self.tracker_type)
        g_media_layout.addRow('Tracker interval (seconds)', self.tracker_interval)
        g_media_layout.addRow('Process name (regex)', self.tracker_process)
        g_media_layout.addRow('Wait before updating (seconds)', self.tracker_update_wait)
        g_media_layout.addRow('Wait until the player is closed', self.tracker_update_close)
        g_media_layout.addRow('Ask before updating', self.tracker_update_prompt)
        g_media_layout.addRow('Ask to add new shows', self.tracker_not_found_prompt)

        g_media.setLayout(g_media_layout)

        # Group: Plex settings
        g_plex = QGroupBox('Plex Media Server')
        g_plex.setFlat(True)
        self.plex_host = QLineEdit()
        self.plex_port = QLineEdit()
        self.plex_user = QLineEdit()
        self.plex_passw = QLineEdit()
        self.plex_passw.setEchoMode(QLineEdit.Password)
        self.plex_obey_wait = QCheckBox()

        g_plex_layout = QGridLayout()
        g_plex_layout.addWidget(QLabel('Host and Port'),                   0, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_host,                            0, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_port,                            0, 2, 1, 2)
        g_plex_layout.addWidget(QLabel('Use "wait before updating" time'), 1, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_obey_wait,                       1, 2, 1, 1)
        g_plex_layout.addWidget(QLabel('myPlex login (claimed server)'),   2, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_user,                            2, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_passw,                           2, 2, 1, 2)

        g_plex.setLayout(g_plex_layout)

        # Group: Library
        g_playnext = QGroupBox('Library')
        g_playnext.setFlat(True)
        self.player = QLineEdit()
        self.player_browse = QPushButton('Browse...')
        self.player_browse.clicked.connect(self.s_player_browse)
        lbl_searchdirs = QLabel('Media directories')
        lbl_searchdirs.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs = QListWidget()
        self.searchdirs_add = QPushButton('Add...')
        self.searchdirs_add.clicked.connect(self.s_searchdirs_add)
        self.searchdirs_remove = QPushButton('Remove')
        self.searchdirs_remove.clicked.connect(self.s_searchdirs_remove)
        self.searchdirs_buttons = QVBoxLayout()
        self.searchdirs_buttons.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs_buttons.addWidget(self.searchdirs_add)
        self.searchdirs_buttons.addWidget(self.searchdirs_remove)
        self.searchdirs_buttons.addWidget(QSplitter())
        self.library_autoscan = QCheckBox()
        self.scan_whole_list = QCheckBox()
        self.library_full_path = QCheckBox()


        g_playnext_layout = QGridLayout()
        g_playnext_layout.addWidget(QLabel('Player'),                    0, 0, 1, 1)
        g_playnext_layout.addWidget(self.player,                         0, 1, 1, 1)
        g_playnext_layout.addWidget(self.player_browse,                  0, 2, 1, 1)
        g_playnext_layout.addWidget(lbl_searchdirs,                      1, 0, 1, 1)
        g_playnext_layout.addWidget(self.searchdirs,                     1, 1, 1, 1)
        g_playnext_layout.addLayout(self.searchdirs_buttons,             1, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Rescan Library at startup'), 2, 0, 1, 2)
        g_playnext_layout.addWidget(self.library_autoscan,               2, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Scan through whole list'),   3, 0, 1, 2)
        g_playnext_layout.addWidget(self.scan_whole_list,                3, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Take subdirectory name into account'), 4, 0, 1, 2)
        g_playnext_layout.addWidget(self.library_full_path,              4, 2, 1, 1)

        g_playnext.setLayout(g_playnext_layout)

        # Media form
        page_media_layout.addWidget(g_media)
        page_media_layout.addWidget(g_plex)
        page_media_layout.addWidget(g_playnext)
        page_media.setLayout(page_media_layout)

        # Sync tab
        page_sync = QWidget()
        page_sync_layout = QVBoxLayout()
        page_sync_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Autoretrieve
        g_autoretrieve = QGroupBox('Autoretrieve')
        g_autoretrieve.setFlat(True)
        self.autoretrieve_off = QRadioButton('Disabled')
        self.autoretrieve_always = QRadioButton('Always at start')
        self.autoretrieve_days = QRadioButton('After n days')
        self.autoretrieve_days.toggled.connect(self.s_autoretrieve_days)
        self.autoretrieve_days_n = QSpinBox()
        self.autoretrieve_days_n.setRange(1, 100)
        g_autoretrieve_layout = QGridLayout()
        g_autoretrieve_layout.setColumnStretch(0, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_off,    0, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_always, 1, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days,   2, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days_n, 2, 1, 1, 1)
        g_autoretrieve.setLayout(g_autoretrieve_layout)

        # Group: Autosend
        g_autosend = QGroupBox('Autosend')
        g_autosend.setFlat(True)
        self.autosend_off = QRadioButton('Disabled')
        self.autosend_always = QRadioButton('Immediately after every change')
        self.autosend_minutes = QRadioButton('After n minutes')
        self.autosend_minutes.toggled.connect(self.s_autosend_minutes)
        self.autosend_minutes_n = QSpinBox()
        self.autosend_minutes_n.setRange(1, 1000)
        self.autosend_size = QRadioButton('After the queue reaches n items')
        self.autosend_size.toggled.connect(self.s_autosend_size)
        self.autosend_size_n = QSpinBox()
        self.autosend_size_n.setRange(2, 20)
        self.autosend_at_exit = QCheckBox('At exit')
        g_autosend_layout = QGridLayout()
        g_autosend_layout.setColumnStretch(0, 1)
        g_autosend_layout.addWidget(self.autosend_off,      0, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_always,   1, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes,    2, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes_n,  2, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size,     3, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size_n,   3, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_at_exit,  4, 0, 1, 1)
        g_autosend.setLayout(g_autosend_layout)

        # Group: Extra
        g_extra = QGroupBox('Additional options')
        g_extra.setFlat(True)
        self.auto_status_change = QCheckBox('Change status automatically')
        self.auto_status_change.toggled.connect(self.s_auto_status_change)
        self.auto_status_change_if_scored = QCheckBox('Change status automatically only if scored')
        self.auto_date_change = QCheckBox('Change start and finish dates automatically')
        g_extra_layout = QVBoxLayout()
        g_extra_layout.addWidget(self.auto_status_change)
        g_extra_layout.addWidget(self.auto_status_change_if_scored)
        g_extra_layout.addWidget(self.auto_date_change)
        g_extra.setLayout(g_extra_layout)

        # Sync layout
        page_sync_layout.addWidget(g_autoretrieve)
        page_sync_layout.addWidget(g_autosend)
        page_sync_layout.addWidget(g_extra)
        page_sync.setLayout(page_sync_layout)

        # UI tab
        page_ui = QWidget()
        page_ui_layout = QFormLayout()
        page_ui_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Icon
        g_icon = QGroupBox('Notification Icon')
        g_icon.setFlat(True)
        self.tray_icon = QCheckBox('Show tray icon')
        self.tray_icon.toggled.connect(self.s_tray_icon)
        self.close_to_tray = QCheckBox('Close to tray')
        self.start_in_tray = QCheckBox('Start minimized to tray')
        self.tray_api_icon = QCheckBox('Use API icon as tray icon')
        self.notifications = QCheckBox('Show notification when tracker detects new media')
        g_icon_layout = QVBoxLayout()
        g_icon_layout.addWidget(self.tray_icon)
        g_icon_layout.addWidget(self.close_to_tray)
        g_icon_layout.addWidget(self.start_in_tray)
        g_icon_layout.addWidget(self.tray_api_icon)
        g_icon_layout.addWidget(self.notifications)
        g_icon.setLayout(g_icon_layout)

        # Group: Window
        g_window = QGroupBox('Window')
        g_window.setFlat(True)
        self.remember_geometry = QCheckBox('Remember window size and position')
        self.remember_columns = QCheckBox('Remember column layouts and widths')
        self.columns_per_api = QCheckBox('Use different visible columns per API')
        g_window_layout = QVBoxLayout()
        g_window_layout.addWidget(self.remember_geometry)
        g_window_layout.addWidget(self.remember_columns)
        g_window_layout.addWidget(self.columns_per_api)
        g_window.setLayout(g_window_layout)

        # Group: Lists
        g_lists = QGroupBox('Lists')
        g_lists.setFlat(True)
        self.filter_bar_position = QComboBox()
        filter_bar_positions = [(FilterBar.PositionHidden,     'Hidden'),
                                (FilterBar.PositionAboveLists, 'Above lists'),
                                (FilterBar.PositionBelowLists, 'Below lists')]
        for (n, label) in filter_bar_positions:
            self.filter_bar_position.addItem(label, n)
        self.inline_edit = QCheckBox('Enable in-line editing')
        g_lists_layout = QFormLayout()
        g_lists_layout.addRow('Filter bar position:', self.filter_bar_position)
        g_lists_layout.addRow(self.inline_edit)
        g_lists.setLayout(g_lists_layout)

        # UI layout
        page_ui_layout.addWidget(g_icon)
        page_ui_layout.addWidget(g_window)
        page_ui_layout.addWidget(g_lists)
        page_ui.setLayout(page_ui_layout)

        # Theming tab
        page_theme = QWidget()
        page_theme_layout = QFormLayout()
        page_theme_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Episode Bar
        g_ep_bar = QGroupBox('Episode Bar')
        g_ep_bar.setFlat(True)
        self.ep_bar_style = QComboBox()
        ep_bar_styles = [(ShowsTableDelegate.BarStyleBasic,  'Basic'),
                         (ShowsTableDelegate.BarStyle04,     'Trackma'),
                         (ShowsTableDelegate.BarStyleHybrid, 'Hybrid')]
        for (n, label) in ep_bar_styles:
            self.ep_bar_style.addItem(label, n)
        self.ep_bar_style.currentIndexChanged.connect(self.s_ep_bar_style)
        self.ep_bar_text = QCheckBox('Show text label')
        g_ep_bar_layout = QFormLayout()
        g_ep_bar_layout.addRow('Style:', self.ep_bar_style)
        g_ep_bar_layout.addRow(self.ep_bar_text)
        g_ep_bar.setLayout(g_ep_bar_layout)

        # Group: Colour scheme
        g_scheme = QGroupBox('Color Scheme')
        g_scheme.setFlat(True)
        col_tabs = [('rows',     '&Row highlights'),
                    ('progress', '&Progress widget')]
        self.colors = {}
        self.colors['rows'] = [('is_playing',  'Playing'),
                               ('is_queued',   'Queued'),
                               ('new_episode', 'New Episode'),
                               ('is_airing',   'Airing'),
                               ('not_aired',   'Unaired')]
        self.colors['progress'] = [('progress_bg',       'Background'),
                                   ('progress_fg',       'Watched bar'),
                                   ('progress_sub_bg',   'Aired episodes'),
                                   ('progress_sub_fg',   'Stored episodes'),
                                   ('progress_complete', 'Complete')]
        self.color_buttons = []
        self.syscolor_buttons = []
        g_scheme_layout = QGridLayout()
        tw_scheme = QTabWidget()
        for (key, tab_title) in col_tabs:
            page = QFrame()
            page_layout = QGridLayout()
            col = 0
            # Generate widgets from the keys and values
            for (key, label) in self.colors[key]:
                self.color_buttons.append(QPushButton())
                # self.color_buttons[-1].setStyleSheet('background-color: ' + getColor(self.config['colors'][key]).name())
                self.color_buttons[-1].setFocusPolicy(QtCore.Qt.NoFocus)
                self.color_buttons[-1].clicked.connect(self.s_color_picker(key, False))
                self.syscolor_buttons.append(QPushButton('System Colors'))
                self.syscolor_buttons[-1].clicked.connect(self.s_color_picker(key, True))
                page_layout.addWidget(QLabel(label),             col, 0, 1, 1)
                page_layout.addWidget(self.color_buttons[-1],    col, 1, 1, 1)
                page_layout.addWidget(self.syscolor_buttons[-1], col, 2, 1, 1)
                col += 1
            page.setLayout(page_layout)
            tw_scheme.addTab(page, tab_title)
        g_scheme_layout.addWidget(tw_scheme)
        g_scheme.setLayout(g_scheme_layout)

        # UI layout
        page_theme_layout.addWidget(g_ep_bar)
        page_theme_layout.addWidget(g_scheme)
        page_theme.setLayout(page_theme_layout)

        # Content
        self.contents = QStackedWidget()
        self.contents.addWidget(page_media)
        self.contents.addWidget(page_sync)
        self.contents.addWidget(page_ui)
        self.contents.addWidget(page_theme)
        if pyqt_version is not 5:
            self.contents.layout().setMargin(0)

        # Bottom buttons
        bottombox = QDialogButtonBox(
            QDialogButtonBox.Ok
            | QDialogButtonBox.Apply
            | QDialogButtonBox.Cancel
        )
        bottombox.accepted.connect(self.s_save)
        bottombox.button(QDialogButtonBox.Apply).clicked.connect(self._save)
        bottombox.rejected.connect(self.reject)

        # Main layout finish
        layout.addWidget(self.category_list,  0, 0, 1, 1)
        layout.addWidget(self.contents,       0, 1, 1, 1)
        layout.addWidget(bottombox,           1, 0, 1, 2)
        layout.setColumnStretch(1, 1)

        self._load()
        self.update_colors()

        self.setLayout(layout)

    def _add_dir(self, path):
        self.searchdirs.addItem(path)

    def _load(self):
        engine = self.worker.engine
        tracker_type = self.tracker_type.findData(engine.get_config('tracker_type'))
        autoretrieve = engine.get_config('autoretrieve')
        autosend = engine.get_config('autosend')

        self.tracker_enabled.setChecked(engine.get_config('tracker_enabled'))
        self.tracker_type.setCurrentIndex(max(0, tracker_type))
        self.tracker_interval.setValue(engine.get_config('tracker_interval'))
        self.tracker_process.setText(engine.get_config('tracker_process'))
        self.tracker_update_wait.setValue(engine.get_config('tracker_update_wait_s'))
        self.tracker_update_close.setChecked(engine.get_config('tracker_update_close'))
        self.tracker_update_prompt.setChecked(engine.get_config('tracker_update_prompt'))
        self.tracker_not_found_prompt.setChecked(engine.get_config('tracker_not_found_prompt'))

        self.player.setText(engine.get_config('player'))
        self.library_autoscan.setChecked(engine.get_config('library_autoscan'))
        self.scan_whole_list.setChecked(engine.get_config('scan_whole_list'))
        self.library_full_path.setChecked(engine.get_config('library_full_path'))
        self.plex_host.setText(engine.get_config('plex_host'))
        self.plex_port.setText(engine.get_config('plex_port'))
        self.plex_obey_wait.setChecked(engine.get_config('plex_obey_update_wait_s'))
        self.plex_user.setText(engine.get_config('plex_user'))
        self.plex_passw.setText(engine.get_config('plex_passwd'))

        for path in engine.get_config('searchdir'):
            self._add_dir(path)

        if autoretrieve == 'always':
            self.autoretrieve_always.setChecked(True)
        elif autoretrieve == 'days':
            self.autoretrieve_days.setChecked(True)
        else:
            self.autoretrieve_off.setChecked(True)

        self.autoretrieve_days_n.setValue(engine.get_config('autoretrieve_days'))

        if autosend == 'always':
            self.autosend_always.setChecked(True)
        elif autosend in ('minutes', 'hours'):
            self.autosend_minutes.setChecked(True)
        elif autosend == 'size':
            self.autosend_size.setChecked(True)
        else:
            self.autosend_off.setChecked(True)

        self.autosend_minutes_n.setValue(engine.get_config('autosend_minutes'))
        self.autosend_size_n.setValue(engine.get_config('autosend_size'))

        self.autosend_at_exit.setChecked(engine.get_config('autosend_at_exit'))
        self.auto_status_change.setChecked(engine.get_config('auto_status_change'))
        self.auto_status_change_if_scored.setChecked(engine.get_config('auto_status_change_if_scored'))
        self.auto_date_change.setChecked(engine.get_config('auto_date_change'))

        self.tray_icon.setChecked(self.config['show_tray'])
        self.close_to_tray.setChecked(self.config['close_to_tray'])
        self.start_in_tray.setChecked(self.config['start_in_tray'])
        self.tray_api_icon.setChecked(self.config['tray_api_icon'])
        self.notifications.setChecked(self.config['notifications'])
        self.remember_geometry.setChecked(self.config['remember_geometry'])
        self.remember_columns.setChecked(self.config['remember_columns'])
        self.columns_per_api.setChecked(self.config['columns_per_api'])
        self.filter_bar_position.setCurrentIndex(self.filter_bar_position.findData(self.config['filter_bar_position']))
        self.inline_edit.setChecked(self.config['inline_edit'])

        self.ep_bar_style.setCurrentIndex(self.ep_bar_style.findData(self.config['episodebar_style']))
        self.ep_bar_text.setChecked(self.config['episodebar_text'])

        self.autoretrieve_days_n.setEnabled(self.autoretrieve_days.isChecked())
        self.autosend_minutes_n.setEnabled(self.autosend_minutes.isChecked())
        self.autosend_size_n.setEnabled(self.autosend_size.isChecked())
        self.close_to_tray.setEnabled(self.tray_icon.isChecked())
        self.start_in_tray.setEnabled(self.tray_icon.isChecked())
        self.notifications.setEnabled(self.tray_icon.isChecked())

        self.color_values = self.config['colors'].copy()

        self.tracker_type_change(None)

    def _save(self):
        engine = self.worker.engine

        engine.set_config('tracker_enabled',       self.tracker_enabled.isChecked())
        engine.set_config('tracker_type',          self.tracker_type.itemData(self.tracker_type.currentIndex()))
        engine.set_config('tracker_interval',      self.tracker_interval.value())
        engine.set_config('tracker_process',       str(self.tracker_process.text()))
        engine.set_config('tracker_update_wait_s', self.tracker_update_wait.value())
        engine.set_config('tracker_update_close',  self.tracker_update_close.isChecked())
        engine.set_config('tracker_update_prompt', self.tracker_update_prompt.isChecked())
        engine.set_config('tracker_not_found_prompt', self.tracker_not_found_prompt.isChecked())

        engine.set_config('player',            self.player.text())
        engine.set_config('library_autoscan',  self.library_autoscan.isChecked())
        engine.set_config('scan_whole_list', self.scan_whole_list.isChecked())
        engine.set_config('library_full_path', self.library_full_path.isChecked())
        engine.set_config('plex_host',         self.plex_host.text())
        engine.set_config('plex_port',         self.plex_port.text())
        engine.set_config('plex_obey_update_wait_s', self.plex_obey_wait.isChecked())
        engine.set_config('plex_user',         self.plex_user.text())
        engine.set_config('plex_passwd',       self.plex_passw.text())

        engine.set_config('searchdir',         [self.searchdirs.item(i).text() for i in range(self.searchdirs.count())])

        if self.autoretrieve_always.isChecked():
            engine.set_config('autoretrieve', 'always')
        elif self.autoretrieve_days.isChecked():
            engine.set_config('autoretrieve', 'days')
        else:
            engine.set_config('autoretrieve', 'off')

        engine.set_config('autoretrieve_days',   self.autoretrieve_days_n.value())

        if self.autosend_always.isChecked():
            engine.set_config('autosend', 'always')
        elif self.autosend_minutes.isChecked():
            engine.set_config('autosend', 'minutes')
        elif self.autosend_size.isChecked():
            engine.set_config('autosend', 'size')
        else:
            engine.set_config('autosend', 'off')

        engine.set_config('autosend_minutes', self.autosend_minutes_n.value())
        engine.set_config('autosend_size',  self.autosend_size_n.value())

        engine.set_config('autosend_at_exit',   self.autosend_at_exit.isChecked())
        engine.set_config('auto_status_change', self.auto_status_change.isChecked())
        engine.set_config('auto_status_change_if_scored', self.auto_status_change_if_scored.isChecked())
        engine.set_config('auto_date_change',   self.auto_date_change.isChecked())

        engine.save_config()

        self.config['show_tray'] = self.tray_icon.isChecked()
        self.config['close_to_tray'] = self.close_to_tray.isChecked()
        self.config['start_in_tray'] = self.start_in_tray.isChecked()
        self.config['tray_api_icon'] = self.tray_api_icon.isChecked()
        self.config['notifications'] = self.notifications.isChecked()
        self.config['remember_geometry'] = self.remember_geometry.isChecked()
        self.config['remember_columns'] = self.remember_columns.isChecked()
        self.config['columns_per_api'] = self.columns_per_api.isChecked()
        self.config['filter_bar_position'] = self.filter_bar_position.itemData(self.filter_bar_position.currentIndex())
        self.config['inline_edit'] = self.inline_edit.isChecked()

        self.config['episodebar_style'] = self.ep_bar_style.itemData(self.ep_bar_style.currentIndex())
        self.config['episodebar_text'] = self.ep_bar_text.isChecked()

        self.config['colors'] = self.color_values

        utils.save_config(self.config, self.configfile)

        self.saved.emit()

    def s_save(self):
        self._save()
        self.accept()

    def tracker_type_change(self, checked):
        if self.tracker_enabled.isChecked():
            self.tracker_interval.setEnabled(True)
            self.tracker_update_wait.setEnabled(True)
            self.tracker_type.setEnabled(True)
            if self.tracker_type.itemData(self.tracker_type.currentIndex()) == 'plex':
                self.plex_host.setEnabled(True)
                self.plex_port.setEnabled(True)
                self.plex_obey_wait.setEnabled(True)
                self.plex_user.setEnabled(True)
                self.plex_passw.setEnabled(True)
                self.tracker_process.setEnabled(False)
            else:
                self.tracker_process.setEnabled(True)
                self.plex_host.setEnabled(False)
                self.plex_port.setEnabled(False)
                self.plex_user.setEnabled(False)
                self.plex_passw.setEnabled(False)
                self.plex_obey_wait.setEnabled(False)
        else:
            self.tracker_type.setEnabled(False)
            self.plex_host.setEnabled(False)
            self.plex_port.setEnabled(False)
            self.plex_user.setEnabled(False)
            self.plex_passw.setEnabled(False)
            self.plex_obey_wait.setEnabled(False)
            self.tracker_process.setEnabled(False)
            self.tracker_interval.setEnabled(False)
            self.tracker_update_wait.setEnabled(False)

    def s_autoretrieve_days(self, checked):
        self.autoretrieve_days_n.setEnabled(checked)

    def s_autosend_minutes(self, checked):
        self.autosend_minutes_n.setEnabled(checked)

    def s_autosend_size(self, checked):
        self.autosend_size_n.setEnabled(checked)

    def s_tray_icon(self, checked):
        self.close_to_tray.setEnabled(checked)
        self.start_in_tray.setEnabled(checked)
        self.tray_api_icon.setEnabled(checked)
        self.notifications.setEnabled(checked)

    def s_ep_bar_style(self, index):
        if self.ep_bar_style.itemData(index) == ShowsTableDelegate.BarStyle04:
            self.ep_bar_text.setEnabled(False)
        else:
            self.ep_bar_text.setEnabled(True)

    def s_auto_status_change(self, checked):
        self.auto_status_change_if_scored.setEnabled(checked)

    def s_player_browse(self):
        if pyqt_version is 5:
            self.player.setText(QFileDialog.getOpenFileName(caption='Choose player executable')[0])
        else:
            self.player.setText(QFileDialog.getOpenFileName(caption='Choose player executable'))

    def s_searchdirs_add(self):
        self._add_dir(QFileDialog.getExistingDirectory(caption='Choose media directory'))

    def s_searchdirs_remove(self):
        row = self.searchdirs.currentRow()
        if row != -1:
            self.searchdirs.takeItem(row)

    def s_switch_page(self, new, old):
        if not new:
            new = old

        self.contents.setCurrentIndex(self.category_list.row(new))

    def s_color_picker(self, key, system):
        return lambda: self.color_picker(key, system)

    def color_picker(self, key, system):
        if system is True:
            current = self.color_values[key]
            result = ThemedColorPicker.do()
            if result is not None and result is not current:
                self.color_values[key] = result
                self.update_colors()
        else:
            current = getColor(self.color_values[key])
            result = QColorDialog.getColor(current)
            if result.isValid() and result is not current:
                self.color_values[key] = str(result.name())
                self.update_colors()

    def update_colors(self):
        for ((key, label), color) in zip(self.colors['rows']+self.colors['progress'], self.color_buttons):
            color.setStyleSheet('background-color: ' + getColor(self.color_values[key]).name())
Exemplo n.º 56
0
class AdremoverSettingsPanel(SettingsPanel):
    def __init__(self, parent=None):
        super(AdremoverSettingsPanel, self).__init__(parent)

        filterEntryRow = custom_widgets.LineEditRow(tr("Add filter:"), self)
        self.filterEntry = filterEntryRow.lineEdit
        self.filterEntry.returnPressed.connect(self.addFilter)
        self.layout().addWidget(filterEntryRow)

        self.addFilterButton = QPushButton(tr("Add"))
        self.addFilterButton.clicked.connect(self.addFilter)
        filterEntryRow.layout().addWidget(self.addFilterButton)

        # Ad Remover filter list.
        self.filterList = QListWidget(self)
        self.layout().addWidget(self.filterList)

        self.removeFilterButton = QPushButton(tr("Remove"))
        self.removeFilterButton.clicked.connect(lambda: self.removeFilter(True))
        self.layout().addWidget(self.removeFilterButton)

        self.removeAction = QAction(self)
        self.removeAction.setShortcut("Del")
        self.removeAction.triggered.connect(self.removeFilter)
        self.addAction(self.removeAction)

    def removeFilter(self, forceFocus=False):
        if self.filterList.hasFocus() or forceFocus:
            self.filterList.takeItem(self.filterList.row(self.filterList.currentItem()))

    def addFilter(self):
        self.filterList.addItem(self.filterEntry.text())
        self.filterEntry.clear()

    def loadSettings(self):
        settings.load_adremover_filters()
        self.filterList.clear()
        for f in settings.adremover_filters:
            self.filterList.addItem(f)

    def saveSettings(self):
        settings.adremover_filters = [self.filterList.item(f).text() for f in range(0, self.filterList.count())]
        settings.save_adremover_filters()
Exemplo n.º 57
0
class DebuggerMainWindow(object):
    def __init__(self, comm):
        self.comm = comm
        self.follow_state = True
        self.init_instances()
        self.init_widgets()
        self.init_actions()
        self.window.closeEvent = self.close_handler
        self.window.showMaximized()

    def run(self):
        self.poll_timer = QTimer()
        self.poll_timer.timeout.connect(self.poll_handler)
        self.comm.start_worker()
        self.poll_timer.start(1000)

    def poll_handler(self):
        self.comm.put_job(self.comm.get_agent_track)
        data = self.comm.take_data()
        for location_info, state in data:
            file_name, node_id = location_info
            i = self.get_instance(file_name)

            if i is None:
                text = "%s:%s" % (str(location_info), state)
            else:
                node = i.model.get_node(node_id)
                if node is not None:
                    text = "%s: %s: %s" % (file_name, node.get_display_text(), state)
                else:
                    text = "%s:%s" % (str(location_info), state)
            self.add_to_history_list(location_info, text)
        if self.follow_state:
            self.focus_last()

    def init_widgets(self):
        self.window = loadUi(MAIN_UI_PATH)
        self.mdi = self.window.mdiArea
        self.mdi.setViewMode(QMdiArea.TabbedView)
        self.mdi.setTabsMovable(True)
        self.mdi.setTabsClosable(True)
        self.mdi.setTabShape(QTabWidget.Rounded)
        self.dock_anchor = self.window.dockAnchor
        self.dock_anchor.layout().setAlignment(Qt.AlignTop)

        self.history_list = QListWidget()
        self.history_list.itemSelectionChanged.connect(self.list_item_selected)
        self.add_dock_content(self.history_list)

    def list_item_selected(self):
        citem = self.history_list.currentItem()
        self.focus_on_location(citem.location_info)

    def init_instances(self):
        self.instances = {}

    def remove_instance(self, ins):
        file_name = ins.file_name
        self.instances.pop(file_name)

    def add_instance(self, ins):
        file_name = ins.file_name
        self.instances[file_name] = ins

    def get_instance(self, file_name):
        if file_name in self.instances:
            return self.instances[file_name]
        else:
            full_path = GraphInstanceVM.get_full_path(file_name)
            model = GraphInstanceVM.get_model(full_path)
            if model is None:
                return None
            ins = GraphInstanceVM(model, self, file_name)
            return ins

    def init_actions(self):
        self.window.actionResume.triggered.connect(self.action_resume_handler)
        self.window.actionStop.triggered.connect(self.action_stop_handler)
        self.window.actionFollow.triggered.connect(self.action_follow_handler)
        self.window.actionHold.triggered.connect(self.action_hold_handler)

    def action_resume_handler(self):
        self.clear_list()
        self.comm.put_job(functools.partial(self.comm.track_agent, True))

    def action_stop_handler(self):
        self.comm.put_job(functools.partial(self.comm.track_agent, False))

    def action_follow_handler(self):
        self.follow_state = True

    def action_hold_handler(self):
        self.follow_state = False

    def close_handler(self, ev):
        # disable tracking for some agents
        self.poll_timer.stop()
        self.comm.put_job(self.comm.finish)
        self.comm.shutdown()

    def add_dock_content(self, widget):
        self.clear_dock_contents()
        self.dock_anchor.layout().addWidget(widget)

    def get_dock_contents(self):
        l = self.dock_anchor.layout()
        ret = []
        for i in range(l.count()):
            ret.append(l.itemAt(i).widget())
        return ret

    def clear_dock_contents(self):
        ws = self.get_dock_contents()
        for w in ws:
            w.deleteLater()

    def focus_on_location(self, location):
        file_name, node_id = location
        instance = self.get_instance(file_name)
        if instance is None:
            logger.fatal("can not find src file for %s" % file_name)
            return False
        ret = instance.focus_on(node_id)
        if ret is False:
            logger.fatal("can not find node %s for %s" % (node_id, file_name))
            return False
        return True

    def add_to_history_list(self, location, text):
        item = HistoryListItem(location, text)
        self.history_list.addItem(item)

    def clear_list(self):
        self.history_list.clear()

    def focus_last(self):
        c = self.history_list.count()
        if c > 0:
            item = self.history_list.item(c-1)
            self.history_list.setCurrentItem(item)
            self.focus_on_location(item.location_info)
Exemplo n.º 58
0
class SelectedLinesWidget(QWidget):
    """ Widget to show and enable lines to be selected
    inp : LineList
      Input LineList
    init_select : str or list of indices
      str -- 'All'

    """
    def __init__(self, inp, parent=None, init_select=None, plot_widget=None):
        """
        """
        super(SelectedLinesWidget, self).__init__(parent)

        self.parent=parent

        # Line list Table
        if isinstance(inp, LineList):
            self.lines = inp._data
            self.llst = inp
        elif isinstance(inp,Table):
            raise ValueError('SelectedLineWidget: DEPRECATED')
        else:
            raise ValueError('SelectedLineWidget: Wrong type of input')

        self.plot_widget = plot_widget

        # Create the line list
        line_label = QLabel('Lines:')
        self.lines_widget = QListWidget(self)
        self.lines_widget.setSelectionMode(QAbstractItemView.MultiSelection)

        # Initialize list
        self.item_flg = 0
        self.init_list()

        # Initial selection
        if init_select is None:
            self.selected = [0]
        elif init_select == 'All':
            self.selected = []
            for ii in range(self.lines_widget.count()):
                self.lines_widget.item(ii).setSelected(True)
                self.selected.append(ii)
        else:
            self.selected = init_select
            if len(self.selected) == 0:
                self.selected = [0]

        for iselect in self.selected:
            self.lines_widget.item(iselect).setSelected(True)

        self.lines_widget.scrollToItem( self.lines_widget.item( self.selected[0] ) )

        # Events
        self.lines_widget.itemSelectionChanged.connect(self.on_item_change)

        # Layout
        vbox = QVBoxLayout()
        vbox.addWidget(line_label)
        vbox.addWidget(self.lines_widget)

        self.setLayout(vbox)

    def init_list(self):
        nlin = len(self.lines['wrest'])
        for ii in range(nlin):
            self.lines_widget.addItem('{:s} :: {:.3f} :: {}'.format(self.lines['name'][ii],
                                                         self.lines['wrest'][ii].value,
                                                         self.lines['f'][ii]))

    def on_item_change(self): #,item):
        # For big changes
        if self.item_flg == 1:
            return
        all_items = [self.lines_widget.item(ii) for ii in range(self.lines_widget.count())]
        sel_items = self.lines_widget.selectedItems()
        self.selected = [all_items.index(isel) for isel in sel_items]
        self.selected.sort()

        #QtCore.pyqtRemoveInputHook()
        #xdb.set_trace()
        #QtCore.pyqtRestoreInputHook()

        # Update llist
        try:
            self.plot_widget.llist['show_line'] = self.selected
        except AttributeError:
            if self.parent is not None:
                self.parent.updated_slines(self.selected)
            return
        else:
            self.plot_widget.on_draw()

    def on_list_change(self, llist):
        # Clear
        if not isinstance(llist, LineList):
            raise ValueError('Expecting LineList!!')
        self.item_flg = 1
        self.lines = llist._data
        self.llst = llist
        self.lines_widget.clear()
        # Initialize
        self.init_list()
        # Set selected
        for iselect in self.selected:
            self.lines_widget.item(iselect).setSelected(True)
        self.lines_widget.scrollToItem(self.lines_widget.item(self.selected[0]))
        self.item_flg = 0
Exemplo n.º 59
0
class GlyphSetTab(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.name = self.tr("Glyph sets")

        self.defaultGlyphSetBox = QCheckBox(
            self.tr("Default glyph set:"), self)
        self.defaultGlyphSetDrop = QComboBox(self)
        self.defaultGlyphSetBox.toggled.connect(self.toggleGlyphSetDrop)

        self.glyphSetList = QListWidget(self)
        self.glyphSetList.setSortingEnabled(True)
        self.glyphSetContents = QPlainTextEdit(self)
        self.glyphSetList.currentItemChanged.connect(
            self.updateGlyphSetContents)
        self.glyphSetList.itemChanged.connect(self.renameGlyphSet)
        self._cachedName = None
        splitter = QSplitter(self)
        splitter.addWidget(self.glyphSetList)
        splitter.addWidget(self.glyphSetContents)
        self.addGlyphSetButton = QPushButton("+", self)
        self.addGlyphSetButton.clicked.connect(lambda: self.addGlyphSet())
        self.removeGlyphSetButton = QPushButton("−", self)
        self.removeGlyphSetButton.clicked.connect(self.removeGlyphSet)
        self.importButton = QPushButton(self.tr("Import"), self)
        importMenu = QMenu(self)
        importMenu.addAction(
            self.tr("Import from current font"), self.importFromCurrentFont)
        self.importButton.setMenu(importMenu)
        self.glyphListBox = QCheckBox(self.tr("Glyph list path:"), self)
        self.glyphListEdit = QLineEdit(self)
        self.glyphListEdit.setReadOnly(True)
        self.glyphListButton = QPushButton(self.tr("Browse…"), self)
        self.glyphListButton.clicked.connect(self.getGlyphList)
        # TODO: find correct solution for this and maybe make a widget w
        # setSizesToText()
        # http://stackoverflow.com/a/19502467/2037879
        textWidth = self.glyphListButton.fontMetrics().boundingRect(
            self.glyphListButton.text()).width() + 16
        self.glyphListButton.setMaximumWidth(textWidth)
        self.glyphListBox.toggled.connect(self.glyphListEdit.setEnabled)
        self.glyphListBox.toggled.connect(self.glyphListButton.setEnabled)

        firstLayout = QGridLayout()
        l = 0
        firstLayout.addWidget(self.defaultGlyphSetBox, l, 0, 1, 2)
        firstLayout.addWidget(self.defaultGlyphSetDrop, l, 3, 1, 3)
        l += 1
        firstLayout.addWidget(splitter, l, 0, 1, 6)
        l += 1
        firstLayout.addWidget(self.addGlyphSetButton, l, 0)
        firstLayout.addWidget(self.removeGlyphSetButton, l, 1)
        firstLayout.addWidget(self.importButton, l, 2)
        secondLayout = QHBoxLayout()
        secondLayout.addWidget(self.glyphListBox, 0)
        secondLayout.addWidget(self.glyphListEdit, 1)
        secondLayout.addWidget(self.glyphListButton, 2)
        mainLayout = QVBoxLayout(self)
        mainLayout.addLayout(firstLayout)
        mainLayout.addLayout(secondLayout)
        self.setLayout(mainLayout)

        self.readSettings()

    def addGlyphSet(self, glyphNames=[], glyphSetName=None):
        if glyphSetName is None:
            glyphSetName = self.tr("New glyph set")
        if glyphSetName in self.glyphSets:
            index = 1
            while "%s %d" % (glyphSetName, index) in self.glyphSets:
                index += 1
            glyphSetName = "%s %d" % (glyphSetName, index)
        self.glyphSets[glyphSetName] = glyphNames
        item = QListWidgetItem(glyphSetName, self.glyphSetList)
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self.glyphSetList.setCurrentItem(item)
        self.glyphSetList.editItem(item)
        self.removeGlyphSetButton.setEnabled(True)

    def removeGlyphSet(self):
        i = self.glyphSetList.currentRow()
        text = self.glyphSetList.takeItem(i).text()
        del self.glyphSets[text]
        if self.glyphSetList.count() < 2:
            self.removeGlyphSetButton.setEnabled(False)

    def renameGlyphSet(self):
        newKey = self.glyphSetList.currentItem()
        if newKey is None:
            return
        newKey = newKey.text()
        self.glyphSets[newKey] = self.glyphSets[self._cachedName]
        del self.glyphSets[self._cachedName]

    def importFromCurrentFont(self):
        font = QApplication.instance().currentFont()
        name = "%s %s" % (font.info.familyName, font.info.styleName)
        self.addGlyphSet(font.glyphOrder, name)

    def toggleGlyphSetDrop(self):
        sender = self.sender()
        self.defaultGlyphSetDrop.setEnabled(sender.isChecked())

    def updateGlyphSetContents(self, current, previous):
        # store content of the textEdit in the glyphSet dict
        if previous is not None:
            glyphNames = self.glyphSetContents.toPlainText().split()
            self.glyphSets[previous.text()] = glyphNames
        # now update the text edit to current glyphSet
        glyphSetName = current.text()
        text = " ".join(self.glyphSets[glyphSetName])
        self.glyphSetContents.setPlainText(text)
        # cache current name for renames
        self._cachedName = glyphSetName

    def getGlyphList(self):
        fileFormats = (
            self.tr("Text file {}").format("(*.txt)"),
            self.tr("All files {}").format("(*.*)"),
        )
        path, _ = QFileDialog.getOpenFileName(
            self, self.tr("Open File"), '', ";;".join(fileFormats)
        )
        if path:
            self.glyphListEdit.setText(path)

    def readSettings(self):
        defaultGlyphSet = settings.defaultGlyphSet()
        self.defaultGlyphSetBox.setChecked(len(defaultGlyphSet))

        self.glyphSets = settings.readGlyphSets()
        self.defaultGlyphSetDrop.clear()
        self.defaultGlyphSetDrop.addItems(self.glyphSets.keys())

        self.glyphSetList.clear()
        glyphSetNames = self.glyphSets.keys()
        # Normally we should be enforcing this rather decently in the interface
        # already
        if glyphSetNames:
            for glyphSetName in glyphSetNames:
                item = QListWidgetItem(glyphSetName, self.glyphSetList)
                item.setFlags(item.flags() | Qt.ItemIsEditable)
            self.glyphSetList.setCurrentRow(0)
        self.removeGlyphSetButton.setEnabled(len(self.glyphSets) > 1)

        glyphListPath = settings.glyphListPath()
        self.glyphListBox.setChecked(bool(glyphListPath))
        self.glyphListEdit.setEnabled(bool(glyphListPath))
        self.glyphListEdit.setText(glyphListPath)
        self.glyphListButton.setEnabled(bool(glyphListPath))

    def writeSettings(self):
        # store content of the textEdit in the glyphSet dict
        glyphNames = self.glyphSetContents.toPlainText().split()
        currentGlyphSet = self.glyphSetList.currentItem().text()
        self.glyphSets[currentGlyphSet] = glyphNames

        settings.writeGlyphSets(self.glyphSets)
        if not self.defaultGlyphSetBox.isChecked():
            settings.setDefaultGlyphSet(None)
        else:
            defaultGlyphSet = self.defaultGlyphSetDrop.currentText()
            settings.setDefaultGlyphSet(defaultGlyphSet)
        if not self.glyphListBox.isChecked():
            settings.setGlyphListPath(None)
        else:
            glyphListPath = self.glyphListEdit.text()
            if glyphListPath:
                settings.setGlyphListPath(glyphListPath)
                QApplication.instance().loadGlyphList()
Exemplo n.º 60
0
class CityListDlg(QDialog):
    citieslist_signal = pyqtSignal([list])
    citiesdict_signal = pyqtSignal([dict])

    def __init__(
        self, citylist, accurate_url, appid, trans_cities_dict, parent=None
    ):
        super(CityListDlg, self).__init__(parent)
        self.settings = QSettings()
        self.citylist = citylist
        self.trans_cities_dict = trans_cities_dict
        self.accurate_url = accurate_url
        self.appid = appid
        self.listWidget = QListWidget()
        self.listWidget.itemDoubleClicked.connect(self.translate)
        cities_list = []
        for i in self.citylist:
            cities_list.append(self.trans_cities_dict.get(i, i))
        self.listWidget.addItems(cities_list)
        buttonLayout = QVBoxLayout()
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.accepted.connect(self.accept)
        layoutT = QVBoxLayout()
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        for text, slot in ((self.tr("&Add..."), self.add),
                           (self.tr("&Remove..."), self.remove),
                           (self.tr("&Up"), self.up),
                           (self.tr("&Down"), self.down),
                           (self.tr("De&fault"), self.default),
                           (self.tr("&Sort"), self.listWidget.sortItems)):
            button = QPushButton(text)
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
        self.translate_button = QPushButton(
            QCoreApplication.translate(
                'Button',
                '&Translate',
                'Edit cities name'
            )
        )
        buttonLayout.addWidget(self.translate_button)
        self.translate_button.clicked.connect(self.translate)
        buttonLayout.addWidget(self.buttonBox)
        self.status = QLabel()
        layoutT.addLayout(layout)
        layoutT.addWidget(self.status)
        self.setLayout(layoutT)
        self.setWindowTitle(
            QCoreApplication.translate(
                'Window title',
                'Cities',
                'Cities list dialogue'
            )
        )
        self.checklength()

    def add(self):
        self.status.setText('')
        lista = []
        newitem = ''
        self.citytoadd = ''
        self.countrytoadd = ''
        self._idtoadd = ''
        dialog = searchcity.SearchCity(self.accurate_url, self.appid, self)
        dialog.id_signal.connect(self.addcity)
        dialog.city_signal.connect(self.addcity)
        dialog.country_signal.connect(self.addcity)
        if dialog.exec_() == 1:
            newitem = (
                self.citytoadd + '_' + self.countrytoadd
                + '_' + self._idtoadd
            )
            for row in range(self.listWidget.count()):
                lista.append(self.listWidget.item(row).text())
            if newitem in lista:
                self.status.setText(
                    QCoreApplication.translate(
                        'Status bar message',
                        'The city already exists in the list',
                        'Cities list dialogue'
                    )
                )
                return
            else:
                self.listWidget.addItem(newitem)
                self.checklength()
                self.status.setText(
                    'ℹ ' + QCoreApplication.translate(
                        'Status bar message',
                        'Toggle cities with mouse scroll on the weather window',
                        'Cities list dialogue'
                    )
                )

    def addcity(self, what):
        self.status.setText('')
        if what[0] == 'ID':
            self._idtoadd = what[1]
        elif what[0] == 'City':
            self.citytoadd = what[1]
        elif what[0] == 'Country':
            self.countrytoadd = what[1]

    def remove(self):
        self.status.setText('')
        if self.listWidget.count() == 1:
            self.status.setText(
                QCoreApplication.translate(
                    'Message when trying to remove the'
                    'last and unique city in the list',
                    'This is the default city !',
                    'Cities list dialogue'
                )
            )
            return
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        message = self.tr('The city "{0}" has been removed').format(
            self.listWidget.item(row).text())
        item = self.listWidget.takeItem(row)
        del item
        self.status.setText(message)

    def up(self):
        self.status.setText('')
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentItem(item)

    def down(self):
        self.status.setText('')
        row = self.listWidget.currentRow()
        if row < self.listWidget.count() - 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentItem(item)

    def default(self):
        self.status.setText('')
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(0, item)
            self.listWidget.setCurrentItem(item)

    def checklength(self):
        if self.listWidget.count() == 1:
            # After adding the first city the entry is not activated
            self.listWidget.setCurrentRow(0)
        if self.listWidget.count() > 0:
            self.translate_button.setEnabled(True)
            self.listWidget.setMinimumWidth(
                self.listWidget.sizeHintForColumn(0)
            )
        else:
            self.translate_button.setEnabled(False)

    def translate(self):
        city = self.listWidget.currentItem().text()
        dialog = citytranslate.CityTranslate(
            city, self.trans_cities_dict, self
        )
        dialog.city_signal.connect(self.current_translation)
        if dialog.exec_() == 1:
            row = self.listWidget.currentRow()
            item = self.listWidget.takeItem(row)
            del item
            self.listWidget.insertItem(row, self.current_translated_city)
            self.listWidget.setCurrentRow(row)

    def current_translation(self, translated_city):
        for city, translated in translated_city.items():
            if translated == '':
                translated = city
            self.trans_cities_dict[city] = translated
            self.current_translated_city = translated

    def accept(self):
        listtosend = []
        for row in range(self.listWidget.count()):
            city = self.find_city_key(self.listWidget.item(row).text())
            listtosend.append(city)
        if self.listWidget.count() == 0:
            return
        self.citieslist_signal[list].emit(listtosend)
        self.citiesdict_signal[dict].emit(self.trans_cities_dict)
        QDialog.accept(self)

    def find_city_key(self, city):
        for key, value in self.trans_cities_dict.items():
            if value == city:
                return key
        return city