예제 #1
1
class ParamSpinBox(QAbstractSpinBox):
    # signals
    valueChanged = pyqtSignal(float)

    def __init__(self, parent):
        QAbstractSpinBox.__init__(self, parent)

        self.fName = ""

        self.fMinimum = 0.0
        self.fMaximum = 1.0
        self.fDefault = 0.0
        self.fValue   = None

        self.fStep      = 0.01
        self.fStepSmall = 0.0001
        self.fStepLarge = 0.1

        self.fIsReadOnly = False
        self.fScalePoints = None
        self.fUseScalePoints = False

        self.fBar = ParamProgressBar(self)
        self.fBar.setContextMenuPolicy(Qt.NoContextMenu)
        #self.fBar.show()

        self.fBox = None

        self.lineEdit().hide()

        self.customContextMenuRequested.connect(self.slot_showCustomMenu)
        self.fBar.valueChanged.connect(self.slot_progressBarValueChanged)

        QTimer.singleShot(0, self.slot_updateProgressBarGeometry)

    def setDefault(self, value):
        value = geFixedValue(self.fName, value, self.fMinimum, self.fMaximum)
        self.fDefault = value

    def setMinimum(self, value):
        self.fMinimum = value
        self.fBar.setMinimum(value)

    def setMaximum(self, value):
        self.fMaximum = value
        self.fBar.setMaximum(value)

    def setValue(self, value):
        value = geFixedValue(self.fName, value, self.fMinimum, self.fMaximum)

        if self.fValue == value:
            return False

        self.fValue = value
        self.fBar.setValue(value)

        if self.fUseScalePoints:
            self._setScalePointValue(value)

        self.valueChanged.emit(value)
        self.update()

        return True

    def setStep(self, value):
        if value == 0.0:
            self.fStep = 0.001
        else:
            self.fStep = value

        if self.fStepSmall > value:
            self.fStepSmall = value
        if self.fStepLarge < value:
            self.fStepLarge = value

        self.fBar.fIsInteger = bool(self.fStepSmall == 1.0)

    def setStepSmall(self, value):
        if value == 0.0:
            self.fStepSmall = 0.0001
        elif value > self.fStep:
            self.fStepSmall = self.fStep
        else:
            self.fStepSmall = value

        self.fBar.fIsInteger = bool(self.fStepSmall == 1.0)

    def setStepLarge(self, value):
        if value == 0.0:
            self.fStepLarge = 0.1
        elif value < self.fStep:
            self.fStepLarge = self.fStep
        else:
            self.fStepLarge = value

    def setLabel(self, label):
        self.fBar.setLabel(label)

    def setName(self, name):
        self.fName = name
        self.fBar.setName(name)

    def setTextCallback(self, textCall):
        self.fBar.setTextCall(textCall)

    def setReadOnly(self, yesNo):
        self.fIsReadOnly = yesNo
        self.setButtonSymbols(QAbstractSpinBox.UpDownArrows if yesNo else QAbstractSpinBox.NoButtons)
        QAbstractSpinBox.setReadOnly(self, yesNo)

    # FIXME use change event
    def setEnabled(self, yesNo):
        self.fBar.setEnabled(yesNo)
        QAbstractSpinBox.setEnabled(self, yesNo)

    def setScalePoints(self, scalePoints, useScalePoints):
        if len(scalePoints) == 0:
            self.fScalePoints     = None
            self.fUseScalePoints = False
            return

        self.fScalePoints     = scalePoints
        self.fUseScalePoints = useScalePoints

        if not useScalePoints:
            return

        # Hide ProgressBar and create a ComboBox
        self.fBar.close()
        self.fBox = QComboBox(self)
        self.fBox.setContextMenuPolicy(Qt.NoContextMenu)
        #self.fBox.show()
        self.slot_updateProgressBarGeometry()

        # Add items, sorted
        boxItemValues = []

        for scalePoint in scalePoints:
            value = scalePoint['value']

            if self.fStep == 1.0:
                label = "%i - %s" % (int(value), scalePoint['label'])
            else:
                label = "%f - %s" % (value, scalePoint['label'])

            if len(boxItemValues) == 0:
                self.fBox.addItem(label)
                boxItemValues.append(value)

            else:
                if value < boxItemValues[0]:
                    self.fBox.insertItem(0, label)
                    boxItemValues.insert(0, value)
                elif value > boxItemValues[-1]:
                    self.fBox.addItem(label)
                    boxItemValues.append(value)
                else:
                    for index in range(len(boxItemValues)):
                        if value >= boxItemValues[index]:
                            self.fBox.insertItem(index+1, label)
                            boxItemValues.insert(index+1, value)
                            break

        if self.fValue is not None:
            self._setScalePointValue(self.fValue)

        self.fBox.currentIndexChanged['QString'].connect(self.slot_comboBoxIndexChanged)

    def stepBy(self, steps):
        if steps == 0 or self.fValue is None:
            return

        value = self.fValue + (self.fStep * steps)

        if value < self.fMinimum:
            value = self.fMinimum
        elif value > self.fMaximum:
            value = self.fMaximum

        self.setValue(value)

    def stepEnabled(self):
        if self.fIsReadOnly or self.fValue is None:
            return QAbstractSpinBox.StepNone
        if self.fValue <= self.fMinimum:
            return QAbstractSpinBox.StepUpEnabled
        if self.fValue >= self.fMaximum:
            return QAbstractSpinBox.StepDownEnabled
        return (QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled)

    def updateAll(self):
        self.update()
        self.fBar.update()
        if self.fBox is not None:
            self.fBox.update()

    def resizeEvent(self, event):
        QAbstractSpinBox.resizeEvent(self, event)
        self.slot_updateProgressBarGeometry()

    @pyqtSlot(str)
    def slot_comboBoxIndexChanged(self, boxText):
        if self.fIsReadOnly:
            return

        value          = float(boxText.split(" - ", 1)[0])
        lastScaleValue = self.fScalePoints[-1]['value']

        if value == lastScaleValue:
            value = self.fMaximum

        self.setValue(value)

    @pyqtSlot(float)
    def slot_progressBarValueChanged(self, value):
        if self.fIsReadOnly:
            return

        if value <= self.fMinimum:
            realValue = self.fMinimum
        elif value >= self.fMaximum:
            realValue = self.fMaximum
        else:
            curStep   = int((value - self.fMinimum) / self.fStep + 0.5)
            realValue = self.fMinimum + (self.fStep * curStep)

            if realValue < self.fMinimum:
                realValue = self.fMinimum
            elif realValue > self.fMaximum:
                realValue = self.fMaximum

        self.setValue(realValue)

    @pyqtSlot()
    def slot_showCustomMenu(self):
        clipboard  = QApplication.instance().clipboard()
        pasteText  = clipboard.text()
        pasteValue = None

        if pasteText:
            try:
                pasteValue = float(pasteText)
            except:
                pass

        menu      = QMenu(self)
        actReset  = menu.addAction(self.tr("Reset (%f)" % self.fDefault))
        actRandom = menu.addAction(self.tr("Random"))
        menu.addSeparator()
        actCopy   = menu.addAction(self.tr("Copy (%f)" % self.fValue))

        if pasteValue is None:
            actPaste = menu.addAction(self.tr("Paste"))
            actPaste.setEnabled(False)
        else:
            actPaste = menu.addAction(self.tr("Paste (%f)" % pasteValue))

        menu.addSeparator()

        actSet = menu.addAction(self.tr("Set value..."))

        if self.fIsReadOnly:
            actReset.setEnabled(False)
            actRandom.setEnabled(False)
            actPaste.setEnabled(False)
            actSet.setEnabled(False)

        actSel = menu.exec_(QCursor.pos())

        if actSel == actReset:
            self.setValue(self.fDefault)

        elif actSel == actRandom:
            value = random() * (self.fMaximum - self.fMinimum) + self.fMinimum
            self.setValue(value)

        elif actSel == actCopy:
            clipboard.setText("%f" % self.fValue)

        elif actSel == actPaste:
            self.setValue(pasteValue)

        elif actSel == actSet:
            dialog = CustomInputDialog(self, self.fName, self.fValue, self.fMinimum, self.fMaximum, self.fStep, self.fScalePoints)
            if dialog.exec_():
                value = dialog.returnValue()
                self.setValue(value)

    @pyqtSlot()
    def slot_updateProgressBarGeometry(self):
        self.fBar.setGeometry(self.lineEdit().geometry())
        if self.fUseScalePoints:
            self.fBox.setGeometry(self.lineEdit().geometry())

    def _getNearestScalePoint(self, realValue):
        finalValue = 0.0

        for i in range(len(self.fScalePoints)):
            scaleValue = self.fScalePoints[i]["value"]
            if i == 0:
                finalValue = scaleValue
            else:
                srange1 = abs(realValue - scaleValue)
                srange2 = abs(realValue - finalValue)

                if srange2 > srange1:
                    finalValue = scaleValue

        return finalValue

    def _setScalePointValue(self, value):
        value = self._getNearestScalePoint(value)

        for i in range(self.fBox.count()):
            if float(self.fBox.itemText(i).split(" - ", 1)[0]) == value:
                self.fBox.setCurrentIndex(i)
                break
예제 #2
0
class QComboBoxDemo(QWidget):
    def __init__(self):
        super(QComboBoxDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('QComboBoxDemo')
        self.resize(300, 280)
        layout = QVBoxLayout()

        self.label = QLabel('请选择语言...')

        self.cb = QComboBox()
        self.cb.addItem('C')
        self.cb.addItem('C++')
        self.cb.addItems(['Java', 'Python'])

        self.cb.currentIndexChanged.connect(self.SelectionChanged)

        layout.addWidget(self.label)
        layout.addWidget(self.cb)
        self.setLayout(layout)

    def SelectionChanged(self, i):
        self.label.setText(self.cb.currentText())
        self.label.adjustSize()
        self.label.setFont(QFont('Arial', 20))

        for item in range(self.cb.count()):
            print('Item:' + str(item) + ',' + self.cb.itemText(item))

        print('CurrentIndex:' + str(i) + ',SelecctionChanged:' + self.cb.itemText(i))
예제 #3
0
class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'Rechoir'
        self.left = 100
        self.top = 100
        self.width = 2 * 640
        self.height = 2 * 480
        self.initData()
        self.initUI()

    def initData(self):
        self.data = pd.read_csv('~/Desktop/engine.data.csv', parse_dates=['DATETIME'])

    def play_sound(self):
        pass

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')
        data = self.currdata[0:10]
        for index, row in data.iterrows():
            self.play_sound()
            print(row['DATETIME'])
            for plt in self.plots:
                plt.set_vl(row['DATETIME'])

        
    def initUI(self):
        self.layout = QHBoxLayout()
        self.setWindowTitle(self.title)
        self.num_plots = 4
        self.cols = ['DT30', 'DP30', 'DN2', 'DFF']
        self.plots = []
        self.setGeometry(self.left, self.top, self.width, self.height)
        for i in range(self.num_plots):
            plot = PlotCanvas(self, width=10, height=2)
            plot.move(80, 10 + (200 * i))
            self.plots.append(plot)
        self.cb = QComboBox(self)
        self.cb.addItems([str(x) for x in self.data['ESN'].unique()])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        self.cb.move(0,0)
        self.layout.addWidget(self.cb)
        self.selectionchange(0)
        self.play = QPushButton('Play', self)
        self.play.move(1100, 10)
        self.play.clicked.connect(self.on_click)
        self.show()

    def selectionchange(self,engine):
        print(self.cb.itemText(engine))
        self.currdata = self.data[self.data['ESN'] == int(self.cb.itemText(engine))].sort_values(by=['DATETIME'])
        for i, plt in enumerate(self.plots):
            plt.plot(self.currdata['DATETIME'], self.currdata[self.cols[i]], self.cols[i])
예제 #4
0
class VelocityCalculate(QDialog, QWidget):
    def __init__(self, title, left, top, width, height):
        super().__init__()
        self.combo = QComboBox(self)
        self.setWindowTitle(title)
        self.setGeometry(left, top, width, height)
        self.initUI()

    def initUI(self):
        self.combo.addItem("Knoten")
        self.combo.addItem("Km/h")
        self.textbox = QLineEdit(self)
        self.textbox.setText("")
        self.l1 = QLabel("Velocity")
        text = self.combo.itemText(
            self.combo.currentIndex() -
            1) if self.combo.currentIndex() == 1 else self.combo.itemText(
                self.combo.currentIndex() + 1)
        self.l1.setText("Geschwindigkeit in " + text)
        self.cancel = QPushButton("Cancel")
        self.cancel.clicked.connect(self.close)
        self.calculate = QPushButton("Berechnen")
        self.calculate.clicked.connect(self.action)
        self.CreateGrid()
        self.windowLayout = QVBoxLayout()
        self.windowLayout.addWidget(self.horizontalGroupBox)
        self.setLayout(self.windowLayout)

    def CreateGrid(self):
        self.horizontalGroupBox = QGroupBox("")
        self.mainLayout = QGridLayout()
        self.mainLayout.setColumnStretch(1, 4)
        self.mainLayout.setColumnStretch(2, 4)
        self.mainLayout.addWidget(self.combo, 0, 1)
        self.mainLayout.addWidget(self.textbox, 0, 0)
        self.mainLayout.addWidget(self.l1, 1, 0)
        self.mainLayout.addWidget(self.calculate, 3, 3)
        self.mainLayout.addWidget(self.cancel, 3, 2)
        self.horizontalGroupBox.setLayout(self.mainLayout)

    def action(self):
        if self.combo.currentIndex() == 1:
            value = C.FlightPath.distanceCalcculator(SC.start.b1.text(),
                                                     self.combo.currentText(),
                                                     int(self.textbox.text()))
            self.l1.setText("Geschwindigkeit in " +
                            self.combo.itemText(self.combo.currentIndex() -
                                                1) + ": " + str(value))
        elif self.combo.currentIndex() == 0:
            value = C.FlightPath.distanceCalcculator(SC.start.b1.text(),
                                                     self.combo.currentText(),
                                                     int(self.textbox.text()))
            self.l1.setText("Geschwindigkeit in " +
                            self.combo.itemText(self.combo.currentIndex() +
                                                1) + ": " + str(value))
예제 #5
0
파일: utils.py 프로젝트: inverse/algobot
def get_elements_from_combobox(combobox: QComboBox) -> List[str]:
    """
    Returns all elements from combobox provided in a list.
    :param combobox: Combobox to get list of elements from.
    :return: List of elements from combobox.
    """
    return [combobox.itemText(i) for i in range(combobox.count())]
예제 #6
0
class QComboBoxDemo(QWidget):
    def __init__(self):
        super(QComboBoxDemo, self).__init__()
        self.v_layout = QVBoxLayout()
        self.label = QLabel('请选择编程语言')
        self.comboBox = QComboBox()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('下拉列表控件')
        self.comboBox.addItem('C++')
        self.comboBox.addItem('C')
        self.comboBox.addItem('Python')
        self.comboBox.addItems(['Java', 'C#', 'R'])
        self.comboBox.currentIndexChanged.connect(self.selection_change)

        self.v_layout.addWidget(self.label)
        self.v_layout.addWidget(self.comboBox)

        self.setLayout(self.v_layout)

    def selection_change(self, index):
        self.label.setText(self.comboBox.currentText())
        # self.label.adjustSize()

        for count in range(self.comboBox.count()):
            print('item {} = {}'.format(count, self.comboBox.itemText(count)))
        print('current index {}, selection changed {}'.format(
            index, self.comboBox.currentText()))
 def append_to_combobox(cbox: QComboBox):
     current = cbox.currentText()
     completions = set(cbox.itemText(i) for i in range(cbox.count()))
     completions.add(current)
     cbox.clear()
     cbox.addItems(completions)
     cbox.setCurrentIndex(cbox.findText(current))
예제 #8
0
class RemoveColumnDialog(QDialog):
    def __init__(self, pm, parent=None):
        super(RemoveColumnDialog, self).__init__(parent)
        self.pm = pm
        self.combo = QComboBox(self)
        cols = ['']
        cols.extend(self.pm.get_custom_columns())
        self.combo.addItems(cols)
        self.message = QLabel('', self)
        self.combo.currentTextChanged.connect(self.update_message)
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Close, self)
        self.buttons.setEnabled(False)
        self.buttons.accepted.connect(self.handle_remove)
        self.buttons.rejected.connect(self.close)
        self.setWindowTitle('Remove Column')
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint
                            | QtCore.Qt.WindowSystemMenuHint
                            | QtCore.Qt.WindowTitleHint)

        vertical_layout = QVBoxLayout(self)
        vertical_layout.addWidget(self.combo)
        vertical_layout.addWidget(self.message)
        vertical_layout.addWidget(self.buttons)

    def update_message(self):
        if self.combo.itemText(0) == '':
            self.combo.removeItem(0)
        self.message.setText(f"Remove {self.combo.currentText()} column?")
        self.buttons.setEnabled(True)

    def handle_remove(self):
        self.pm.remove_column(self.combo.currentText())
        self.accept()
예제 #9
0
class NewContactDialog(QDialog):
    def __init__(self, users):
        super().__init__()

        self.setWindowTitle("New Contact")

        self.users = QComboBox()
        self.users.addItems(users)
        self.users.currentTextChanged.connect(self.userSelected)

        self.current = [self.users.itemText(i) for i in range(self.users.count())][0]

        self.addBtn = QPushButton()
        self.addBtn.setText('Add')
        self.addBtn.clicked.connect(self.addContact)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.users)
        self.layout.addWidget(self.addBtn)
        self.setLayout(self.layout)

    def addContact(self):
        self.close()

    def userSelected(self, value):
        self.current = value
예제 #10
0
파일: latex.py 프로젝트: afalaize/pyphs_gui
class LatexWidget(QWidget):
    def __init__(self, latexcode, fs=6):

        QWidget.__init__(self)

        # Fontsize widget
        fontsize = QHBoxLayout()
        fontsize.addWidget(QLabel('Font Size'))

        # Latex widget
        self.latex = LatexLabel(latexcode, FSINIT)

        self.qcb = QComboBox(self)
        self.qcb.addItems(list(map(str, range(1, 11))))
        self.qcb.activated[str].connect(self.onchange_fontsize)
        self.qcb.setCurrentIndex(fs)
        self.onchange_fontsize(self.qcb.itemText(fs))
        fontsize.addWidget(self.qcb)
        fontsize.addStretch()

        # define vbox
        vbox = QVBoxLayout()
        vbox.addLayout(fontsize)
        vbox.addWidget(self.latex)

        # set layout and show
        self.setLayout(vbox)

    def onchange_fontsize(self, fs):
        self.latex.fs = int(fs)
        self.latex.update()

    def update_code(self, latexcode):
        self.latex.code = latexcode
        self.latex.update()
예제 #11
0
class comboBoxDemo(QWidget):
    def __init__(self):
        super(comboBoxDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('下拉列表框测试')

        self.label = QLabel('请选择您最喜欢的春节晚会节目')
        layout = QHBoxLayout()  # 使用水平布局
        self.cb = QComboBox()  # 实例化一个下拉列表框
        self.cb.addItems(['相声', '小品', '歌曲', '舞蹈'])  # 添加下拉列表中的选项
        self.cb.currentIndexChanged.connect(
            self.selectionChange)  # 信号绑定,并传递所选的索引Index
        # 控件使用水平布局
        layout.addWidget(self.label)
        layout.addWidget(self.cb)

        self.setLayout(layout)

    def selectionChange(self, i):
        "这是一个函数文档,下面的for循环及那个cb下拉列表框中的项都打印出来"
        for count in range(self.cb.count()):
            print('item' + str(count) + '=' + self.cb.itemText(count))
        # 打印目前选中的
        print('current index', i, 'selection changed', self.cb.currentText())
예제 #12
0
class MainWin(QWidget):
    def __init__(self, parent=None):
        super(MainWin, self).__init__(parent)

        layout = QVBoxLayout()
        self.cb = QComboBox()
        self.cb.addItem('C')
        self.cb.addItem('C++')
        self.cb.addItems(['Java', 'C#', 'Python'])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        layout.addWidget(self.cb)

        self.lb = QLabel('')
        layout.addWidget(self.lb)

        self.setLayout(layout)
        self.resize(300, 90)
        self.setWindowTitle('ComboBox')

    def selectionchange(self, idx):
        self.lb.setText(self.cb.currentText())
        print('Items in the list are: ')
        for i in range(self.cb.count()):
            print('item {} = {}'.format(i, self.cb.itemText(i)))
        print('Current index', idx, 'selection changed', self.cb.currentText())
예제 #13
0
 def get_style_combo_box(self):
     combo_box = QComboBox()
     combo_box.addItems(QStyleFactory.keys())
     combo_box.activated[str].connect(self.change_style)
     all_items = [combo_box.itemText(i) for i in range(combo_box.count())]
     idx = all_items.index('Fusion')
     combo_box.setCurrentIndex(idx)
     return combo_box
예제 #14
0
class RenameColumnDialog(QDialog):
    def __init__(self, pm, parent=None):
        super(RenameColumnDialog, self).__init__(parent)
        self.pm = pm
        self.column_to_rename = QLabel('column to rename:', self)
        self.combo = QComboBox(self)
        cols = ['']
        cols.extend(self.pm.get_custom_columns())
        self.combo.addItems(cols)
        self.combo.currentTextChanged.connect(self.handle_combo_change)
        self.new_name_label = QLabel('new name:', self)
        self.new_name_field = QLineEdit(self)
        self.new_name_field.textChanged.connect(self.handle_text_change)
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Close, self)
        self.buttons.setEnabled(False)
        self.buttons.accepted.connect(self.handle_rename)
        self.buttons.rejected.connect(self.close)
        self.setWindowTitle('Rename Column')
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint
                            | QtCore.Qt.WindowSystemMenuHint
                            | QtCore.Qt.WindowTitleHint)

        grid_layout = QGridLayout(self)
        grid_layout.addWidget(self.column_to_rename, 0, 0)
        grid_layout.addWidget(self.combo, 0, 1)
        grid_layout.addWidget(self.new_name_label, 1, 0)
        grid_layout.addWidget(self.new_name_field, 1, 1)
        grid_layout.addWidget(self.buttons, 2, 0, 1, 2)

    def handle_combo_change(self):
        if self.combo.itemText(0) == '':
            self.combo.removeItem(0)
        if self.new_name_field.text() != '':
            self.buttons.setEnabled(True)

    def handle_text_change(self):
        if self.new_name_field.text() != '' and self.combo.itemText(0) != '':
            self.buttons.setEnabled(True)
        else:
            self.buttons.setEnabled(False)

    def handle_rename(self):
        self.pm.rename_column(self.combo.currentText(),
                              self.new_name_field.text())
        self.accept()
예제 #15
0
 def addToCombo(self, combo: QComboBox, data):
     print(data, combo)
     if data:
         if 'id' in data.keys() and 'name' in data.keys():
             item = "{id} - {name}".format(**data)
             #QComboBox.itemText
             items = [combo.itemText(i) for i in range(combo.count())]
             if item not in items:
                 combo.addItem(item)
예제 #16
0
class GeneralTools(QWidget):

    def __init__(self, parent):
        super(GeneralTools, self).__init__(parent)

        self.plugin = self.parent().plugin

        layout = QFormLayout()

        self.cb = QComboBox()
        self.cb.addItems(['Spectrum', 'Spectrogram'])
        self.cb.currentIndexChanged.connect(self.switch_spect_type)
        layout.addRow("Transform", self.cb)

        self.low_lim_le = QLineEdit()
        self.low_lim_le_validator = QDoubleValidator()
        self.low_lim_le.setValidator(self.low_lim_le_validator)

        self.high_lim_le = QLineEdit()
        self.high_lim_le_validator = QDoubleValidator()
        self.high_lim_le.setValidator(self.high_lim_le_validator)

        layout.addRow("Low limit", self.low_lim_le)
        layout.addRow("High limit", self.high_lim_le)

        self.low_lim_le.editingFinished.connect(self.set_low_lim)
        self.high_lim_le.editingFinished.connect(self.set_high_lim)

        self.setMaximumWidth(260)

        self.setLayout(layout)

    def switch_spect_type(self, idx):
        self.parent().curr_tools_widget.setParent(None)
        self.plugin.signal_widget.set_spect_type(self.cb.itemText(idx).lower())
        self.parent().layout().insertWidget(1,
                                            self.parent().specific_tools[idx])
        self.parent().curr_tools_widget = self.parent().specific_tools[idx]

    def set_low_lim(self):
        if self.low_lim_le.text() != '':
            self.plugin.signal_widget.low_lim = float(self.low_lim_le.text())
            self.plugin.signal_widget.update_signals()
        else:
            self.plugin.signal_widget.low_lim = None
            self.plugin.signal_widget.update_signals()

    def set_high_lim(self):
        if self.high_lim_le.text() != '':
            self.plugin.signal_widget.high_lim = float(self.high_lim_le.text())
            self.plugin.signal_widget.update_signals()
        else:
            self.plugin.signal_widget.high_lim = None
            self.plugin.signal_widget.update_signals()
예제 #17
0
 class PortSelector(QWidget):
     tty_pfxs = ("ttyUSB",)
     def __init__(self, *args):
         QWidget.__init__(self, *args)
         self.setLayout(QHBoxLayout())
         self.layout().setContentsMargins(0,0,0,0)
         self._combo = QComboBox()
         self._button = QPushButton("...")
         self.layout().addWidget(self._combo, 1)
         self.layout().addWidget(self._button, 0)
         self.rescan()
         self.connect(self._button, QtCore.SIGNAL("clicked()"), self.show_prompt)
     def value(self):
         return self._combo.itemText(self._combo.currentIndex())
     def set_value(self, text):
         found = False
         for i in range(self._combo.count()):
             if self._combo.itemText(i) == text:
                 self._combo.setCurrentIndex(i)
                 found = True
                 break
         if not found:
             self.set_custom(text)
     def set_custom(self, text):
         if self._custom_port:
             self._combo.removeItem(0)
         self._combo.insertItem(0, text)
         self._combo.setCurrentIndex(0)
         self._custom_port = True
     def show_prompt(self):
         text, ok = QInputDialog.getText(self, "Custom entry", "Port", text="/dev/")
         if ok:
             self.set_custom(text)
     def rescan(self):
         self._combo.clear()
         self._custom_port = False
         for x in os.listdir("/dev/"):
             for y in self.tty_pfxs:
                 if x[:len(y)] == y:
                     self._combo.addItem("/dev/" + x)
                     break
예제 #18
0
    def display_ports(ports: typing.List[QtSerialPort.QSerialPortInfo],
                      combo: QComboBox) -> typing.Dict[str, str]:
        known_keys = set()
        remove_indices = []
        was_empty = combo.count() == 0

        def make_description(p: QtSerialPort.QSerialPortInfo) -> str:
            out = f'{p.portName()}: {p.manufacturer() or "Unknown vendor"} - {p.description() or "Unknown product"}'
            if p.serialNumber().strip():
                out += ' #' + str(p.serialNumber())

            return out

        description_location_mapping = {}
        description_icon_mapping = {}
        for x in ports:
            desc = make_description(x)
            icon = _get_port_icon(x)
            description_location_mapping[desc] = x.systemLocation()
            if icon:
                description_icon_mapping[desc] = icon

        # Marking known and scheduling for removal
        for idx in itertools.count():
            tx = combo.itemText(idx)
            if not tx:
                break

            known_keys.add(tx)
            if tx not in description_location_mapping:
                _logger.debug('Removing port %r', tx)
                remove_indices.append(idx)

        # Removing - starting from the last item in order to retain indexes
        for idx in remove_indices[::-1]:
            combo.removeItem(idx)

        # Adding new items - starting from the last item in order to retain the final order
        for key in list(description_location_mapping.keys())[::-1]:
            if key not in known_keys:
                _logger.debug('Adding port %r', key)
                try:
                    combo.insertItem(0, description_icon_mapping[key], key)
                except KeyError:
                    combo.insertItem(0, key)

        # Updating selection
        if was_empty:
            combo.setCurrentIndex(0)

        return description_location_mapping
예제 #19
0
class tb_pulse_load_type(QWidget):

	changed = pyqtSignal()

	def __init__(self,index):
		self.index=index

		QWidget.__init__(self)


		layout=QHBoxLayout()
		label=QLabel()
		label.setText(_("Load type:"))
		layout.addWidget(label)

		self.sim_mode = QComboBox(self)
		self.sim_mode.setEditable(True)


		layout.addWidget(self.sim_mode)

		self.setLayout(layout)

		self.sim_mode.addItem("open_circuit")
		self.sim_mode.addItem("load")
		self.sim_mode.addItem("ideal_diode_ideal_load")


		lines=[]
		inp_load_file(lines,os.path.join(get_inp_file_path(),"pulse"+str(self.index)+".inp"))

		token=inp_get_token_value("pulse"+str(self.index)+".inp", "#pulse_sim_mode")

		all_items  = [self.sim_mode.itemText(i) for i in range(self.sim_mode.count())]
		for i in range(0,len(all_items)):
		    if all_items[i] == token:
		        self.sim_mode.setCurrentIndex(i)

		self.sim_mode.currentIndexChanged.connect(self.call_back_sim_mode_changed)


	def call_back_sim_mode_changed(self):
		mode=self.sim_mode.currentText()
		inp_update_token_value("pulse"+str(self.index)+".inp", "#pulse_sim_mode", mode,1)
		self.changed.emit()
예제 #20
0
class tb_pulse_load_type(QWidget):

    changed = pyqtSignal()

    def __init__(self, index):
        self.index = index

        QWidget.__init__(self)

        layout = QHBoxLayout()
        label = QLabel()
        label.setText(_("Load type") + ":")
        layout.addWidget(label)

        self.sim_mode = QComboBox(self)
        self.sim_mode.setEditable(True)

        layout.addWidget(self.sim_mode)

        self.setLayout(layout)

        self.sim_mode.addItem("open_circuit")
        self.sim_mode.addItem("load")
        self.sim_mode.addItem("ideal_diode_ideal_load")

        token = inp_get_token_value(
            os.path.join(get_sim_path(), "pulse" + str(self.index) + ".inp"),
            "#pulse_sim_mode")

        all_items = [
            self.sim_mode.itemText(i) for i in range(self.sim_mode.count())
        ]
        for i in range(0, len(all_items)):
            if all_items[i] == token:
                self.sim_mode.setCurrentIndex(i)

        self.sim_mode.currentIndexChanged.connect(
            self.call_back_sim_mode_changed)

    def call_back_sim_mode_changed(self):
        mode = self.sim_mode.currentText()
        inp_update_token_value(
            os.path.join(get_sim_path(), "pulse" + str(self.index) + ".inp"),
            "#pulse_sim_mode", mode)
        self.changed.emit()
예제 #21
0
class BodyContentViewer(QWidget):
    def __init__(self, plugin_registry, message, context, state, parent=None):
        super().__init__(parent)
        self.plugin_registry = plugin_registry
        vbox = QVBoxLayout()
        self.combo = QComboBox()
        vbox.addWidget(self.combo)
        vbox.addStretch()
        vbox.itemAt(vbox.count() - 1)
        self.vbox = vbox
        self.setLayout(vbox)

        self.setContent(message, context)
        self.restoreState(state)

        self.combo.currentIndexChanged.connect(self.onComboChanged)
        self.onComboChanged()

    def setContent(self, data: HttpMessage, context: RequestResponse):
        self.data = data
        self.context = context
        self.combo.clear()
        for title, function in self.plugin_registry.get_content_representations(
                data, context):
            self.combo.addItem(title, function)

    def onComboChanged(self):
        function = self.combo.currentData()
        if function:
            newWidget = function(self.data, self.context, self)
            self.vbox.removeItem(self.vbox.itemAt(self.vbox.count() - 1))
            self.vbox.addWidget(newWidget)

    def saveState(self):
        return dict(selected=self.combo.currentText())

    def restoreState(self, state):
        if state and state.get('selected', None) is not None:
            selected = state['selected']
            for i in range(self.combo.count()):
                if self.combo.itemText(i) == selected:
                    self.combo.setCurrentIndex(i)
                    break
예제 #22
0
class QComboBoxDemo(QWidget):
    def __init__(self):
        super(QComboBoxDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('下拉列表')
        # self.resize(600, 800)

        layout = QVBoxLayout()

        self.lable = QLabel("请选择")

        self.btn = QPushButton('getSelect')

        self.cb = QComboBox()
        self.cb.addItem('C')
        self.cb.addItem('Java')
        self.cb.addItem('Python')
        self.cb.addItems(['C#', 'Go', 'Ruby'])

        self.cb.currentIndexChanged.connect(self.selectChange)

        layout.addWidget(self.lable)
        layout.addWidget(self.cb)
        layout.addWidget(self.btn)

        self.btn.clicked.connect(self.clickdd)

        self.setLayout(layout)

    def selectChange(self, l):
        print(l)
        self.lable.setText(self.cb.currentText())
        self.lable.adjustSize()

        for i in range(self.cb.count()):
            print('item', str(i), '=', self.cb.itemText(i))
            print('current index', l, 'select changed', self.cb.currentText())

    def clickdd(self):
        print(self.cb.currentText())
예제 #23
0
    def PopulateCMBX(self, CMBX: QtWidgets.QComboBox, Data=None):  # Tested
        """
        Populates the CMBX with the data provided

        :Args:
        CMBX: QtWidgets.QComboBox
            Combobox with all the DB names.
        Data: list[str, str, str]
            data to fill in the combobox
        """
        if Data == None:
            DBnames = self.UI.DB_Monitored.keys()
        else:
            DBnames = Data

        [CMBX.removeItem(item) for item in range(CMBX.count())]
        CMBXitems = [CMBX.itemText(item) for item in range(CMBX.count())]
        for Name in DBnames:
            if Name not in CMBXitems:
                CMBX.addItem(Name)
예제 #24
0
class combodemo(QWidget):
    def __init__(self, parent=None):
        super(combodemo, self).__init__(parent)

        layout = QHBoxLayout()
        self.cb = QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])
        self.cb.currentIndexChanged.connect(self.selectionchange)

        layout.addWidget(self.cb)
        self.setLayout(layout)
        self.setWindowTitle("combo box demo")

    def selectionchange(self, i):
        print("Items in the list are :")

        for count in range(self.cb.count()):
            print(self.cb.itemText(count))
        print("Current index", i, "selection changed ", self.cb.currentText())
예제 #25
0
class QComboxDemo(QWidget):
    def __init__(self):
        super(QComboxDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.resize(500, 200)
        self.setWindowTitle('QComboxDemo')

        self.label = QLabel('请选择编程语言')

        self.combox = QComboBox()
        # 为combox添加item
        self.combox.addItem('C')
        self.combox.addItem('C++')
        self.combox.addItem('Java')
        self.combox.addItems(['Python', 'C#', 'R'])
        #关联信号
        self.combox.currentIndexChanged.connect(self.selectionChange)
        #布局
        layout = QHBoxLayout()
        self.label.setMaximumSize(150, 30)
        self.combox.setMaximumSize(100, 30)
        layout.addWidget(self.label)
        layout.addWidget(self.combox)

        self.setLayout(layout)

    def selectionChange(self, i):
        #设置标签文本
        self.label.setText(self.combox.currentText())
        self.label.adjustSize()

        for index in range(self.combox.count()):
            #根据下标获取文本
            print('item' + str(index) + ' = ' + self.combox.itemText(index))
        #获取当前文本
        print('current index', i, 'selection changed',
              self.combox.currentText())
예제 #26
0
class StatusBar(QStatusBar):
    """Status bar of the application."""

    mode_change = pyqtSignal(EncryptionMode)

    def __init__(self, my_addr: Address) -> None:
        super().__init__()

        self._client_address = QLabel(f"Your IP: {my_addr}")
        self._server_address = QLabel()
        self._combobox = QComboBox()

        self._server_address.setVisible(False)
        self._combobox.addItems(
            [
                EncryptionMode.ECB.value,
                EncryptionMode.CBC.value,
                EncryptionMode.CFB.value,
                EncryptionMode.OFB.value,
            ]
        )
        self._combobox.currentIndexChanged.connect(
            lambda mode_index: self.mode_change.emit(
                EncryptionMode(self._combobox.itemText(mode_index))
            )
        )
        self.addWidget(self._combobox)
        self.addPermanentWidget(self._client_address)
        self.addPermanentWidget(self._server_address)

    @pyqtSlot(Address)
    def update_server_addr(self, addr: Optional[Address]) -> None:
        """Update an address of the connected server."""

        if addr is None:
            self._server_address.setVisible(False)
        else:
            self._server_address.setText(f"Connected to: {addr}")
            self._server_address.setVisible(True)
예제 #27
0
    def init_UI(self):
        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        vbox.addLayout(hbox)
        button = QPushButton("Turn on\ngenerator")
        button.setProperty("turn_on", self.state)
        button.clicked.connect(self._turn)
        generator_type = QComboBox(self)
        current_indx = 0
        for i, key in enumerate(GENERATOR_FACTORY.keys()):
            generator_type.insertItem(i, key)
            if self.settings.last_generator == key:
                current_indx = i

        vbox_1 = QVBoxLayout()
        vbox_1.addWidget(generator_type)
        vbox_1.addWidget(self._create_reset())
        hbox.addLayout(vbox_1, 1)
        hbox.addWidget(button, 1)

        generator_type.currentIndexChanged.connect(
            lambda x: self.change_generator(generator_type.itemText(x)))
        generator_type.setCurrentIndex(current_indx)
        vbox.addWidget(self.current_generator)

        def turn(state):
            generator_type.setDisabled(state)
            button.setProperty("turn_on", state)
            update_style(button)
            if state:
                button.setText("Turn off\ngenerator")
                self.current_generator.start()
            else:
                button.setText("Turn on\ngenerator")
                self.current_generator.stop()
                if self.settings.auto_reset_generator:
                    self.device.reset_value()

        self.state_signal.connect(turn)
예제 #28
0
class GUITheoryAlgebraicExpression(BaseTheoryAlgebraicExpression, QTheory):
    """GUI Version"""

    def __init__(self, name="", parent_dataset=None, ax=None):
        """**Constructor**"""
        super().__init__(name, parent_dataset, ax)

        # add widgets specific to the theory
        tb = QToolBar()
        tb.setIconSize(QSize(24, 24))
        self.spinbox = QSpinBox()
        self.spinbox.setRange(1, self.MAX_DEGREE)  # min and max number of modes
        self.spinbox.setToolTip("Number of parameters")
        self.spinbox.setValue(self.parameters["n"].value)  #initial value
        tb.addWidget(self.spinbox)
        self.expressionCB = QComboBox()
        self.expressionCB.setToolTip("Algebraic expression")
        self.expressionCB.addItem("A0+A1*x")
        self.expressionCB.addItem("A0*sin(A1*x)")
        self.expressionCB.addItem("A0*sin(A1*x+A2)")
        self.expressionCB.setEditable(True)
        self.expressionCB.setMinimumWidth(self.parent_dataset.width()-75)
        tb.addWidget(self.expressionCB)

        self.thToolsLayout.insertWidget(0, tb)
        connection_id = self.spinbox.valueChanged.connect(
            self.handle_spinboxValueChanged)
        connection_id = self.expressionCB.currentIndexChanged.connect(
            self.handle_expressionChanged)

    def handle_spinboxValueChanged(self, value):
        """Handle a change of the parameter 'n'"""
        self.set_param_value("n", value)

    def handle_expressionChanged(self, item):
        """Handle a change in the algebraic expression"""
        self.set_param_value("expression", self.expressionCB.itemText(item))
예제 #29
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.label = QLabel("Ubuntu", self)

        #Creating the instance os the QcomboBox class.
        self.combo = QComboBox(self)

        #Adding items to the combo box.
        self.combo.addItem("Ubuntu")
        self.combo.addItem("Mandriva")
        self.combo.addItem("Fedora")
        self.combo.addItem("Arch")
        self.combo.addItem("Gentoo")

        self.combo.move(50, 50)
        self.label.move(50, 150)

        self.combo.activated.connect(self.onActivated)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QComboBox')
        self.show()

    def onActivated(self, index):

        #Retreiving item value at given index.
        text = self.combo.itemText(index)

        self.label.setText(text)
        self.label.adjustSize()
예제 #30
0
class NetworkSettingsPanel(SettingsPanel):
    def __init__(self, parent=None):
        super(NetworkSettingsPanel, self).__init__(parent)

        # Checkbox to toggle DNS prefetching.
        self.dnsPrefetchingToggle = QCheckBox(tr("Enable DNS &prefetching"), self)
        self.layout().addWidget(self.dnsPrefetchingToggle)

        # Checkbox to toggle XSS auditing.
        self.xssAuditingToggle = QCheckBox(tr("Enable X&SS auditing"), self)
        self.layout().addWidget(self.xssAuditingToggle)

        # Proxy label.
        proxyLabel = QLabel(tr("<b>Proxy configuration</b>"))
        self.layout().addWidget(proxyLabel)

        # Type row.
        typeRow = custom_widgets.Row(self)
        self.layout().addWidget(typeRow)

        # Create a nice label.
        typeLabel = QLabel(tr("Type:"), self)
        typeRow.addWidget(typeLabel)

        # Combo box to select proxy type.
        self.proxySelect = QComboBox(self)
        self.proxySelect.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.proxySelect.addItem("None")
        self.proxySelect.addItem('Socks5')
        self.proxySelect.addItem('Http')
        typeRow.addWidget(self.proxySelect)

        # Hostname and port row.
        self.hostNamePortRow = custom_widgets.Row()
        self.layout().addWidget(self.hostNamePortRow)

        # Hostname row.
        self.hostNameRow = custom_widgets.LineEditRow(tr("Hostname:"), self)
        self.hostNameEntry = self.hostNameRow.lineEdit
        self.hostNamePortRow.addWidget(self.hostNameRow)

        # Port row.
        self.portRow = custom_widgets.SpinBoxRow(tr("Port:"), self)
        self.portRow.expander.hide()
        self.portEntry = self.portRow.spinBox
        self.portEntry.setMaximum(99999)
        self.hostNamePortRow.addWidget(self.portRow)

        # User row.
        self.userRow = custom_widgets.LineEditRow(tr("User:"******"Password:"******"proxy/Hostname")))
        self.userEntry.setText(str(settings.settings.value("proxy/User")))
        self.passwordEntry.setText(str(settings.settings.value("proxy/Password")))
        self.xssAuditingToggle.setChecked(settings.setting_to_bool("network/XSSAuditingEnabled"))
        self.dnsPrefetchingToggle.setChecked(settings.setting_to_bool("network/DnsPrefetchingEnabled"))
        port = settings.setting_to_int("proxy/Port")
        if port == "None":
            port = str(settings.default_port)
        self.portEntry.setValue(port)
        for index in range(0, self.proxySelect.count()):
            if self.proxySelect.itemText(index) == settings.settings.value("proxy/Type"):
                self.proxySelect.setCurrentIndex(index)
                break

    def saveSettings(self):
        settings.settings.setValue("proxy/Hostname", self.hostNameEntry.text())
        proxyType = self.proxySelect.currentText()
        if proxyType == "None":
            proxyType = "No"
        settings.settings.setValue("network/XSSAuditingEnabled", self.xssAuditingToggle.isChecked())
        settings.settings.setValue("network/DnsPrefetchingEnabled", self.dnsPrefetchingToggle.isChecked())
        settings.settings.setValue("proxy/Type", proxyType)
        settings.settings.setValue("proxy/Port", self.portEntry.value())
        settings.settings.setValue("proxy/User", self.userEntry.text())
        settings.settings.setValue("proxy/Password", self.passwordEntry.text())
        common.applyWebSettings()
        settings.settings.sync()
예제 #31
0
class SqliteDbTableEditer(QWidget):
    #Db=sqlite3.connect("test.db")
    def __init__(self,dbPath,tblName='',parent=None):

        self.app=QApplication(sys.argv)
        self.SqliteDbTypes=['integer','real','text','blob']
        self.DbPath,self.CurrentTable=dbPath,tblName
        #连接数据库
        self.Db=sqlite3.connect(self.DbPath)
        #构建Gui组件
        super(SqliteDbTableEditer,self).__init__(parent)
        self.setWindowTitle('Sqlite数据库表修改器')
        screen=QDesktopWidget().availableGeometry(0)
        self.setGeometry(screen.width()/3/2-1,
                         screen.height()/5/2-1,
                         screen.width()*2/3,
                         screen.height()*4/5
                         )
        #lay
        lay=QVBoxLayout()
        self.setLayout(lay)
        #数据库表设置控件
        ##layDb
        layDb=QHBoxLayout()
        lay.addLayout(layDb)
        ###lblDb
        lblDb=QLabel('数据库:')
        layDb.addWidget(lblDb)
        ###self.leDb
        self.leDb=QLineEdit()
        self.leDb.setText(self.DbPath)
        layDb.addWidget(self.leDb)
        ###btnDb
        btnChangeDb=QPushButton('浏览')
        btnChangeDb.clicked.connect(self.btnChangeDb_Clicked)
        layDb.addWidget(btnChangeDb)
        ###lblTbl
        lblTbl=QLabel('数据表:')
        layDb.addWidget(lblTbl)
        ###self.cbbTbls
        self.cbbTbls=QComboBox()
        tbls=list(map(lambda x:x[1],
                      list(filter(lambda x:x[0]=='table',
                                  self.Db.execute(
                                      'Select * From sqlite_master'
                                      ).fetchall()
                                  )
                           )
                      )
                  )
        self.cbbTbls.addItems(tbls)
        if self.CurrentTable!='' :
            self.cbbTbls.setCurrentIndex(tbls.index(self.CurrentTable))
        else:
            self.CurrentTable=tbls[0]
            self.makeTableInfo()
            self.cbbTbls.setCurrentIndex(0)
        layDb.addWidget(self.cbbTbls)
        ###lblRename
        lblRename=QLabel('重命名为:')
        layDb.addWidget(lblRename)
        ###self.leRename
        self.leRename=QLineEdit()
        self.leRename.setFixedWidth(100)
        layDb.addWidget(self.leRename)
        ###btnRename
        btnRenameTable=QPushButton('重命名')
        btnRenameTable.clicked.connect(self.btnRenameTable_Clicked)
        layDb.addWidget(btnRenameTable)
        ###btnDeleteTable
        btnDeleteTable=QPushButton('删除表')
        btnDeleteTable.clicked.connect(self.btnDeleteTable_Clicked)
        layDb.addWidget(btnDeleteTable)
        ###btnShow
        self.btnShow=QPushButton('查看表结构')
        self.btnShow.clicked.connect(self.btnShow_Clicked)
        layDb.addWidget(self.btnShow)
        ###设置TableView控件self.tv,以呈现表数据
        self.tv=QTableView()
        lay.addWidget(self.tv)
        ###self.model基本初始化
        self.model=QSqlTableModel(self,QSqlDatabase.addDatabase('QSQLITE'))
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        ###self.tv链接到数据源
        self.tv.setModel(self.model)
        ###self.model数据初始化
        self.model.database().setDatabaseName(self.DbPath)
        self.model.database().open()
        self.model.setTable(self.CurrentTable)
        self.model.select()
        self.cbbTbls.currentIndexChanged.connect(self.changeTable)
        ##layBtns
        layBtns=QHBoxLayout()
        lay.addLayout(layBtns)
        ###btnAddColumn
        btnAddColumn=QPushButton('添加列')
        btnAddColumn.setToolTip('给当前表添加列')
        btnAddColumn.clicked.connect(self.btnAddColumn_Clicked)
        layBtns.addWidget(btnAddColumn)
        ###btnDeleteColumn
        btnDeleteColumn=QPushButton('删除列')
        btnDeleteColumn.setToolTip('删除当前表的列')
        btnDeleteColumn.clicked.connect(self.btnDeleteColumn_Clicked)
        layBtns.addWidget(btnDeleteColumn)
        ###btnRenameColumn
        btnRenameColumn=QPushButton('重命名列')
        btnRenameColumn.setToolTip('重命名当前表的列')
        btnRenameColumn.clicked.connect(self.btnRenameColumn_Clicked)
        layBtns.addWidget(btnRenameColumn)
        ###btnModifyColumnType
        btnModifyColumnType=QPushButton('修改列数据类型')
        btnModifyColumnType.setToolTip('修改当前表的列的数据类型')
        btnModifyColumnType.clicked.connect(self.btnModifyColumnType_Clicked)
        layBtns.addWidget(btnModifyColumnType)
        ###btnModifyColumnConstraint
        btnModifyColumnConstraint=QPushButton('修改列约束')
        btnModifyColumnConstraint.setToolTip('修改当前表的列的约束')
        btnModifyColumnConstraint.clicked.connect(
            self.btnModifyColumnConstraint_Clicked)
        layBtns.addWidget(btnModifyColumnConstraint)
        ###btnOrderColumns
        btnOrderColumns=QPushButton('调整列顺序')
        btnOrderColumns.setToolTip('调整当前表的列的顺序')
        btnOrderColumns.clicked.connect(self.btnOrderColumns_Clicked)
        layBtns.addWidget(btnOrderColumns)
        ###btnModifyTableStruct
        btnModifyTableStruct=QPushButton('修改表结构')
        btnModifyTableStruct.setToolTip('功能:1.增加列;2.删除列;'
                                        +'3.修改列名;4.修改列类型;'
                                        +'5.修改列约束;6.调整列顺序'
                                        )
        btnModifyTableStruct.clicked.connect(self.btnModifyTableStruct_Clicked)
        layBtns.addWidget(btnModifyTableStruct)
        ###btnInsertRow
        btnInsertRow=QPushButton('插入行')
        btnInsertRow.setToolTip('将在数据表最后增加一行新记录')
        btnInsertRow.clicked.connect(self.btnInsertRow_Clicked)
        layBtns.addWidget(btnInsertRow)
        ###btnDeleteRows
        btnDeleteRows=QPushButton('删除行')
        btnDeleteRows.setToolTip('删除所有选中项所在的行')
        btnDeleteRows.clicked.connect(self.btnDeleteRows_Clicked)
        layBtns.addWidget(btnDeleteRows)
        ###btnQuery
        btnQuery=QPushButton('查询数据')
        btnQuery.setToolTip('对当前表或数据库进行查询,查询语句将被直接链接到self.model上')
        btnQuery.clicked.connect(self.btnQuery_Clicked)
        layBtns.addWidget(btnQuery)

        self.show()
        self.app.exec_()

    def __del__(self):
        #销毁多余数据库连接
        #self.Db.commit()
        self.Db.close()
    #----------------------------------------------------------------
    def makeTableInfo(self):
        #table_info=self.Db.execute('pragma table_info(%s)'%self.CurrentTable).fetchall()
        paragmastr="pragma table_info( '" + self.CurrentTable + "' ) "
        table_info=self.Db.execute(paragmastr).fetchall()
        self.columnsCount=len(table_info)
        self.columnsName=list(map(lambda x:x[1],table_info))
        self.columnsType=list(map(lambda x:x[2],table_info))
        dbinfo=self.Db.execute('select * from sqlite_master').fetchall()
        for x in dbinfo:
            if x[0]=='table' and x[1]==self.CurrentTable:
                self.sqlStr=x[4]
                break
    def DeleteColumn(self,tableName,columnName,tempName=''):
        if tempName=='':
            #tempName==''表示直接删除对应的列并提交数据库更改
            tempName=tableName+'temp'
            sqlite_master_sql="select * from sqlite_master"
            sqlite_master=self.Db.execute(sqlite_master_sql).fetchall()
            createStr=filter(lambda x:x[0]=='table' and x[1]==tableName,
                             self.Db.execute('select * from sqlite_master').fetchall())[0][4]
            createStr=','.join(filter(lambda x:x.find(columnName)==-1,createStr.split(',')))
            newColumns=','.join(map(lambda x:x[1],self.Db.execute('Pragma table_info(%s)'%tableName).fetchall()))
            #将旧表重命名为临时表名
            self.Db.execute("Alter Table %s Rename To %s"%(tableName,tempName))
            #新建删除了指定列的数据表
            self.Db.execute(createStr)
            #将旧表的数据导入新表
            self.Db.execute('Insert Into %s Select %s From %s'%
                            (tableName,newColumns,tempName))
            #删除旧表
            self.Db.execute('Drop Table %s'%tempName)
    #----------------------------------------------------------------
    def btnChangeDb_Clicked(self,event):
        pt=QFileDialog.getOpenFileName(
            caption='请选择一个sqlite数据库文件:',
            filter='sqlite数据库文件 (*.db)',
            directory=os.path.dirname(self.DbPath)
            )
        p=pt[0]
        if platform.system()=='Windows':
            p=p.replace('/','\\')
        if os.path.exists(p):
            self.DbPath=p
            self.Db=sqlite3.connect(self.DbPath)
            tbls=map(lambda x:x[1],
                 filter(lambda x:x[0]=='table',
                        self.Db.execute(
                            'Select * From sqlite_master'
                            ).fetchall()
                        )
                 )
            self.cbbTbls.currentIndexChanged.disconnect(self.changeTable)
            self.cbbTbls.clear()
            self.cbbTbls.addItems(tbls)
            self.cbbTbls.currentIndexChanged.connect(self.changeTable)
            self.CurrentTable=tbls[0]
            self.cbbTbls.setCurrentIndex(0)
            self.leDb.setText(p)
            self.model.database().setDatabaseName(self.DbPath)
            self.model.database().open()
            self.model.setTable(self.CurrentTable)
            self.model.select()
    def changeTable(self,event):
        if self.CurrentTable!=self.cbbTbls.itemText(event):
            self.CurrentTable=self.cbbTbls.itemText(event)
            self.model.setTable(self.CurrentTable)
            self.model.select()
            self.makeTableInfo()
            self.btnShow.setText('查看表结构')
    def btnDeleteTable_Clicked(self,event):
        self.Db.execute('Drop Table %s'%self.CurrentTable)
        for i in range(self.cbbTbls.count()-1,-1,-1):
            if self.cbbTbls.itemText(i)==self.CurrentTable:
                self.cbbTbls.removeItem(i)
                break
        self.CurrentTable=self.cbbTbls.itemText(0)
        self.model.setTable(self.CurrentTable)
        self.model.select()
    def btnRenameTable_Clicked(self,event):
        if self.leRename.text()!='':
            if self.leRename.text()!=self.CurrentTable:
                try:
                    self.Db.execute('Alter Table %s Rename To %s'%
                                (self.CurrentTable,self.leRename.text())
                                )
                except sqlite3.OperationalError as e:
                    if e.message=='there is already another table or index with this name: %s'%self.leRename.text():
                        QMessageBox.information(self,'错误',
                            '抱歉,本数据库中以“'+self.leRename.text()+
                            '”为名称的表或索引已经存在,无法完'+
                            '成重命名,请重新输入一个名称',
                            '知道了')
                    else:
                        QMessageBox.information(self,'错误',
                            '抱歉,可能是因表名包含非法字符,故'+
                            '无法完成重命名,请重新输入表名',
                            '知道了')
                    self.leRename.setText('')
                    return
                self.CurrentTable=self.leRename.text()
                self.cbbTbls.setItemText(self.cbbTbls.currentIndex(),
                                         self.CurrentTable
                                         )
                self.model.clear()
                self.model.setQuery(QSqlQuery(
                    'Select * From %s'%self.CurrentTable))
                self.model.select()
                self.leRename.setText('')
        else:
            QMessageBox.information(self,'注意',
                '抱歉,你还没有输入当前表要修改成的表名\n\n'+
                '请先在文本框里输入当前表要重命名成的名字,再点击我',
                '知道了')
    def btnShow_Clicked(self,event):
        if self.btnShow.text()=='查看表结构':
            self.model.setTable('')
            self.model.setQuery(QSqlQuery(
                'pragma table_info(%s)'%self.CurrentTable))
            self.model.select()
            self.btnShow.setText('查看表数据')
        else:
            self.model.setTable(self.CurrentTable)
            self.model.select()
            self.btnShow.setText('查看表结构')
    #----------------------------------------------------------------
    def btnInsertRow_Clicked(self,event):
        self.dlg_InsertRow_Values=[]
        #self.dlg
        self.dlg=QDialog()
        self.dlg.setWindowTitle('插入数据行:')
        #lay
        lay=QVBoxLayout()
        self.dlg.setLayout(lay)
        #lblprompt
        lblprompt=QLabel(
            '请参照创建此表的Sql字符串:\n'+self.sqlStr+
            '\n设置各个字段的数据:')
        lay.addWidget(lblprompt)
        #layG
        layG=QGridLayout()
        lay.addLayout(layG)
        for i in range(len(self.columnsName)):
            #lbl
            lbl=QLabel(self.columnsName[i]+'('+self.columnsType[i]+'):')
            lbl.setAlignment(Qt.AlignRight)
            layG.addWidget(lbl,i,0)
            #le
            le=QLineEdit()
            layG.addWidget(le,i,1)
            if self.columnsType[i].lower() not in self.SqliteDbTypes:
                #cbb
                cbb=QComboBox()
                cbb.addItems(self.SqliteDbTypes)
                cbb.setCurrentIndex(2)
                cbb.setToolTip(
                    '此字段的数据类型不是sqlite标准数据'+
                    '类型,请设置其存储时的使用的sqlite数据类型')
                layG.addWidget(cbb,i,2)
                self.dlg_InsertRow_Values.append((le,cbb))
            else:
                self.dlg_InsertRow_Values.append((le,self.columnsType[i]))
        layG.setColumnStretch(1,1)
        #layH
        layH=QHBoxLayout()
        lay.addLayout(layH)
        #btnOk
        btnOk=QPushButton('确定')
        btnOk.clicked.connect(self.dlg_InsertRow_btnOk_Clicked)
        layH.addWidget(btnOk)
        #btnCancel
        btnCancel=QPushButton('取消')
        btnCancel.clicked.connect(self.dlg.close)
        layH.addWidget(btnCancel)
        self.dlg.show()
    def dlg_InsertRow_btnOk_Clicked(self,event):
        sqlStr="Insert Into %s Values("%self.CurrentTable
        for item in self.dlg_InsertRow_Values:
            if item[0].text()!='':
                if type(item[1])==QComboBox:
                    print (item[0].text(),item[1].currentText())
                else:
                    print (item[0].text(),item[1])
            else:
                pass
    def btnDeleteRows_Clicked(self,event):
        rs=list(map(lambda x:x.row(),self.tv.selectedIndexes()))
        if len(rs)==0:
            QMessageBox.information(self,'提醒','请先选中至少一行,再点击此按钮!')
            return
        for i in reversed(rs):
            self.model.removeRows(i,1)
        self.model.submitAll()
    def btnQuery_Clicked(self,event):
        sqltxt,ok=QInputDialog.getText(self,'查询语句设置',
           '参照创建此表的Sql字符串:\n'+self.sqlStr+
           '\n请输入要设置到self.model的查询语句:')
        if ok:
            self.model.setTable('')
            self.model.setQuery(QSqlQuery(sqltxt))
            self.model.select()
    #----------------------------------------------------------------
    def btnAddColumn_Clicked(self,event):
        self.dlgMake_AddColumn()
    def dlgMake_AddColumn(self,lay=None):
        if lay is None:
            self.dlg=QDialog(self)
            self.dlg.setWindowTitle('添加列:')
        else:
            ##self.grpAddColumn
            self.grpAddColumn=QGroupBox('添加列:')
            self.grpAddColumn.setCheckable(True)
            self.grpAddColumn.setChecked(True)
            lay.addWidget(self.grpAddColumn)
	###layAddColumn
        layAddColumn=QVBoxLayout()
        if lay is None:
            self.dlg.setLayout(layAddColumn)
        else:
            self.grpAddColumn.setLayout(layAddColumn)
        ####self.grpAddColumn_ByCmdArgs
        self.grpAddColumn_ByCmdArgs=QGroupBox('使用参数创建列:')
        self.grpAddColumn_ByCmdArgs.setCheckable(True)
        self.grpAddColumn_ByCmdArgs.setChecked(True)
        self.PreviousChecked=0
        self.grpAddColumn_ByCmdArgs.toggled.connect(
            self.grpAddColumn_ByCmd_toggled)
        layAddColumn.addWidget(self.grpAddColumn_ByCmdArgs)
        #####layAddColumn_ByCmdArgs
        layAddColumn_ByCmdArgs=QHBoxLayout()
        self.grpAddColumn_ByCmdArgs.setLayout(layAddColumn_ByCmdArgs)
        ####lblAddColumn_select
        lblAddColumn_name=QLabel('列名:')
        layAddColumn_ByCmdArgs.addWidget(lblAddColumn_name)
        ####self.leAddColumn_name
        self.leAddColumn_name=QLineEdit()
        self.leAddColumn_name.setFixedWidth(100)
        layAddColumn_ByCmdArgs.addWidget(self.leAddColumn_name)
        ######lblAddColumn_type
        lblAddColumn_type=QLabel('类型:')
        layAddColumn_ByCmdArgs.addWidget(lblAddColumn_type)
        ######self.cbbAddColumn_type
        self.cbbAddColumn_type=QComboBox()
        self.cbbAddColumn_type.addItems(self.SqliteDbTypes)
        self.cbbAddColumn_type.setCurrentIndex(0)
        self.cbbAddColumn_type.setEditable(True)
        layAddColumn_ByCmdArgs.addWidget(self.cbbAddColumn_type)
        ######lblAddColumn_constraint
        lblAddColumn_constraint=QLabel('约束字符串:')
        layAddColumn_ByCmdArgs.addWidget(lblAddColumn_constraint)
        ######self.leAddColumn_constraint
        self.leAddColumn_constraint=QLineEdit()
        layAddColumn_ByCmdArgs.addWidget(self.leAddColumn_constraint)
        ####self.grpAddColumn_ByCmdStr
        self.grpAddColumn_ByCmdStr=QGroupBox('使用sql字符串创建列:')
        self.grpAddColumn_ByCmdStr.setCheckable(True)
        self.grpAddColumn_ByCmdStr.setChecked(False)
        self.grpAddColumn_ByCmdStr.toggled.connect(
            self.grpAddColumn_ByCmd_toggled)
        layAddColumn.addWidget(self.grpAddColumn_ByCmdStr)
        #####layAddColumn_ByCmdStr
        layAddColumn_ByCmdStr=QHBoxLayout()
        self.grpAddColumn_ByCmdStr.setLayout(layAddColumn_ByCmdStr)
        ######lblAddColumn_cmdstr
        lblAddColumn_cmdstr=QLabel('用来增加列的部分或完整Sql字符串:')
        layAddColumn_ByCmdStr.addWidget(lblAddColumn_cmdstr)
        ######self.leAddColumn_cmdstr
        self.leAddColumn_cmdstr=QLineEdit()
        layAddColumn_ByCmdStr.addWidget(self.leAddColumn_cmdstr)
        if lay is None:
            self.dlg.show()
    def grpAddColumn_ByCmd_toggled(self,event):
        if self.PreviousChecked==0:
            self.grpAddColumn_ByCmdStr.setChecked(True)
            self.grpAddColumn_ByCmdArgs.setChecked(False)
            self.PreviousChecked=1
        else:
            self.grpAddColumn_ByCmdArgs.setChecked(True)
            self.grpAddColumn_ByCmdStr.setChecked(False)
            self.PreviousChecked=0
    #----------------------------------------------------------------
    def btnDeleteColumn_Clicked(self,event):
        self.dlgMake_DeleteColumn()
    def dlgMake_DeleteColumn(self,lay=None):
        if lay is None:
            self.dlg=QDialog(self)
            self.dlg.setWindowTitle('删除列:')
        else:
            ##self.grpDeleteColumn
            self.grpDeleteColumn=QGroupBox('删除列:')
            self.grpDeleteColumn.setCheckable(True)
            self.grpDeleteColumn.setChecked(False)
            lay.addWidget(self.grpDeleteColumn)
        ###layDeleteColumn
        layDeleteColumn=QHBoxLayout()
        if lay is None:
            self.dlg.setLayout(layDeleteColumn)
        else:
            self.grpDeleteColumn.setLayout(layDeleteColumn)
        ###layColumnList
        layColumnList=QVBoxLayout()
        layDeleteColumn.addLayout(layColumnList)
        ####lblDeleteColumn
        lblDeleteColumn=QLabel('原有的所有列:')
        layColumnList.addWidget(lblDeleteColumn)
        ####self.lstColumnList
        self.lstColumnList=QListWidget()
        self.lstColumnList.addItems(self.columnsName)
        self.lstColumnList.setFixedWidth(150)
        layColumnList.addWidget(self.lstColumnList)
        ###layDeleteBtns
        layDeleteBtns=QVBoxLayout()
        layDeleteColumn.addLayout(layDeleteBtns)
        ####btnDeleteColumn_Store
        btnDeleteColumn_Store=QPushButton('>>')
        btnDeleteColumn_Store.setFixedWidth(50)
        layDeleteBtns.addWidget(btnDeleteColumn_Store)
        ####btnDeleteColumn_Unstore
        btnDeleteColumn_Unstore=QPushButton('<<')
        btnDeleteColumn_Unstore.setFixedWidth(50)
        layDeleteBtns.addWidget(btnDeleteColumn_Unstore)
        ###layColumnsToDelete
        layColumnsToDelete=QVBoxLayout()
        layDeleteColumn.addLayout(layColumnsToDelete)
        ####lblColumnsToDelete
        lblColumnsToDelete=QLabel('要删除的列:')
        layColumnsToDelete.addWidget(lblColumnsToDelete)
        ####self.lstColumnsToDelete
        self.lstColumnsToDelete=QListWidget()
        self.lstColumnsToDelete.setFixedWidth(150)
        layColumnsToDelete.addWidget(self.lstColumnsToDelete)
        if lay is None:
            self.dlg.show()
    #----------------------------------------------------------------
    def btnRenameColumn_Clicked(self,event):
        self.dlgMake_RenameColumn()
    def dlgMake_RenameColumn(self,lay=None):
        if lay is None:
            self.dlg=QDialog(self)
            self.dlg.setWindowTitle('重命名列:')
        else:
            ##self.grpRenameColumn
            self.grpRenameColumn=QGroupBox('重命名列:')
            self.grpRenameColumn.setCheckable(True)
            self.grpRenameColumn.setChecked(False)
            lay.addWidget(self.grpRenameColumn)
        ###layRenameColumn
        layRenameColumn=QHBoxLayout()
        if lay is None:
            self.dlg.setLayout(layRenameColumn)
        else:
            self.grpRenameColumn.setLayout(layRenameColumn)
        ####lblRenameColumn_select
        lblRenameColumn_select=QLabel('选择列:')
        layRenameColumn.addWidget(lblRenameColumn_select)
        ####self.cbbRenameColumn_select
        self.cbbRenameColumn_select=QComboBox()
        self.cbbRenameColumn_select.addItems(self.columnsName)
        layRenameColumn.addWidget(self.cbbRenameColumn_select)
        ####lblRenameColumn_renameto
        lblRenameColumn_renameto=QLabel('重命名为:')
        layRenameColumn.addWidget(lblRenameColumn_renameto)
        ####self.leRenameColumn_renameto
        self.leRenameColumn_renameto=QLineEdit()
        self.leRenameColumn_renameto.setFixedWidth(80)
        layRenameColumn.addWidget(self.leRenameColumn_renameto)
        ####btnRenameColumn_Store
        btnRenameColumn_Store=QPushButton('标记 >>')
        layRenameColumn.addWidget(btnRenameColumn_Store)
        ####self.cbbRenameColumn_Store
        self.cbbRenameColumn_Store=QComboBox()
        layRenameColumn.addWidget(self.cbbRenameColumn_Store,1)
        if lay is None:
            self.dlg.show()
    #----------------------------------------------------------------
    def btnModifyColumnType_Clicked(self,event):
        self.dlgMake_ModifyColumnType()
    def dlgMake_ModifyColumnType(self,lay=None):
        if lay is None:
            self.dlg=QDialog(self)
            self.dlg.setWindowTitle('修改列数据类型:')
        else:
            ##self.grpModifyColumnType
            self.grpModifyColumnType=QGroupBox('修改列数据类型:')
            self.grpModifyColumnType.setCheckable(True)
            self.grpModifyColumnType.setChecked(False)
            lay.addWidget(self.grpModifyColumnType)
        ###layModifyColumnType
        layModifyColumnType=QHBoxLayout()
        if lay is None:
            self.dlg.setLayout(layModifyColumnType)
        else:
            self.grpModifyColumnType.setLayout(layModifyColumnType)
        ####lblModifyColumnType_select
        lblModifyColumnType_select=QLabel('选择列:')
        layModifyColumnType.addWidget(lblModifyColumnType_select)
        ####self.cbbModifyColumnType_select
        self.cbbModifyColumnType_select=QComboBox()
        self.cbbModifyColumnType_select.addItems(self.columnsName)
        layModifyColumnType.addWidget(self.cbbModifyColumnType_select)
        ####lblModifyColumnType_modifyto
        lblModifyColumnType_modifyto=QLabel('改类型为:')
        layModifyColumnType.addWidget(lblModifyColumnType_modifyto)
        ####self.cbbModifyColumnType_modifyto
        self.cbbModifyColumnType_modifyto=QComboBox()
        self.cbbModifyColumnType_modifyto.setEditable(True)
        self.cbbModifyColumnType_modifyto.addItems(self.SqliteDbTypes)
        self.cbbModifyColumnType_modifyto.setCurrentIndex(2)
        self.cbbModifyColumnType_modifyto.setFixedWidth(80)
        layModifyColumnType.addWidget(self.cbbModifyColumnType_modifyto)
        ####btnModifyColumnType_Store
        btnModifyColumnType_Store=QPushButton('标记 >>')
        layModifyColumnType.addWidget(btnModifyColumnType_Store)
        ####self.cbbModifyColumnType_Store
        self.cbbModifyColumnType_Store=QComboBox()
        layModifyColumnType.addWidget(self.cbbModifyColumnType_Store,1)
        if lay is None:
            self.dlg.show()
    #----------------------------------------------------------------
    def btnModifyColumnConstraint_Clicked(self,event):
        self.dlgMake_ModifyColumnConstraint()
    def dlgMake_ModifyColumnConstraint(self,lay=None):
        if lay is None:
            self.dlg=QDialog(self)
            self.dlg.setWindowTitle('修改列约束:')
        else:
            ##self.grpModifyColumnConstraint
            self.grpModifyColumnConstraint=QGroupBox('修改列约束:')
            self.grpModifyColumnConstraint.setCheckable(True)
            self.grpModifyColumnConstraint.setChecked(False)
            lay.addWidget(self.grpModifyColumnConstraint)
        ###layModifyColumnConstraint
        layModifyColumnConstraint=QHBoxLayout()
        if lay is None:
            self.dlg.setLayout(layModifyColumnConstraint)
        else:
            self.grpModifyColumnConstraint.setLayout(layModifyColumnConstraint)
        ####lblModifyColumnConstraint_select
        lblModifyColumnConstraint_select=QLabel('选择列:')
        layModifyColumnConstraint.addWidget(lblModifyColumnConstraint_select)
        ####self.cbbModifyColumnConstraint_select
        self.cbbModifyColumnConstraint_select=QComboBox()
        self.cbbModifyColumnConstraint_select.addItems(self.columnsName)
        layModifyColumnConstraint.addWidget(self.cbbModifyColumnConstraint_select)
        ####lblModifyColumnConstraint_modifyto
        lblModifyColumnConstraint_modifyto=QLabel('约束改为:')
        layModifyColumnConstraint.addWidget(lblModifyColumnConstraint_modifyto)
        ####self.leModifyColumnConstraint_modifyto
        self.leModifyColumnConstraint_modifyto=QLineEdit()
        self.leModifyColumnConstraint_modifyto.setFixedWidth(80)
        layModifyColumnConstraint.addWidget(self.leModifyColumnConstraint_modifyto)
        ####btnModifyColumnConstraint_Store
        btnModifyColumnConstraint_Store=QPushButton('标记 >>')
        layModifyColumnConstraint.addWidget(btnModifyColumnConstraint_Store)
        ####self.cbbModifyColumnConstraint_Store
        self.cbbModifyColumnConstraint_Store=QComboBox()
        layModifyColumnConstraint.addWidget(self.cbbModifyColumnConstraint_Store,1)
        if lay is None:
            self.dlg.show()
    #----------------------------------------------------------------
    def btnOrderColumns_Clicked(self,event):
        self.dlgMake_OrderColumns()
    def dlgMake_OrderColumns(self,lay=None):
        if lay is None:
            self.dlg=QDialog(self)
            self.dlg.setWindowTitle('调整列顺序:')
        else:
            ##self.grpAdjustColumnOrder
            self.grpAdjustColumnOrder=QGroupBox('调整列顺序:')
            self.grpAdjustColumnOrder.setCheckable(True)
            self.grpAdjustColumnOrder.setChecked(False)
            lay.addWidget(self.grpAdjustColumnOrder)
        ###layAdjustColumnOrder
        layAdjustColumnOrder=QVBoxLayout()
        if lay is None:
            self.dlg.setLayout(layAdjustColumnOrder)
        else:
            self.grpAdjustColumnOrder.setLayout(layAdjustColumnOrder)
        ####lblAdjustColumnOrder
        lblAdjustColumnOrder=QLabel('请调整列顺序:')
        layAdjustColumnOrder.addWidget(lblAdjustColumnOrder)
        ####self.lstAdjustColumnOrder
        self.lstAdjustColumnOrder=QListWidget()
        self.lstAdjustColumnOrder.addItems(self.columnsName)
        self.lstAdjustColumnOrder.setFixedWidth(150)
        layAdjustColumnOrder.addWidget(self.lstAdjustColumnOrder)
        if lay is None:
            self.dlg.setFixedWidth(175)
            self.dlg.show()
    #----------------------------------------------------------------
    def btnModifyTableStruct_Clicked(self,event):
        self.dlg=QDialog(self)
        self.dlg.setWindowTitle(self.CurrentTable+'表结构修改:')
        self.dlg.setWindowFlags(Qt.Window|
                           Qt.MSWindowsFixedSizeDialogHint
                           )
        #lay
        lay=QVBoxLayout()
        self.dlgMake_AddColumn(lay)
        self.dlgMake_RenameColumn(lay)
        self.dlgMake_ModifyColumnType(lay)
        self.dlgMake_ModifyColumnConstraint(lay)
        #layLists
        layLists=QHBoxLayout()
        lay.addLayout(layLists)
        self.dlgMake_DeleteColumn(layLists)
        self.dlgMake_OrderColumns(layLists)
        ##layBtns
        layBtns=QHBoxLayout()
        lay.addLayout(layBtns)
        ##btnOk
        btnOk=QPushButton('提交修改')
        btnOk.clicked.connect(self.btnOk_Clicked)
        layBtns.addWidget(btnOk)
        ##btnCancel
        btnCancel=QPushButton('放弃修改')
        btnCancel.clicked.connect(self.btnCancel_Clicked)
        layBtns.addWidget(btnCancel)

        self.dlg.setLayout(lay)
        self.dlg.open()
    def btnOk_Clicked(self,event):
        #do something here
        self.dlg.close()
    def btnCancel_Clicked(self,event):
        self.dlg.close()
예제 #32
0
class TorrentPreferencesDialog(QDialog):
    dataReady = pyqtSignal(dict)

    def __init__(self, parent, torrent_info):
        super().__init__(parent)
        self.torrentInfo = torrent_info

        self.setUp()

    def setUp(self):
        self.setWindowTitle("Torrent settings")

        parentRect = self.parentWidget().geometry()
        self.resize(parentRect.width() * 0.75, parentRect.height() * 0.9)
        self.setMinimumSize(self.size())

        # Create the dialog layout
        self.layout = QVBoxLayout(self)

        # Set up the destination folder selector
        self.setUpDialogHeader()
        # Set up the file lister for the torrent file
        self.setUpFileLister()
        # Set up the whole torrent priority combo box and buttons
        self.setUpDialogFooter()

    def setUpDialogHeader(self):
        headerLayout = QGridLayout()
        self.destinationFolder = paths.writableLocation(paths.DownloadLocation)
        torrentName = self.torrentInfo.name()

        # Show the torrent name row
        nameLabel = QLabel("Torrent name:", self)
        headerLayout.addWidget(nameLabel, 0, 0)

        nameEdit = QLineEdit(torrentName, self)
        nameEdit.setReadOnly(True)
        headerLayout.addWidget(nameEdit, 0, 1)

        # Show the destination folder row
        dirLabel = QLabel("Destination folder:", self)
        headerLayout.addWidget(dirLabel, 1, 0)

        self.textField = QLineEdit(self.destinationFolder, self)
        self.textField.setReadOnly(True)
        headerLayout.addWidget(self.textField, 1, 1)

        button = QPushButton("Browse", self)
        button.clicked.connect(self.selectFolder)
        headerLayout.addWidget(button, 1, 2)

        self.layout.addLayout(headerLayout)

    def selectFolder(self):
        newDir = str(QFileDialog.getExistingDirectory(self,
                                                      "Select Directory"))
        if newDir:
            self.textField.setText(newDir)
            self.destinationFolder = newDir

    def setUpFileLister(self):
        self.files = [(f.path, f.size) for f in self.torrentInfo.files()]
        self.treeView = QTreeWidget(self)
        self.treeView.setColumnCount(3)
        self.treeView.setColumnWidth(0, 350)
        self.treeView.setColumnWidth(1, 80)
        self.treeView.setHeaderLabels(["Name", "size", "Priority"])
        self.treeView.setExpandsOnDoubleClick(False)

        if len(self.files) == 1:
            tree = file_tree.FileTree(self.files[0][0], self.files[0][1])
        else:
            tree = file_tree.FileTree(self.files[0][0].split('/')[0], 0)
            for f in self.files:
                tree.add_file(f[0], f[1])

        rootItem = TreeNodeItem(tree.get_root(), self.treeView)
        self.treeView.addTopLevelItem(rootItem)
        self.treeView.expandAll()
        self.treeView.itemClicked.connect(self.rowClicked)
        self.layout.addWidget(self.treeView)

    def rowClicked(self, item, column):
        if item.checkState(0) == Qt.PartiallyChecked:
            item.setCheckState(0, Qt.Checked)

        if column == 2:
            priorityChanges = {'Normal': 'High',
                               'High': 'Low',
                               'Low': 'Normal',
                               'Mixed': 'Normal'}
            newPriority = priorityChanges[item.text(2)]
            self.changeTextOfAllChildren(item, 2, newPriority)

            self.reprioritize(item)

    def changeTextOfAllChildren(self, item, column, text):
        item.setText(column, text)
        for i in range(0, item.childCount()):
            self.changeTextOfAllChildren(item.child(i), column, text)

    def reprioritize(self, start_node):
        parent = start_node.parent()
        if parent:
            if self.allChildrenHaveSamePriority(parent):
                parent.setText(2, start_node.text(2))
            else:
                parent.setText(2, "Mixed")

            self.reprioritize(parent)

    def allChildrenHaveSamePriority(self, node):
        for i in range(1, node.childCount()):
            if node.child(i - 1).text(2) != node.child(i).text(2):
                return False

        return True

    def setUpDialogFooter(self):
        footerLayout = QGridLayout()
        footerLayout.setColumnStretch(0, 4)

        footerLayout.addWidget(QLabel("Torrent priority"), 0, 1)
        self.priorityComboBox = QComboBox(self)
        self.priorityComboBox.addItems(["High", "Normal", "Low"])
        self.priorityComboBox.setCurrentIndex(1)
        footerLayout.addWidget(self.priorityComboBox, 0, 2)

        secondRowLayout = QHBoxLayout()

        OKButton = QPushButton("Open", self)
        OKButton.setFocus()
        OKButton.clicked.connect(self.accept)
        cancelButton = QPushButton("Cancel", self)
        cancelButton.clicked.connect(self.reject)
        secondRowLayout.addWidget(OKButton)
        secondRowLayout.addWidget(cancelButton)
        footerLayout.addLayout(secondRowLayout, 1, 2)

        self.layout.addLayout(footerLayout)

    def accept(self):
        torrentPriorities = {"Low": 0, "Normal": 127, "High": 255}
        filePriorities = {"Low": 1, "Normal": 4, "High": 7}

        it = QTreeWidgetItemIterator(self.treeView,
                                     QTreeWidgetItemIterator.NoChildren)

        itemsInfo = {}
        while it.value():
            currentItem = it.value()
            if currentItem.checkState(0) == Qt.Unchecked:
                priority = 0
            else:
                priority = filePriorities[currentItem.text(2)]

            itemsInfo[self.getFullPath(currentItem)] = priority
            it += 1

        paths = [f.path for f in self.torrentInfo.files()]
        self.prioritiesList = [itemsInfo[p] for p in paths]

        comboBoxIndex = self.priorityComboBox.currentIndex()
        self.priority = torrentPriorities[self.priorityComboBox.itemText(
                                                                comboBoxIndex)]

        self.hide()
        self.dataReady.emit(self.getData())
        super().accept()

    def getFullPath(self, treeItem):
        items = [treeItem.text(0)]
        parent = treeItem.parent()

        while parent:
            items.append(parent.text(0))
            parent = parent.parent()

        return '/'.join(reversed(items))

    def getData(self):
        return {'info': self.torrentInfo,
                'destination_folder': self.destinationFolder,
                'torrent_priority': self.priority,
                'file_priorities': self.prioritiesList}
예제 #33
0
class Preferences(QDialog):
    # Signal to warn that the window is closed
    settingsClosed = pyqtSignal()

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

        # Main container
        # This contains a grid
        main_box = QVBoxLayout(self)
        main_box.setContentsMargins(200, 50, 200, 100)

        # The grid contains two containers
        # left container and right container
        grid = QGridLayout()

        # Left Container
        left_container = QVBoxLayout()
        left_container.setContentsMargins(0, 0, 0, 0)

        # General
        group_gral = QGroupBox(self.tr("General"))
        box_gral = QVBoxLayout(group_gral)
        # Updates
        btn_updates = QPushButton(self.tr("Check for updates"))
        box_gral.addWidget(btn_updates)
        # Language
        group_language = QGroupBox(self.tr("Language"))
        box = QVBoxLayout(group_language)
        # Find .qm files in language path
        available_langs = file_manager.get_files_from_folder(
            settings.LANGUAGE_PATH)

        languages = ["English"] + available_langs
        self._combo_lang = QComboBox()
        box.addWidget(self._combo_lang)
        self._combo_lang.addItems(languages)
        self._combo_lang.currentIndexChanged[int].connect(
            self._change_lang)
        if PSetting.LANGUAGE:
            self._combo_lang.setCurrentText(PSetting.LANGUAGE)
        box.addWidget(QLabel(self.tr("(Requires restart)")))

        # Add widgets
        left_container.addWidget(group_gral)
        left_container.addWidget(group_language)
        left_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                           QSizePolicy.Expanding))

        # Right Container
        right_container = QVBoxLayout()
        right_container.setContentsMargins(0, 0, 0, 0)

        # Editor
        editor_group = QGroupBox(self.tr("Editor Configurations"))
        box_editor = QHBoxLayout(editor_group)
        # Current line
        self._highlight_current_line = QCheckBox(
            self.tr("Highlight Current Line"))
        self._highlight_current_line.setChecked(
            PSetting.HIGHLIGHT_CURRENT_LINE)
        self._highlight_current_line.stateChanged[int].connect(
            self.__current_line_value_changed)
        box_editor.addWidget(self._highlight_current_line)
        # Matching paren
        self._matching_paren = QCheckBox(self.tr("Matching Parenthesis"))
        self._matching_paren.setChecked(
            PSetting.MATCHING_PARENTHESIS)
        self._matching_paren.stateChanged[int].connect(
            self.__set_enabled_matching_parenthesis)
        box_editor.addWidget(self._matching_paren)
        # Font group
        font_group = QGroupBox(self.tr("Font"))
        font_grid = QGridLayout(font_group)
        font_grid.addWidget(QLabel(self.tr("Family")), 0, 0)
        self._combo_font = QFontComboBox()
        self._combo_font.setCurrentFont(PSetting.FONT)
        font_grid.addWidget(self._combo_font, 0, 1)
        font_grid.addWidget(QLabel(self.tr("Point Size")), 1, 0)
        self._combo_font_size = QComboBox()
        fdb = QFontDatabase()
        combo_sizes = fdb.pointSizes(PSetting.FONT.family())
        current_size_index = combo_sizes.index(
            PSetting.FONT.pointSize())

        self._combo_font_size.addItems([str(f) for f in combo_sizes])
        self._combo_font_size.setCurrentIndex(current_size_index)
        font_grid.addWidget(self._combo_font_size, 1, 1)

        right_container.addWidget(editor_group)
        right_container.addWidget(font_group)
        right_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding,
                                            QSizePolicy.Expanding))

        # Add widgets
        grid.addLayout(left_container, 0, 0)
        grid.addLayout(right_container, 0, 1)
        main_box.addLayout(grid)

        # Button close and reset
        hbox = QHBoxLayout()
        hbox.setSpacing(20)
        hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        btn_cancel = QPushButton(self.tr("Back"))
        hbox.addWidget(btn_cancel)
        btn_reset = QPushButton(self.tr("Reset Configurations"))
        hbox.addWidget(btn_reset)
        main_box.addLayout(hbox)

        # Overlay
        self.overlay = overlay_widget.OverlayWidget(self)
        self.overlay.hide()

        # Effect and animations
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        duration, x = 180, 150  # Animation duration
        # Animation start
        # Opacity animation
        self.opacity_animation_s = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_s.setDuration(duration)
        self.opacity_animation_s.setStartValue(0.0)
        self.opacity_animation_s.setEndValue(1.0)
        # X animation
        self.x_animation_s = QPropertyAnimation(self, b"geometry")
        self.x_animation_s.setDuration(duration)
        self.x_animation_s.setStartValue(QRect(x, 0, parent.width(),
                                               parent.height()))
        self.x_animation_s.setEndValue(QRect(0, 0, parent.width(),
                                             parent.height()))
        # Animation end
        # Opacity animation
        self.opacity_animation_e = QPropertyAnimation(self.effect, b"opacity")
        self.opacity_animation_e.setDuration(duration)
        self.opacity_animation_e.setStartValue(1.0)
        self.opacity_animation_e.setEndValue(0.0)
        # X animation
        self.x_animation_e = QPropertyAnimation(self, b"geometry")
        self.x_animation_e.setDuration(duration)
        self.x_animation_e.setStartValue(QRect(0, 0, parent.width(),
                                               parent.height()))
        self.x_animation_e.setEndValue(QRect(-x, 0, parent.width(),
                                             parent.height()))

        # Group animation start
        self.group_animation_s = QParallelAnimationGroup()
        self.group_animation_s.addAnimation(self.opacity_animation_s)
        self.group_animation_s.addAnimation(self.x_animation_s)

        # Group animation end
        self.group_animation_e = QParallelAnimationGroup()
        self.group_animation_e.addAnimation(self.opacity_animation_e)
        self.group_animation_e.addAnimation(self.x_animation_e)

        # Connections
        self.group_animation_e.finished.connect(
            self._on_group_animation_finished)
        btn_cancel.clicked.connect(self.close)
        btn_reset.clicked.connect(self._reset_settings)
        btn_updates.clicked.connect(self._check_for_updates)
        # self.thread.finished.connect(self._on_thread_finished)
        self._combo_font.currentFontChanged.connect(
            self._change_font)
        self._combo_font_size.currentTextChanged.connect(
            self._change_font_size)

    def __current_line_value_changed(self, value):
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue('highlight_current_line', value)
        PSetting.HIGHLIGHT_CURRENT_LINE = value

    def __set_enabled_matching_parenthesis(self, value):
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue("matching_parenthesis", value)
        PSetting.MATCHING_PARENTHESIS = value

    def _change_font(self, font):
        # FIXME: un quilombo esto
        central = Pireal.get_service("central")
        mcontainer = central.get_active_db()
        if mcontainer is not None:
            query_widget = mcontainer.query_container.currentWidget()
            if query_widget is not None:
                weditor = query_widget.get_editor()
                if weditor is not None:
                    qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
                    weditor.set_font(font)
                    qs.setValue("font", font)

    def _change_font_size(self, size):
        # FIXME: un quilombo esto
        font = self._combo_font.currentFont()
        font.setPointSize(int(size))
        central = Pireal.get_service("central")
        mcontainer = central.get_active_db()
        if mcontainer is not None:
            query_widget = mcontainer.query_container.currentWidget()
            if query_widget is not None:
                weditor = query_widget.get_editor()
                if weditor is not None:
                    qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
                    weditor.set_font(font)
                    qs.setValue("font", font)

    def showEvent(self, event):
        super(Preferences, self).showEvent(event)
        self.group_animation_s.start()

    def resizeEvent(self, event):
        self.overlay.resize(self.size())
        event.accept()

    def done(self, result):
        self.res = result
        self.group_animation_e.start()

    def _on_group_animation_finished(self):
        super(Preferences, self).done(self.res)
        self.settingsClosed.emit()

    def _check_for_updates(self):
        # Thread
        self._thread = QThread()
        self._updater = updater.Updater()
        self._updater.moveToThread(self._thread)
        self._thread.started.connect(self._updater.check_updates)
        self._updater.finished.connect(self.__on_thread_update_finished)
        # Show overlay widget
        self.overlay.show()
        # Start thread
        self._thread.start()

    def __on_thread_update_finished(self):
        # Hide overlay widget
        self.overlay.hide()
        self._thread.quit()
        msg = QMessageBox(self)
        if not self._updater.error:
            if self._updater.version:
                version = self._updater.version
                msg.setWindowTitle(self.tr("New version available!"))
                msg.setText(self.tr("Check the web site to "
                                    "download <b>Pireal {}</b>".format(
                                        version)))
                download_btn = msg.addButton(self.tr("Download!"),
                                             QMessageBox.YesRole)
                msg.addButton(self.tr("Cancel"),
                              QMessageBox.RejectRole)
                msg.exec_()
                r = msg.clickedButton()
                if r == download_btn:
                    webbrowser.open_new(
                        "http://centaurialpha.github.io/pireal")
            else:
                msg.setWindowTitle(self.tr("Information"))
                msg.setText(self.tr("Last version installed"))
                msg.addButton(self.tr("Ok"),
                              QMessageBox.AcceptRole)
                msg.exec_()
        else:
            msg.critical(self, self.tr("Error"),
                         self.tr("Connection error"))

        self._thread.deleteLater()
        self._updater.deleteLater()

    def _reset_settings(self):
        """ Remove all settings """

        msg = QMessageBox(self)
        msg.setWindowTitle(self.tr("Reset Settings"))
        msg.setText(self.tr("Are you sure you want to clear all settings?"))
        msg.setIcon(QMessageBox.Question)
        msg.addButton(self.tr("No"), QMessageBox.NoRole)
        yes_btn = msg.addButton(self.tr("Yes"),
                                QMessageBox.YesRole)
        msg.exec_()
        r = msg.clickedButton()
        if r == yes_btn:
            QSettings(settings.SETTINGS_PATH, QSettings.IniFormat).clear()
            self.close()

    def _change_lang(self, index):
        lang = self._combo_lang.itemText(index)
        qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
        qs.setValue('language', lang)
예제 #34
0
class VideoFinderAddLink(AddLinkWindow):
    formats_showing = []
    media_title = ''
    running_thread = None
    threadPool = {}

    def __init__(self, parent, receiver_slot, settings, video_dict={}):
        super().__init__(parent, receiver_slot, settings, video_dict)
        self.setWindowTitle(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video Finder'))
        self.size_label.hide()
		
# add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)


        # Fetch Button
        self.url_submit_button = QPushButton(self.link_frame)
        self.link_horizontalLayout.addWidget(self.url_submit_button)

        # Status Box
        self.status_box = QTextEdit(self.link_frame)
        self.status_box.setMaximumHeight(150)
        self.link_verticalLayout.addWidget(self.status_box)

        # Select format horizontal layout
        select_format_hl = QHBoxLayout()

        # Selection Label
        select_format_label = QLabel(self.link_frame)
        select_format_hl.addWidget(select_format_label)

        # Selection combobox
        self.media_combo = QComboBox(self.link_frame)
        self.media_combo.setMinimumWidth(200)
        select_format_hl.addWidget(self.media_combo)

        # Duration label
        self.duration_label = QLabel(self.link_frame)
        select_format_hl.addWidget(self.duration_label)

        self.selection_line = QFrame(self)
        self.selection_line.setLayout(select_format_hl)
        self.link_verticalLayout.addWidget(self.selection_line)

        # Set Texts
        self.url_submit_button.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetch Media List'))
        self.ok_pushButton.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Download Now'))
        select_format_label.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Select a format'))


        # Add Slot Connections
        self.url_submit_button.setEnabled(False)
        self.change_name_lineEdit.setEnabled(False)
        self.ok_pushButton.setEnabled(False)
        self.download_later_pushButton.setEnabled(False)


        self.url_submit_button.clicked.connect(self.submit_clicked)
        self.media_combo.currentIndexChanged.connect(self.media_selection_changed)
        self.link_lineEdit.textChanged.disconnect(super().linkLineChanged)  # Should be disconnected.
        self.link_lineEdit.textChanged.connect(self.linkLineChangedHere)

        self.setMinimumSize(500, 400)

        self.status_box.hide()
        self.selection_line.hide()

        if 'link' in video_dict.keys() and video_dict['link']:
            self.link_lineEdit.setText(video_dict['link'])
            self.url_submit_button.setEnabled(True)
        else:
            # check clipboard
            clipboard = QApplication.clipboard()
            text = clipboard.text()
            if (("tp:/" in text[2:6]) or ("tps:/" in text[2:7])):
                self.link_lineEdit.setText(str(text))

            self.url_submit_button.setEnabled(True)

    # Define native slots
    def url_changed(self, value):
        if ' ' in value or value == '':
            self.url_submit_button.setEnabled(False)
            self.url_submit_button.setToolTip(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Please enter a valid video link'))
        else:
            self.url_submit_button.setEnabled(True)
            self.url_submit_button.setToolTip('')

    def submit_clicked(self, button=None):
        # Clear media list
        self.media_combo.clear()
        self.selection_line.hide()
        self.change_name_lineEdit.clear()
        self.threadPool.clear()
        self.change_name_checkBox.setChecked(False)
        self.formats_showing.clear()
        self.url_submit_button.setEnabled(False)
        self.status_box.setText(QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetching Media Info...'))
        self.status_box.show()
        self.ok_pushButton.setEnabled(False)
        self.download_later_pushButton.setEnabled(False)

        dictionary_to_send = deepcopy(self.plugin_add_link_dictionary)
        # More options
        more_options = self.collect_more_options()
        for k in more_options.keys():
            dictionary_to_send[k] = more_options[k]
        dictionary_to_send['link'] = self.link_lineEdit.text()
        fetcher_thread = MediaListFetcherThread(self.fetched_result, dictionary_to_send, self)
        self.running_thread = fetcher_thread
        fetcher_thread.start()

    def filename_changed(self, value):
        if value.strip() == '':
            self.ok_pushButton.setEnabled(False)

    def media_selection_changed(self):
        try:
            self.change_name_lineEdit.setText(self.media_title + '.' +
                                              self.formats_showing[self.media_combo.currentIndex()]['ext'])
            self.change_name_checkBox.setChecked(True)
        except Exception as ex:
            logger.sendToLog(ex, "ERROR")

    def okButtonPressed(self, button, download_later):
        index = self.media_combo.currentIndex()
        self.link_lineEdit.setText(self.formats_showing[index]['url'])
        super().okButtonPressed(button, download_later)

    def fetched_result(self, media_dict):
        self.url_submit_button.setEnabled(True)
        if 'error' in media_dict.keys():
            self.status_box.setText('<font color="#f11">' + str(media_dict['error']) + '</font>')
            self.status_box.show()
        else:  # Show the media list
            self.media_title = media_dict['title']
            i = 0
            if 'formats' not in media_dict.keys() and 'entries' in media_dict.keys():
                formats = media_dict['entries']
                formats = formats[0]
                media_dict['formats'] = formats['formats']
            elif 'formats' not in media_dict.keys() and 'format' in media_dict.keys():
                media_dict['formats'] = [media_dict.copy()]

            try:
                for f in media_dict['formats']:
                    text = ''
                    if 'acodec' in f.keys():
                        if f['acodec'] == 'none' and f['vcodec'] != 'none' and self.persepolis_setting.value('settings/video_finder/hide_no_audio', 'yes') == 'yes':
                            continue
                        if f['acodec'] == 'none':
                            text = 'No Audio {}p'.format(f['height'])

                    if 'vcodec' in f.keys():
                        if f['vcodec'] == 'none' and f['acodec'] != 'none' and self.persepolis_setting.value('settings/video_finder/hide_no_video', 'yes') == 'yes':
                            continue

                        if f['vcodec'] == 'none':  # No video, show audio bit rate
                            text = 'Only Audio {}kbps'.format(f['abr'])

                    if 'height' in f.keys():
                        text = '{}p'.format(f['height'])

                    if 'ext' in f.keys():
                        text = '{} .{}'.format(text, f['ext'])

                    if 'filesize' in f.keys() and f['filesize']:
                        # Youtube api does not supply file size for some formats, so check it.
                        text = '{} - {}'.format(text, get_readable_size(f['filesize']))

                    else:  # Start spider to find file size
                        input_dict = deepcopy(self.plugin_add_link_dictionary)

                        # input_dict['out'] = self.media_title + str(f['ext'])
                        input_dict['link'] = f['url']
                        more_options = self.collect_more_options()

                        for key in more_options.keys():
                            input_dict[key] = more_options[key]
                        size_fetcher = FileSizeFetcherThread(input_dict, i, self.file_size_found)
                        self.threadPool[str(i)] = {'thread': size_fetcher, 'item_id': i}
                        size_fetcher.start()

                    # Add current format to combobox
                    self.formats_showing.append(f)
                    self.media_combo.addItem(text)
                    i = i + 1
            except Exception as ex:
                logger.sendToLog(ex, "ERROR")

            self.status_box.hide()

            if 'duration' in media_dict.keys():
                self.duration_label.setText('Duration ' + get_readable_duration(media_dict['duration']))

            self.selection_line.show()
            self.ok_pushButton.setEnabled(True)
            self.download_later_pushButton.setEnabled(True)

    def file_size_found(self, result):
        try:
            item_id = self.threadPool[str(result['thread_key'])]['item_id']
            if result['file_size'] and result['file_size'] != '0':
                text = self.media_combo.itemText(item_id)
                self.media_combo.setItemText(item_id, '{} - {}'.format(text, result['file_size']))
            else:  # Retry
                sleep(0.8)
                self.threadPool[str(result['thread_key'])]['thread'].start()
        except Exception as ex:
            logger.sendToLog(ex, "ERROR")

    def linkLineChangedHere(self, lineEdit):
        if str(lineEdit) == '':
            self.url_submit_button.setEnabled(False)
        else:
            self.url_submit_button.setEnabled(True)

    # This method collects additional information like proxy ip, user, password etc.
    def collect_more_options(self):
        options = {'ip': None, 'port': None, 'proxy_user': None, 'proxy_passwd': None, 'download_user': None,
                   'download_passwd': None}
        if self.proxy_checkBox.isChecked():
            options['ip'] = self.ip_lineEdit.text()
            options['port'] = self.port_spinBox.value()
            options['proxy_user'] = self.proxy_user_lineEdit.text()
            options['proxy_passwd'] = self.proxy_pass_lineEdit.text()
        if self.download_checkBox.isChecked():
            options['download_user'] = self.download_user_lineEdit.text()
            options['download_passwd'] = self.download_pass_lineEdit.text()

        # These info (keys) are required for spider to find file size, because spider() does not check if key exists.
        additional_info = ['header', 'load_cookies', 'user_agent', 'referer', 'out']
        for i in additional_info:
            if i not in self.plugin_add_link_dictionary.keys():
                options[i] = None
        return options
    def on_form_open(db_path, add_functions_class, wo_order_window, parent,
                     wo_orders_table, wo_orders_model):
        def on_name_changed():
            item_name_txt = name_edit.currentText()
            print(item_name_txt)
            con = sqlite3.connect(db_path)
            cur = con.cursor()
            # Подаставляем номер
            sql_item_numb = """\
            SELECT item_numb FROM nomenclature WHERE item_name = ?
            """
            cur.execute(sql_item_numb, (item_name_txt, ))
            cur_numb = cur.fetchone()
            numb_edit.setValue(cur_numb[0])

            # Подаставляем ед. изм
            sql_item_unit = """\
            SELECT item_unit FROM nomenclature WHERE item_name = ?
            """
            cur.execute(sql_item_unit, (item_name_txt, ))
            cur_unit = cur.fetchone()

            unit_edit_mas = unit_edit.count()
            for i in range(unit_edit_mas):
                if unit_edit.itemText(i) == cur_unit[0]:
                    unit_edit.setCurrentIndex(i)

            # Подставляем категорию
            sql_item_cat = """\
            SELECT item_cat FROM nomenclature WHERE item_name = ?
            """
            cur.execute(sql_item_cat, (item_name_txt, ))
            cur_cat = cur.fetchone()

            cat_edit_mas = cat_edit.count()

            for i in range(cat_edit_mas):
                if cat_edit.itemText(i) == cur_cat[0]:
                    cat_edit.setCurrentIndex(i)

            cur.close()
            con.close()

        def on_fio_changed():

            fio_txt = fio_edit.currentText()
            # print(fio_txt)
            con = sqlite3.connect(db_path)
            cur = con.cursor()
            # Подставляем должность
            sql_item_pos = """\
            SELECT position FROM employee WHERE fio = ?
            """
            cur.execute(sql_item_pos, (fio_txt, ))
            cur_pos = cur.fetchone()
            # print(cur_pos[0])

            receiver_edit_mas = receiver_edit.count()
            for i in range(receiver_edit_mas):
                if receiver_edit.itemText(i) == cur_pos[0]:
                    receiver_edit.setCurrentIndex(i)
            cur.close()
            con.close()

        def on_wo_form_btnCancel():
            wo_order_window.wo_order_form_window.close()

        def on_wo_form_btnSave():

            con = sqlite3.connect(db_path)
            cur = con.cursor()
            sql_wo_insert = "INSERT INTO wo_orders (numb, name, cat, unit, quant, fio, receiver) VALUES (?, ?, ?, ?, ?, ?, ?)"
            numb_val = numb_edit.value()
            name_val = name_edit.currentText()
            cat_val = cat_edit.currentText()
            unit_val = unit_edit.currentText()
            quant_val = quant_edit.value()
            fio_val = fio_edit.currentText()
            receiver_val = receiver_edit.currentText()
            sql_wo_values = (numb_val, name_val, cat_val, unit_val, quant_val,
                             fio_val, receiver_val)
            cur.execute(sql_wo_insert, sql_wo_values)
            con.commit()

            wo_order_window.wo_order_form_window.close()

            wo_orders_model = add_functions_class.all_wo_orders_print(
                parent, db_path)
            wo_orders_table.setModel(wo_orders_model)
            # Изменяем дополнительную таблицу
            sql_item_pos = """\
            SELECT item_name FROM items_positions WHERE item_name = ?
            """
            cur.execute(sql_item_pos, (item_name_txt, ))
            cur_item_pos = cur.fetchone()

            if cur_item_pos is not None:
                sql_item_quant = """\
                SELECT item_amount FROM items_positions WHERE item_name = ?
                """
                cur.execute(sql_item_quant, (item_name_txt, ))
                cur_item_quant = cur.fetchone()
                item_amount = cur_item_quant[0] - quant_val
                print(item_amount)

                sql_amount_upd = "UPDATE items_positions SET item_amount = ? WHERE item_name = ?"
                cur.execute(sql_amount_upd, (item_amount, item_name_txt))
                #cur_item_pos = cur.fetchone()
                con.commit()
            else:
                msg_lbl = QLabel(
                    '<span style="color:#ff0000;">Данный товар еще не оприходован</span>'
                )
                parent.sm_list_widget.clear()
                parent.item = QListWidgetItem()
                parent.sm_list_widget.addItem(parent.item)
                parent.sm_list_widget.setItemWidget(parent.item, msg_lbl)

        con = sqlite3.connect(db_path)
        cur = con.cursor()

        # Названия полей
        numb_label = QLabel('Номенклатурный номер:')
        name_label = QLabel('Наименование:')
        cat_label = QLabel('Категория:')
        unit_label = QLabel('Ед.измерения:')
        quant_label = QLabel('Количество:')
        fio_label = QLabel('ФИО:')
        receiver_label = QLabel('Получатель:')

        # Поля

        # -Наименование
        con = sqlite3.connect(db_path)
        cur = con.cursor()
        sql_name = """\
        SELECT item_name FROM nomenclature ORDER BY rowid
        """
        cur.execute(sql_name)
        name_arr = cur.fetchall()
        name_list = [el[0] for el in name_arr]

        name_edit = QComboBox()
        name_edit.setFixedSize(300, 25)
        name_edit.addItems(name_list)
        item_name_txt = name_edit.currentText()
        name_edit.activated.connect(on_name_changed)

        # -Номенклатурный номер
        numb_edit = QSpinBox()
        numb_edit.setFixedSize(100, 25)
        numb_edit.setRange(0, 10000000)
        numb_edit.setEnabled(False)
        sql_numb_first = """\
        SELECT item_numb FROM nomenclature where item_name = ?
        """
        cur.execute(sql_numb_first, (item_name_txt, ))
        first_numb = cur.fetchone()
        numb_edit.setValue(first_numb[0])

        # -Категория
        sql_cat = """\
        SELECT item_cat FROM nomenclature where item_name = ?
        """
        cur.execute(sql_cat, (item_name_txt, ))
        first_cat = cur.fetchone()

        sql_cat_all = """\
        SELECT category FROM categories
        """
        cur.execute(sql_cat_all)
        cat_arr = cur.fetchall()

        cat_list = [el[0] for el in cat_arr]
        cat_edit = QComboBox()
        cat_edit.setEnabled(False)
        cat_edit.setFixedSize(200, 25)
        cat_edit.addItems(cat_list)

        cat_edit_mas = cat_edit.count()
        for i in range(cat_edit_mas):
            if cat_edit.itemText(i) == first_cat[0]:
                cat_edit.setCurrentIndex(i)

        ##-Ед. измерения
        sql_units = """\
        SELECT item_unit FROM nomenclature where item_name = ?
        """
        cur.execute(sql_units, (item_name_txt, ))
        first_unit = cur.fetchone()

        sql_units_all = """\
        SELECT unit FROM units
        """
        cur.execute(sql_units_all)
        unit_arr = cur.fetchall()

        unit_list = [el[0] for el in unit_arr]

        unit_edit = QComboBox()
        unit_edit.setEnabled(False)
        unit_edit.addItems(unit_list)
        unit_edit.setFixedSize(100, 25)

        unit_edit_mas = unit_edit.count()
        for i in range(unit_edit_mas):
            if unit_edit.itemText(i) == first_unit[0]:
                unit_edit.setCurrentIndex(i)

        # -Количество
        quant_edit = QSpinBox()
        quant_edit.setFixedSize(100, 25)
        quant_edit.setRange(0, 1000000)

        # -ФИО
        sql_fio_all = """\
        SELECT fio FROM employee
        """
        cur.execute(sql_fio_all)
        fio_arr = cur.fetchall()

        fio_list = [el[0] for el in fio_arr]

        fio_edit = QComboBox()
        fio_edit.addItems(fio_list)
        fio_edit.setFixedSize(100, 25)

        fio_edit.activated.connect(on_fio_changed)
        fio_txt = fio_edit.currentText()

        # -Должность
        sql_receiver_all = """\
        SELECT position FROM positions
        """
        cur.execute(sql_receiver_all)
        receiver_arr = cur.fetchall()

        receiver_list = [el[0] for el in receiver_arr]

        receiver_edit = QComboBox()
        receiver_edit.setEnabled(False)
        receiver_edit.addItems(receiver_list)
        receiver_edit.setFixedSize(100, 25)

        cur.close()
        con.close()

        # Размещаем все компоненты
        wo_order_form_grid = QGridLayout()

        wo_order_form_grid = QGridLayout()
        wo_order_form_grid.addWidget(numb_label,
                                     0,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(numb_edit,
                                     0,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_grid.addWidget(name_label,
                                     1,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(name_edit,
                                     1,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_grid.addWidget(cat_label,
                                     2,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(cat_edit,
                                     2,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_grid.addWidget(unit_label,
                                     3,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(unit_edit,
                                     3,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_grid.addWidget(quant_label,
                                     4,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(quant_edit,
                                     4,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_grid.addWidget(fio_label,
                                     5,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(fio_edit,
                                     5,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_grid.addWidget(receiver_label,
                                     6,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addWidget(receiver_edit,
                                     6,
                                     1,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_form_frame = QFrame()
        wo_order_form_frame.setStyleSheet(
            open("./styles/properties_form_style.qss", "r").read())
        wo_order_form_frame.setLayout(wo_order_form_grid)

        #-----------------------------Кнопки формы--------------------------#

        wo_order_form_btnSave = QPushButton('Сохранить')
        wo_order_form_btnSave.setFixedSize(80, 25)
        wo_order_form_btnSave.clicked.connect(on_wo_form_btnSave)

        wo_order_form_btnCancel = QPushButton('Отмена')
        wo_order_form_btnCancel.setFixedSize(80, 25)
        wo_order_form_btnCancel.clicked.connect(on_wo_form_btnCancel)

        buttons_hbox = QHBoxLayout()
        buttons_hbox.addWidget(wo_order_form_btnSave)
        buttons_hbox.addWidget(wo_order_form_btnCancel)

        # --------------------Размещение на форме всех компонентов---------#

        wo_order_form_grid = QGridLayout()
        wo_order_form_grid.addWidget(wo_order_form_frame,
                                     0,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
        wo_order_form_grid.addLayout(buttons_hbox,
                                     1,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)

        wo_order_window.wo_order_form_window = QWidget()
        wo_order_window.wo_order_form_window.setWindowModality(
            QtCore.Qt.ApplicationModal)
        wo_order_window.wo_order_form_window.setWindowTitle("Приходный ордер")

        wo_order_window.wo_order_form_window.setLayout(wo_order_form_grid)
        wo_order_window.wo_order_form_window.show()
예제 #36
0
class SchemeSelector(QWidget):

    currentChanged = pyqtSignal()
    changed = pyqtSignal()

    def __init__(self, parent=None):
        super(SchemeSelector, self).__init__(parent)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.label = QLabel()
        self.scheme = QComboBox()
        self.menuButton = QPushButton(flat=True)
        menu = QMenu(self.menuButton)
        self.menuButton.setMenu(menu)
        layout.addWidget(self.label)
        layout.addWidget(self.scheme)
        layout.addWidget(self.menuButton)
        layout.addStretch(1)
        # action generator
        def act(slot, icon=None):
            a = QAction(self, triggered=slot)
            self.addAction(a)
            icon and a.setIcon(icons.get(icon))
            return a

        # add action
        a = self.addAction_ = act(self.slotAdd, 'list-add')
        menu.addAction(a)

        # remove action
        a = self.removeAction = act(self.slotRemove, 'list-remove')
        menu.addAction(a)


        # rename action
        a = self.renameAction = act(self.slotRename, 'document-edit')
        menu.addAction(a)

        menu.addSeparator()

        # import action
        a = self.importAction = act(self.slotImport, 'document-open')
        menu.addAction(a)

        # export action
        a = self.exportAction = act(self.slotExport, 'document-save-as')
        menu.addAction(a)


        self.scheme.currentIndexChanged.connect(self.slotSchemeChanged)
        app.translateUI(self)

    def translateUI(self):
        self.label.setText(_("Scheme:"))
        self.menuButton.setText(_("&Menu"))
        self.addAction_.setText(_("&Add..."))
        self.removeAction.setText(_("&Remove"))
        self.renameAction.setText(_("Re&name..."))
        self.importAction.setText(_("&Import..."))
        self.exportAction.setText(_("&Export..."))

    def slotSchemeChanged(self, index):
        """Called when the Scheme combobox is changed by the user."""
        self.disableDefault(self.scheme.itemData(index) == 'default')
        self.currentChanged.emit()
        self.changed.emit()

    def disableDefault(self, val):
        self.removeAction.setDisabled(val)
        self.renameAction.setDisabled(val)

    def schemes(self):
        """Returns the list with internal names of currently available schemes."""
        return [self.scheme.itemData(i) for i in range(self.scheme.count())]

    def currentScheme(self):
        """Returns the internal name of the currently selected scheme"""
        return self.scheme.itemData(self.scheme.currentIndex())

    def insertSchemeItem(self, name, scheme):
        for i in range(1, self.scheme.count()):
            n = self.scheme.itemText(i)
            if n.lower() > name.lower():
                self.scheme.insertItem(i, name, scheme)
                break
        else:
            self.scheme.addItem(name, scheme)

    def addScheme(self, name):
        num, key = 1, 'user1'
        while key in self.schemes() or key in self._schemesToRemove:
            num += 1
            key = 'user{0}'.format(num)
        self.insertSchemeItem(name, key)
        self.scheme.setCurrentIndex(self.scheme.findData(key))
        return key

    def slotAdd(self):
        name, ok = QInputDialog.getText(self,
            app.caption(_("Add Scheme")),
            _("Please enter a name for the new scheme:"))
        if ok:
            self.addScheme(name)


    def slotRemove(self):
        index = self.scheme.currentIndex()
        scheme = self.scheme.itemData(index)
        if scheme == 'default':
            return # default can not be removed

        self._schemesToRemove.add(scheme)
        self.scheme.removeItem(index)

    def slotRename(self):
        index = self.scheme.currentIndex()
        name = self.scheme.itemText(index)
        scheme = self.scheme.itemData(index)
        newName, ok = QInputDialog.getText(self, _("Rename"), _("New name:"), text=name)
        if ok:
            self.scheme.blockSignals(True)
            self.scheme.removeItem(index)
            self.insertSchemeItem(newName, scheme)
            self.scheme.setCurrentIndex(self.scheme.findData(scheme))
            self.scheme.blockSignals(False)
            self.changed.emit()

    def slotImport(self):
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
        caption = app.caption(_("dialog title", "Import color theme"))
        filename = QFileDialog.getOpenFileName(self, caption, QDir.homePath(), filetypes)[0]
        if filename:
            self.parent().import_(filename)

    def slotExport(self):
        name = self.scheme.currentText()
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
        caption = app.caption(_("dialog title",
            "Export {name}").format(name=name))
        path = os.path.join(QDir.homePath(), name+'.xml')
        filename = QFileDialog.getSaveFileName(self, caption, path, filetypes)[0]
        if filename:
            if os.path.splitext(filename)[1] != '.xml':
                filename += '.xml'
            self.parent().export(name, filename)


    def loadSettings(self, currentKey, namesGroup):
        # don't mark schemes for removal anymore
        self._schemesToRemove = set()

        s = QSettings()
        cur = s.value(currentKey, "default", str)

        # load the names for the shortcut schemes
        s.beginGroup(namesGroup)
        block = self.scheme.blockSignals(True)
        self.scheme.clear()
        self.scheme.addItem(_("Default"), "default")
        lst = [(s.value(key, key, str), key) for key in s.childKeys()]
        for name, key in sorted(lst, key=lambda f: f[0].lower()):
            self.scheme.addItem(name, key)

        # find out index
        index = self.scheme.findData(cur)
        self.disableDefault(cur == 'default')
        self.scheme.setCurrentIndex(index)
        self.scheme.blockSignals(block)
        self.currentChanged.emit()

    def saveSettings(self, currentKey, namesGroup, removePrefix=None):
        # first save new scheme names
        s = QSettings()
        s.beginGroup(namesGroup)
        for i in range(self.scheme.count()):
            if self.scheme.itemData(i) != 'default':
                s.setValue(self.scheme.itemData(i), self.scheme.itemText(i))

        for scheme in self._schemesToRemove:
            s.remove(scheme)
        s.endGroup()
        if removePrefix:
            for scheme in self._schemesToRemove:
                s.remove("{0}/{1}".format(removePrefix, scheme))
        # then save current
        scheme = self.currentScheme()
        s.setValue(currentKey, scheme)
        # clean up
        self._schemesToRemove = set()
예제 #37
0
class Example(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.resize(800, 600)

        centralWidget = QWidget(self)
        grid = QGridLayout(centralWidget)
        grid.setSpacing(10)

        self.listOfDiscipline = QComboBox(centralWidget)
        grid.addWidget(self.listOfDiscipline, 0, 0, 1, 1)

        textIn = QLabel(centralWidget)
        textIn.setText('Входные компетенции')
        grid.addWidget(textIn, 1, 0, 1, 1)

        self.tableIn = QTableView(centralWidget)
        grid.addWidget(self.tableIn, 2, 0, 1, 1)

        textOut = QLabel(centralWidget)
        textOut.setText('Выходные компетенции')
        grid.addWidget(textOut, 3, 0, 1, 1)

        self.tableOut = QTableView(centralWidget)
        grid.addWidget(self.tableOut, 4, 0, 1, 1)

        self.setCentralWidget(centralWidget)

        openFile = QAction('Открыть базу данных', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Открыть базу данных комптенций')
        openFile.triggered.connect(self.MainFunc)

        exitWindow = QAction('Выход', self)
        exitWindow.setStatusTip('Завершение программы')
        exitWindow.triggered.connect(self.close)

        saveFile_one = QAction('Сохранить дисциплину', self)
        saveFile_one.setShortcut('Ctrl+S')
        saveFile_one.setStatusTip('Сохранить одну дисциплину в формате xlsx')
        saveFile_one.triggered.connect(self.save_one)

        saveFile_all = QAction('Сохранить все дисциплины', self)
        saveFile_all.setShortcut('Ctrl+A')
        saveFile_all.setStatusTip('Сохранить все дисциплины в формате xlsx')
        saveFile_all.triggered.connect(self.save_all)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&Файл')
        fileMenu.addAction(openFile)
        fileSaveMenu = fileMenu.addMenu('&Дисциплины')
        fileSaveMenu.addAction(saveFile_one)
        fileSaveMenu.addAction(saveFile_all)
        fileMenu.addAction(fileSaveMenu.menuAction())
        fileMenu.addSeparator()
        fileMenu.addAction(exitWindow)

        self.nameFileOpen = ''

        self.statusBar()
        self.setWindowTitle('Формирование компетенций')
        self.show()

    def MainFunc(self):
        """
        Основная функция
        :return:
        """
        self.nameFileOpen = self.showDialog()
        self.listOfDiscipline.activated[str].connect(self.comboPrint)

    def comboPrint(self, displ):
        self.formInComp(displ, self.nameFileOpen, 'table')

    def showDialog(self):
        """
        Открытие базы данных
        :return:
        """
        fname = QFileDialog.getOpenFileName(self, 'Открыть базу данных', '/', 'DataBase(*.sqlite)')[0]
        self.displ = self.listDB(fname)
        return fname

    def listDB(self, namebd):
        """
        Получение списка таблиц базы данных
        :param nameDB:
        :return:
        """
        cache = []
        db = sqlite3.connect(namebd)
        cur = db.cursor()

        k = cur.execute('SELECT * FROM sqlite_master WHERE type = "table"')
        for j in k:
            if j[1] != 'sqlite_stat1' and j[1] != 'ОК' and j[1] != 'ОПК':
                cache.append(j[1])

        cur.close()
        db.close()
        self.listOfDiscipline.addItems(cache)
        return cache

    def formInComp(self, displ, namebd, type):
        """
        Формирование входящих компетенций на основе выходящих
        :param list, namebd:
        :return:
        """
        self.cacheIn = []
        self.cacheOut = []
        self.cacheInDisp = []
        rowIn = 0
        rowOut = 0
        db = sqlite3.connect(namebd)
        cur = db.cursor()
        k = cur.execute('SELECT * FROM ' + displ)
        for line in k:
            inDisp = self.procInDisp(line[6])
            if str(line[0]).find('К') != -1:
                rowOut = rowOut + 1
                self.cacheOut.append(line)
            if inDisp != '':
                self.cacheInDisp.append(inDisp)

        for dis in self.cacheInDisp:
            if dis in self.displ:
                k = cur.execute('SELECT * FROM ' + dis)
                for line in k:
                    if (line[0] != '') and (line[0] != '\t'):
                        self.cacheIn.append(line)
                        rowIn = rowIn + 1

        self.cacheIn.sort()
        self.cacheOut.sort()
        if type == 'table':
            self.createTable('out', rowOut, self.cacheOut)
            self.createTable('in', rowIn, self.cacheIn)
        else:
            return self.cacheIn, self.cacheOut

        cur.close()
        db.close()

    def procInDisp(self, disp):
        """
        Обработка входящих дисциплин для применения в SQL запросах
        :param disp:
        :return:
        """
        m = disp
        m = m.strip()
        m = m.replace(' ', '_')
        m = m.replace('  ', '')
        m = m.replace('   ', '')
        m = m.replace('-', '_')
        m = m.replace('.', '')
        m = m.replace('«', '')
        m = m.replace('»', '')
        m = m.replace(',', '')
        m = m.capitalize()
        return m

    def createTable(self, type_table, rows, list_of_komp):
        """
        Создание и заполнение таблицы
        :param type_table:
        :param row:
        :param list_komp:
        :param list_desc:
        :return:
        """
        if type_table == 'out':
            model = QStandardItemModel(rows, 2)
            list_horizontal = ['Код компетенции', 'Описание компетенции']
            model.setHorizontalHeaderLabels(list_horizontal)
            self.tableOut.setModel(model)
            self.tableOut.setColumnWidth(0, 110)
            self.tableOut.setColumnWidth(1, self.tableOut.width() - 130)
            for row in range(rows):
                for column in range(2):
                    index = model.index(row, column, QModelIndex())
                    model.setData(index, str(list_of_komp[row][column]).strip())
        else:
            model = QStandardItemModel(rows, 2)
            list_horizontal = ['Код компетенции', 'Описание компетенции']
            model.setHorizontalHeaderLabels(list_horizontal)
            self.tableIn.setModel(model)
            self.tableIn.setColumnWidth(0, 110)
            self.tableIn.setColumnWidth(1, self.tableIn.width() - 130)
            for row in range(rows):
                for column in range(2):
                    index = model.index(row, column, QModelIndex())
                    model.setData(index, str(list_of_komp[row][column]).strip())

    def save_one(self):
        wb = openpyxl.Workbook()

        ws = wb.active
        ws.title = str(self.listOfDiscipline.currentText())[:20]
        ws.append(['Входящие компетенции'])
        for line in self.cacheIn:
            ws.append([line[0].strip(), line[1].strip()])
        ws.append(['Выходящие компетенции'])
        for line in self.cacheOut:
            ws.append([line[0].strip(), line[1].strip()])

        wb.save(self.listOfDiscipline.currentText() + '.xlsx')

    def save_all(self):
        count_displ = self.listOfDiscipline.count()
        wb = openpyxl.Workbook()

        ws = wb.active
        ws.title = 'Дисциплины'
        ws['A1'] = 'Сохранениые дисциплины'
        for count in range(count_displ):
            ws.append([str(self.listOfDiscipline.itemText(count))])
        for count in range(count_displ):
            inDis, outDis = self.formInComp(self.listOfDiscipline.itemText(count), self.nameFileOpen, ' ')
            ws = wb.create_sheet(self.listOfDiscipline.itemText(count)[:20])
            ws.append(['Входящие компетенции'])
            for line in inDis:
                ws.append([line[0].strip(), line[1].strip()])
            ws.append(['Выходящие компетенции'])
            for line in outDis:
                ws.append([line[0].strip(), line[1].strip()])
        wb.save('Все дисциплины.xlsx')
예제 #38
0
class PadCalc(QWidget):
    def __init__(self):
        super().__init__()
        load_data()

        card_tags = ['leader','sub1','sub2','sub3','sub4','friend']
        self.cards = { t: CardIcon() for t in card_tags }

        self.vlayout = QVBoxLayout(self)
        self.vlayout.setSpacing(0)
        self.setLayout(self.vlayout)

        self.userbox = QHBoxLayout()
        userfield = QLineEdit()
        userbutton = QPushButton('Load')
        userbutton.clicked.connect(lambda: self.set_user(userfield.text()))
        self.userbox.addWidget(userfield)
        self.userbox.addWidget(userbutton)
        userfield.returnPressed.connect(userbutton.click)
        self.vlayout.addLayout(self.userbox)

        maxcheckbox = QCheckBox('Use maxed stats?')
        maxcheckbox.stateChanged[int].connect(self.setMaxed)
        self.vlayout.addWidget(maxcheckbox)


        self.teamchooser = QComboBox(self)
        self.teamchooser.currentIndexChanged[int].connect(self.set_team)
        self.vlayout.addWidget(self.teamchooser)

        teambox = QHBoxLayout()
        teambox.addStretch(1)
        for card in card_tags:
            teambox.addWidget(self.cards[card])

        teambox.setSpacing(0)
        teambox.addStretch(1)
        teambox.setAlignment(Qt.AlignCenter)
        self.vlayout.addLayout(teambox)

        self.board = Board()
        self.vlayout.addWidget(self.board)
        self.vlayout.itemAt(self.vlayout.indexOf(self.board)).setAlignment(Qt.AlignCenter)

        self.orbchooser = QHBoxLayout()
        b = OrbButton(value = 0)
        b.clicked.connect(functools.partial(self.setPaintOrb,Orb.Null))
        self.orbchooser.addWidget(b)
        for i in ORBS:
            b = OrbButton(value=i)
            #print('Setting click value of button %s to %s' % (id(b),i))
            b.clicked.connect(functools.partial(self.setPaintOrb,i))
            self.orbchooser.addWidget(b)

        self.vlayout.addLayout(self.orbchooser)

        self.damagereadout = QLabel()
        font = QFont()
        font.setPointSize(30)
        self.damagereadout.setAlignment(Qt.AlignCenter)
        self.damagereadout.setFont(font)
        self.vlayout.addWidget(self.damagereadout)
        self.board.valueChanged.connect(self.update_damage)

        labels = ['atk','combos','leaders','enhance','prongs','rows']
        lfont = QFont()
        lfont.setPointSize(9)
        vfont = QFont()
        vfont.setPointSize(12)
        self.details = {key: QVBoxLayout() for key in labels}
        for i in labels:
            label = QLabel(i)
            label.setFont(lfont)
            label.setAlignment(Qt.AlignCenter)
            label.setMargin(0)
            label.setContentsMargins(0,0,0,0)
            label.setIndent(0)
            self.details[i].label = label
            self.details[i].addWidget(self.details[i].label)
            value = QLabel('1')
            value.setFont(vfont)
            value.setAlignment(Qt.AlignCenter)
            value.setMargin(0)
            value.setIndent(0)
            value.setContentsMargins(0,0,0,0)
            self.details[i].value = value
            self.details[i].addWidget(self.details[i].value)
            self.details[i].setContentsMargins(1,1,1,1)

        self.detailreadout = QHBoxLayout()
        for i in labels:
            self.detailreadout.addLayout(self.details[i])
            timeslabel = QLabel('\u00d7')
            timeslabel.setMargin(0)
            timeslabel.setIndent(0)
            timeslabel.setAlignment(Qt.AlignCenter)
            timeslabel.setContentsMargins(0,0,0,0)
            self.detailreadout.addWidget(timeslabel)

        self.detailreadout.takeAt(self.detailreadout.count()-1)
        self.vlayout.addLayout(self.detailreadout)

        self.vlayout.addStretch(1000)
        self.skillbox = QHBoxLayout()
        self.vlayout.addLayout(self.skillbox)
        #self.set_user('korora')

    def setMaxed(self,state):
        Card.use_max_stats = (state == Qt.Checked)
        self.drawui()
        self.update_damage()
        self.set_team(self.teamchooser.currentIndex())

    def setPaintOrb(self,orb):
        global paintOrb
        paintOrb = orb

    def set_user(self,username):
        newuser = User(username)

        if hasattr(self,'user'):
            olduser = self.user.username
        else:
            olduser = ''

        if hasattr(newuser,'teams') and len(newuser.teams) > 0:
            teamchooser = self.teamchooser
            self.user = newuser
            index = teamchooser.currentIndex()
            try:
                teamchooser.currentIndexChanged[int].disconnect()
            except:
                return

            teamchooser.clear()
            for team in self.user.teams:
                teamchooser.addItem('%s' % (team['name']))

            if newuser.username != olduser:
                self.set_team(0)
            else:
                teamchooser.setCurrentIndex(index)
                self.set_team(index)

            teamchooser.currentIndexChanged[int].connect(self.set_team)

    def update_damage(self):
        (match,enhanced,row) = self.board.match()
        nmatch = sum(len(v) for v in match.values())
        nrow = sum(v for v in row.values())
        (dmg, multipliers) = compute_damage((match,enhanced,row),self.team)
        self.damagereadout.setText('{:,}'.format(round(sum([sum(i) for i in dmg.values()]))))
        for i in multipliers:
            if i is not 'atk':
                self.details[i].value.setText('%.2f' % multipliers[i])
            else:
                self.details[i].value.setText('%d' % multipliers[i])

        for card in self.cards.values():
            # add a damage label
            dam = dmg[card.card]
            card.main_attack = dam[0]
            card.sub_attack = dam[1]
            card.repaint()

    def set_team(self,index):
        teamdata = self.user.teams[index]
        team = []
        for i in ['leader','sub1','sub2','sub3','sub4']:
            team += [Card().load_from_id(self.user,teamdata[i])]
        friend = {
                'monster': teamdata['friend_leader'],
                'plus_atk': teamdata['friend_atk'],
                'plus_hp': teamdata['friend_hp'],
                'plus_rcv': teamdata['friend_rcv'],
                'current_awakening': teamdata['friend_awakening'],
                'lv': teamdata['friend_level'],
                'current_skill': teamdata['friend_skill']
                }
        team += [Card().load_from_card(friend)]
        self.team = Team(team)
        #print('|'+self.teamchooser.itemText(index)+'|')
        #print(len(self.teamchooser.itemText(index)))
        self.teamchooser.setMinimumContentsLength(len(self.teamchooser.itemText(index))-3)
        for i in range(self.skillbox.count()):
            w = self.skillbox.takeAt(i)
            w.widget().deleteLater()
            
        #svc = SkillViewController(skill=self.team.lskills[0])
        #svc.skillsChanged.connect(self.update_damage)
        #self.skillbox.addWidget(svc)
        self.drawui()
        self.update_damage()

    def drawui(self):
        self.cards['leader'].card = (self.team.cards[0])
        self.cards['sub1'].card = (self.team.cards[1])
        self.cards['sub2'].card = (self.team.cards[2])
        self.cards['sub3'].card = (self.team.cards[3])
        self.cards['sub4'].card = (self.team.cards[4])
        self.cards['friend'].card = (self.team.cards[5])
        for card in self.cards.values():
            card.load_icon()
예제 #39
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        self.setWindowTitle("RainbowBB")
        self.setParent(parent)
        self.initUI()

    def initUI(self):
        self.setStyleSheet("QCheckBox { background: palette(window); border-radius: 4px; padding: 2px; margin-right: 2px; }")

        self.toolBar = QToolBar(self)
        self.toolBar.setStyleSheet(stylesheet % (create_gradient("pastel"),))
        self.toolBar.setMovable(False)
        self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu)
        self.addToolBar(self.toolBar)

        self.reverseBox = QCheckBox("&Reverse", self)
        self.reverseBox.clicked.connect(lambda: self.updateGradient())
        self.toolBar.addWidget(self.reverseBox)

        self.byWordBox = QCheckBox("By &word", self)
        self.toolBar.addWidget(self.byWordBox)

        self.bounceBox = QCheckBox("&Bounce", self)
        self.bounceBox.clicked.connect(lambda: self.updateGradient())
        self.toolBar.addWidget(self.bounceBox)
        
        self.sizeList = QComboBox(self)
        self.sizeList.addItem("None")
        for num in range(1, 8):
            self.sizeList.addItem(str(num))
        self.toolBar.addWidget(self.sizeList)
        
        self.cycleList = QComboBox(self)
        self.toolBar.addWidget(self.cycleList)
        self.cycleList.currentIndexChanged.connect(self.updateGradient)
        self.loadCycles()
        
        self.convertButton = QPushButton("&Convert", self)
        self.convertButton.clicked.connect(self.convert)
        self.toolBar.addWidget(self.convertButton)

        self.reloadButton = QPushButton("Reload", self)
        self.reloadButton.setShortcut("Alt+Shift+R")
        self.reloadButton.clicked.connect(self.loadCycles)
        self.toolBar.addWidget(self.reloadButton)

        self.inputDock = QDockWidget("Input", self)
        self.inputDock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.inputDock.setContextMenuPolicy(Qt.CustomContextMenu)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.inputDock)

        self.inputField = QTextEdit(self)
        self.inputField.setAcceptRichText(False)
        self.inputDock.setWidget(self.inputField)

        self.outputField = QTextEdit(self)
        self.outputField.setReadOnly(True)
        self.setCentralWidget(self.outputField)

    def updateGradient(self, index=None):
        if not index:
            index = self.cycleList.currentIndex()
        self.toolBar.setStyleSheet(stylesheet % (create_gradient(self.cycleList.itemText(index), self.reverseBox.isChecked(), self.bounceBox.isChecked()),))

    def loadCycles(self):
        rainbowbb.load_cycles()
        self.cycleList.clear()
        self.cycleList.addItem("pastel")
        for cycle in sorted(list(rainbowbb.cycles.keys())):
            if cycle != "pastel":
                self.cycleList.addItem(cycle)

    def show(self):
        self.setVisible(True)
        self.inputField.setFocus()

    def convert(self):
        self.outputField.setPlainText(rainbowbb.size(rainbowbb.colorize(self.inputField.toPlainText(), self.cycleList.currentText(), self.reverseBox.isChecked(), not self.byWordBox.isChecked(), self.bounceBox.isChecked()), self.sizeList.currentText() if self.sizeList.currentText() != "None" else None))
예제 #40
0
class CSVOptionsWindow(QWidget):
    def __init__(self, mainwindow):
        QWidget.__init__(self, mainwindow, Qt.Window)
        self._setupUi()
        self.doc = mainwindow.doc
        self.model = mainwindow.model.csv_options
        self.tableModel = CSVOptionsTableModel(self.model, self.tableView)
        self.model.view = self
        self.encodingComboBox.addItems(SUPPORTED_ENCODINGS)

        self.cancelButton.clicked.connect(self.hide)
        self.continueButton.clicked.connect(self.model.continue_import)
        self.targetComboBox.currentIndexChanged.connect(self.targetIndexChanged)
        self.layoutComboBox.currentIndexChanged.connect(self.layoutIndexChanged)
        self.rescanButton.clicked.connect(self.rescanClicked)

    def _setupUi(self):
        self.setWindowTitle(tr("CSV Options"))
        self.resize(526, 369)
        self.verticalLayout = QVBoxLayout(self)
        msg = tr(
            "Specify which CSV columns correspond to which transaction fields. You must also "
            "uncheck the \"Import\" column for lines that don\'t represent a transaction "
            "(header, footer, comments)."
        )
        self.label = QLabel(msg)
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.gridLayout = QGridLayout()
        self.label_2 = QLabel(tr("Layout:"))
        self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
        self.layoutComboBox = QComboBox(self)
        self.layoutComboBox.setMinimumSize(QtCore.QSize(160, 0))
        self.gridLayout.addWidget(self.layoutComboBox, 0, 1, 1, 1)
        self.label_4 = QLabel(tr("Delimiter:"))
        self.gridLayout.addWidget(self.label_4, 0, 3, 1, 1)
        self.fieldSeparatorEdit = QLineEdit(self)
        self.fieldSeparatorEdit.setMaximumSize(QtCore.QSize(30, 16777215))
        self.gridLayout.addWidget(self.fieldSeparatorEdit, 0, 4, 1, 1)
        self.targetComboBox = QComboBox(self)
        self.gridLayout.addWidget(self.targetComboBox, 1, 1, 1, 1)
        self.label_3 = QLabel(tr("Target:"))
        self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)
        self.encodingComboBox = QComboBox(self)
        self.gridLayout.addWidget(self.encodingComboBox, 1, 4, 1, 1)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 2, 2, 1, 1)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setSpacing(0)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.rescanButton = QPushButton(tr("Rescan"))
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.rescanButton.sizePolicy().hasHeightForWidth())
        self.rescanButton.setSizePolicy(sizePolicy)
        self.horizontalLayout_2.addWidget(self.rescanButton)
        self.gridLayout.addLayout(self.horizontalLayout_2, 2, 3, 1, 2)
        self.label_5 = QLabel(tr("Encoding:"))
        self.gridLayout.addWidget(self.label_5, 1, 3, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        self.tableView = QTableView(self)
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setShowGrid(False)
        self.tableView.horizontalHeader().setHighlightSections(False)
        self.tableView.verticalHeader().setVisible(False)
        self.tableView.verticalHeader().setDefaultSectionSize(18)
        self.verticalLayout.addWidget(self.tableView)
        self.horizontalLayout = QHBoxLayout()
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.cancelButton = QPushButton(tr("Cancel"))
        self.cancelButton.setShortcut("Esc")
        self.horizontalLayout.addWidget(self.cancelButton)
        self.continueButton = QPushButton(tr("Continue Import"))
        self.continueButton.setDefault(True)
        self.horizontalLayout.addWidget(self.continueButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

    # --- Private
    def _newLayout(self):
        title = tr("New Layout")
        msg = tr("Choose a name for your new layout:")
        name, ok = QInputDialog.getText(self, title, msg)
        if ok and name:
            self.model.new_layout(name)

    def _renameLayout(self):
        title = tr("Rename Layout")
        msg = tr("Choose a name for your layout:")
        name, ok = QInputDialog.getText(self, title, msg)
        if ok and name:
            self.model.rename_selected_layout(name)

    # --- Event Handling
    def layoutIndexChanged(self, index):
        # This one is a little complicated. We want to only be able to select the layouts. If
        # anything else is clicked, we revert back to the old index. If the item has user data,
        # it means that an action has to be performed.
        if index < 0:
            return
        elif index < len(self.model.layout_names):
            layout_name = None if index == 0 else str(self.layoutComboBox.itemText(index))
            self.model.select_layout(layout_name)
        else:
            self.layoutComboBox.setCurrentIndex(self.layoutComboBox.findText(self.model.layout.name))
            data = str(self.layoutComboBox.itemData(index))
            if data == NEW_LAYOUT:
                self._newLayout()
            elif data == RENAME_LAYOUT:
                self._renameLayout()
            elif data == DELETE_LAYOUT:
                self.model.delete_selected_layout()

    def rescanClicked(self):
        self.model.encoding_index = self.encodingComboBox.currentIndex()
        self.model.field_separator = str(self.fieldSeparatorEdit.text())
        self.model.rescan()

    def targetIndexChanged(self, index):
        self.model.selected_target_index = index

    # --- model --> view
    # hide() is called from the model, but is already covered by QWidget
    def refresh_columns(self):
        self.tableModel.beginResetModel()
        self.tableModel.endResetModel()

    def refresh_columns_name(self):
        self.tableModel.refreshColumnsName()

    def refresh_layout_menu(self):
        self.layoutComboBox.currentIndexChanged.disconnect(self.layoutIndexChanged)
        self.layoutComboBox.clear()
        self.layoutComboBox.addItems(self.model.layout_names)
        self.layoutComboBox.insertSeparator(self.layoutComboBox.count())
        self.layoutComboBox.addItem(tr("New Layout..."), NEW_LAYOUT)
        self.layoutComboBox.addItem(tr("Rename Selected Layout..."), RENAME_LAYOUT)
        self.layoutComboBox.addItem(tr("Delete Selected Layout"), DELETE_LAYOUT)
        self.layoutComboBox.setCurrentIndex(self.layoutComboBox.findText(self.model.layout.name))
        self.layoutComboBox.currentIndexChanged.connect(self.layoutIndexChanged)

    def refresh_lines(self):
        self.tableModel.beginResetModel()
        self.tableModel.endResetModel()
        self.fieldSeparatorEdit.setText(self.model.field_separator)

    def refresh_targets(self):
        self.targetComboBox.currentIndexChanged.disconnect(self.targetIndexChanged)
        self.targetComboBox.clear()
        self.targetComboBox.addItems(self.model.target_account_names)
        self.targetComboBox.currentIndexChanged.connect(self.targetIndexChanged)

    def show(self):
        # For non-modal dialogs, show() is not enough to bring the window at the forefront, we have
        # to call raise() as well
        QWidget.show(self)
        self.raise_()

    def show_message(self, msg):
        title = "Warning"
        QMessageBox.warning(self, title, msg)
예제 #41
0
class LanguageSelectWidget(QWidget):
    language_changed = pyqtSignal(str)

    def __init__(self, lyrics_path, current_language, *args, **kwargs):

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

        self.lyrics_path = QStandardPaths.locate(QStandardPaths.AppDataLocation, lyrics_path,
                                                 QStandardPaths.LocateDirectory)
        self.current_language = current_language

        layout = QVBoxLayout()
        layout.setSpacing(5)
        layout.setContentsMargins(0, 0, 0, 0)

        languages = []
        try:
            for filename in os.listdir(self.lyrics_path):
                if filename != "timing" and os.path.isdir(os.path.join(self.lyrics_path, filename)):
                    languages.append(filename)
        except FileNotFoundError:
            pass

        self.languages_combo_box = QComboBox()
        self.languages_combo_box.addItems(sorted(languages) + [self.tr("New Language...")])
        self.languages_combo_box.currentTextChanged.connect(self._language_changed)

        self._select_current_language()
        layout.addWidget(self.languages_combo_box)

        self.edit_button = QPushButton(text=self.tr("Edit Language..."), clicked=self._edit_current_language)
        layout.addWidget(self.edit_button)

        self.setLayout(layout)

        self.import_lyrics_wizard = ImportLyricsWizard(lyrics_path,
                                                       accepted=self._wizard_done,
                                                       rejected=self._wizard_aborted,
                                                       )

        self._editing_language = False

        if not languages:
            self.import_lyrics_wizard.open()

    def _language_changed(self, name):

        if name == self.tr("New Language..."):
            self.import_lyrics_wizard.open()
        else:
            self.current_language = name
            self.language_changed.emit(name)

    def _wizard_done(self):

        languages = [self.languages_combo_box.itemText(i) for i in range(self.languages_combo_box.count() - 1)]

        if self._editing_language:
            self._editing_language = False
            old_index = languages.index(self.current_language)
            self.languages_combo_box.removeItem(old_index)
            languages.pop(old_index)

        new_language = self.import_lyrics_wizard.language
        print("new", new_language)

        languages.append(new_language)
        languages.sort()

        index = languages.index(new_language)
        self.languages_combo_box.insertItem(index, new_language)
        self.languages_combo_box.setCurrentIndex(index)

    def _wizard_aborted(self):
        self._select_current_language()

    def _select_current_language(self):
        languages = [self.languages_combo_box.itemText(i) for i in range(self.languages_combo_box.count() - 1)]
        if languages:
            self.languages_combo_box.setCurrentIndex(languages.index(self.current_language))

    def _edit_current_language(self):
        self._editing_language = True
        self.import_lyrics_wizard.open()
        self.import_lyrics_wizard.edit_language(self.current_language)
예제 #42
0
class snapshot_slider(QWidget):

	changed = pyqtSignal()

	def cal_min_max(self):

		self.z_max=-1e40
		self.z_min=1e40

		for i in range(0,len(self.dirs)):
			fname=os.path.join(self.dirs[i],self.files_combo.currentText())
			x=[]
			y=[]
			z=[]

			my_data=dat_file()
			if dat_file_read(my_data,fname) == True:
				#print(z)
				temp_max,temp_min=dat_file_max_min(my_data)

				if temp_max>self.z_max:
					self.z_max=temp_max

				if temp_min<self.z_min:
					self.z_min=temp_min
		
	def update(self):
		self.dirs=[]
		if os.path.isdir(self.path)==True:
			for name in os.listdir(self.path):
				if name!="." and name!= "..":
					full_path=os.path.join(self.path, name)
					if os.path.isdir(full_path):
						self.dirs.append(full_path)
		self.slider_max=len(self.dirs)-1
		self.slider0.setMaximum(self.slider_max)
		self.update_file_combo()

	def slider0_change(self):
		value = self.slider0.value()
		self.label0.setText(str(value))
		self.changed.emit()

	def get_file_name(self):
		file_path=os.path.join(self.path,str(self.slider0.value()),self.files_combo.currentText())
		if os.path.isfile(file_path)==False:
			file_path=None
		return file_path

	def set_path(self,path):
		self.path=path
		self.update()
		self.cal_min_max()

		
	def __init__(self):
		QWidget.__init__(self)
		self.path=""
		
		self.setWindowTitle(_("Snapshot slider")) 
		
		self.main_vbox = QVBoxLayout()

		self.slider_hbox0= QHBoxLayout()
		self.slider_max=30
		
		self.slider0 = QSlider(Qt.Horizontal)
		self.slider0.setMinimum(10)
		self.slider0.setMaximum(self.slider_max)

		self.slider0.setTickPosition(QSlider.TicksBelow)
		self.slider0.setTickInterval(5)
		self.slider0.valueChanged.connect(self.slider0_change)
		self.slider0.setMinimumSize(300, 80)

		self.slider_hbox0.addWidget(self.slider0)

		self.label0 = QLabel()
		self.label0.setText("")

		self.slider0.setValue(20)

		self.slider_hbox0.addWidget(self.label0)

		self.widget0=QWidget()
		self.widget0.setLayout(self.slider_hbox0)

		self.main_vbox.addWidget(self.widget0)


################
		self.slider_hbox1= QHBoxLayout()
		self.label1 = QLabel()
		self.label1.setText("File")
		self.slider_hbox1.addWidget(self.label1)

		self.files_combo=QComboBox()
		self.slider_hbox1.addWidget(self.files_combo)

		self.files_combo.currentIndexChanged.connect(self.files_combo_changed)

		self.widget1=QWidget()
		self.widget1.setLayout(self.slider_hbox1)

		self.main_vbox.addWidget(self.widget1)

###############

		self.setLayout(self.main_vbox)

	def update_file_combo(self):
		self.files_combo.blockSignals(True)
		self.files_combo.clear()
		path=os.path.join(self.path,str(self.slider0.value()))
		if os.path.isdir(path)==True:
			for name in os.listdir(path):
				full_path=os.path.join(path, name)
				if os.path.isfile(full_path):
					if name!="snapshot_info.dat":
						self.files_combo.addItem(name)

		all_items  = [self.files_combo.itemText(i) for i in range(self.files_combo.count())]

		for i in range(0,len(all_items)):
			if all_items[i] == "Jn.dat":
				self.files_combo.setCurrentIndex(i)
		self.files_combo.blockSignals(False)

		
	def files_combo_changed(self):
		self.cal_min_max()
		self.changed.emit()
예제 #43
0
파일: view.py 프로젝트: alberand/PySM
class View(QWidget):

    # Send data to port
    send_data           = pyqtSignal(object)
    # Chage baudrate
    baudrate_changed    = pyqtSignal(object)
    # Change end of line
    eol_changed         = pyqtSignal(object)
    # Change port
    port_changed        = pyqtSignal(object)
    # Pause model
    pause_m             = pyqtSignal(object)
    # Continue model
    start_m             = pyqtSignal(object)

    def __init__(self):
        QWidget.__init__(self)

        self.queue      = None
        self.end_cmd    = None
        self.autoscroll = False
        self.msg_sent   = False

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_gui)
        self.timer.start(100)
                
        self.__initUI()

    def __initUI(self):
        vbox = QVBoxLayout(self)

        # Command box
        cmd_hbox = QHBoxLayout()

        self.cmd_edit = QLineEdit()
        cmd_hbox.addWidget(self.cmd_edit)

        cmd_btn = QPushButton('Send')
        cmd_btn.clicked.connect(self.emit_send_data)
        cmd_hbox.addWidget(cmd_btn)

        cmd_btn = QPushButton('Start')
        cmd_btn.clicked.connect(self.start_m.emit)
        cmd_hbox.addWidget(cmd_btn)

        cmd_btn = QPushButton('Stop')
        cmd_btn.clicked.connect(self.pause_m.emit)
        cmd_hbox.addWidget(cmd_btn)

        vbox.addLayout(cmd_hbox)

        # Text edit area
        self.editer = QPlainTextEdit()
        self.editer.scrollContentsBy = self.ModScrollContentsBy
        vbox.addWidget(self.editer)

        # Settings area
        stng_hbox = QHBoxLayout()

        # - Autoscroll
        chk_btn = QCheckBox('Autoscroll')
        chk_btn.stateChanged.connect(self.set_autoscroll)
        stng_hbox.addWidget(chk_btn)

        cmd_btn = QPushButton('Clear')
        cmd_btn.clicked.connect(self.editer.clear)
        stng_hbox.addWidget(cmd_btn)

        stng_hbox.addStretch(1)

        # - Ending of line
        self.eol_menu = QComboBox()
        self.eol_menu.addItem('No line ending')
        self.eol_menu.addItem('Newline')
        self.eol_menu.addItem('Carriage return')
        self.eol_menu.addItem('Both NL + CR')
        self.eol_menu.setCurrentIndex(0)
        self.eol_menu.currentIndexChanged.connect(self.emit_eol_changed)
        stng_hbox.addWidget(self.eol_menu)

        # - Baudrate select
        self.br_menu = QComboBox()
        self.br_menu.addItem('300 baud')
        self.br_menu.addItem('1200 baud')
        self.br_menu.addItem('2400 baud')
        self.br_menu.addItem('4800 baud')
        self.br_menu.addItem('9600 baud')
        self.br_menu.addItem('19200 baud')
        self.br_menu.addItem('38400 baud')
        self.br_menu.addItem('57600 baud')
        self.br_menu.addItem('115200 baud')
        self.br_menu.addItem('230400 baud')
        self.br_menu.addItem('460800 baud')
        self.br_menu.currentIndexChanged.connect(self.emit_br_changed)
        # Set default baudrate 9600
        self.br_menu.setCurrentIndex(4)

        stng_hbox.addWidget(self.br_menu)

        vbox.addLayout(stng_hbox)

        port_hbox = QHBoxLayout()
        port_lbl = QLabel('Port: ')
        port_hbox.addWidget(port_lbl)

        self.port_edit = QLineEdit()

        self.port_edit.editingFinished.connect(self.changePort)
        port_hbox.addWidget(self.port_edit)

        vbox.addLayout(port_hbox)

        self.setLayout(vbox)

    def show_error(self, value):
        msg = QMessageBox(
                QMessageBox.NoIcon, 'Error occured.', value, QMessageBox.Ok)
        msg.exec()

#==============================================================================
# Get, set
#==============================================================================

    def set_queue(self, queue):
        self.queue = queue

    def set_end_cmd(self, end_cmd):
        self.end_cmd = end_cmd

    def set_autoscroll(self, value):
        print('Set autoscroll: {}.'.format(value))
        self.autoscroll = value

    def set_port(self, value):
        self.port_edit.insert(value)

    def get_cmd(self):
        return self.cmd_edit.text()

    def set_eol(self, value):
        self.eol_menu.setCurrentIndex(value)

    def closeEvent(self, event):
        self.end_cmd()
        QWidget.closeEvent(self, event)
        print('exit')

    def update_gui(self):
        self.process_incoming()
        self.update()

    def process_incoming(self):
        while self.queue.qsize():
            try:
                msg = self.queue.get(0)
                # Check contents of message and do what it says
                # As a test, we simply print it
                print(str(msg))
                self.editer.appendPlainText(str(msg))
                if self.autoscroll:
                    self.editer.ensureCursorVisible()
                    self.scroll_down()
            except Queue.empty:
                pass

    def scroll_down(self):
        sb = self.editer.verticalScrollBar()
        sb.setValue(sb.maximum())
        self.editer.moveCursor(QTextCursor.End)

    def changePort(self):
        if not self.msg_sent:
            self.msg_sent = True
            self.emit_port_changed()
        else:
            self.msg_sent = False
            return None

#==============================================================================
# Signals
#==============================================================================

    def emit_send_data(self):
        self.send_data.emit(self.get_cmd())
        self.cmd_edit.clear()

    def emit_br_changed(self, value):
        baudrate = self.br_menu.itemText(value)[:-5]
        self.baudrate_changed.emit(baudrate)

    def emit_eol_changed(self, value):
        self.eol_changed.emit(value)

    def emit_port_changed(self):
        self.port_edit.clearFocus()
        self.port_changed.emit(self.port_edit.text())

#==============================================================================
# Events
#==============================================================================
    def ModScrollContentsBy(self, dx, dy):
        if self.autoscroll:
            self.editer.ensureCursorVisible()
        else:
            QPlainTextEdit.scrollContentsBy(self.editer, dx, dy)
예제 #44
0
class MeteoSettings(QDialog):
    applied_signal = pyqtSignal()

    def __init__(self, accurate_url, appid, parent=None):
        super(MeteoSettings, self).__init__(parent)
        self.layout = QVBoxLayout()
        self.accurate_url = accurate_url
        self.appid = appid
        self.settings = QSettings()
        self.set_city = self.settings.value("City") or "?"
        locale = QLocale.system().name()
        locale_long = ["pt_BR", "zh_CN", "zh_TW"]
        if locale not in locale_long:
            locale = locale[:2]
        self.interval_set = self.settings.value("Interval") or "30"
        self.temp_tray_color = self.settings.value("TrayColor") or ""
        # -----Cities comboBox------------------------
        self.first = True
        self.clear_combo = False
        self.city_list_before = []
        self.citylist = []
        self.city_combo = QComboBox()
        if self.set_city != "?":
            self.add_cities_incombo()
        self.city_combo.currentIndexChanged.connect(self.city_default)
        self.city_title = QLabel(self.tr("City"))
        self.city_button = QPushButton()
        self.city_button.setIcon(QIcon(":/configure"))
        self.city_button.setToolTip(self.tr("Click to edit the cities list"))
        self.city_button.clicked.connect(self.edit_cities_list)
        # ------Language------------------------------
        self.language_label = QLabel(self.tr("Language"))
        self.language_combo = QComboBox()
        self.language_combo.setToolTip(
            QCoreApplication.translate(
                "Tooltip", "The application has to be restared to apply the language setting", "Settings dialogue"
            )
        )
        self.language_dico = {
            "bg": self.tr("Bulgarian"),
            "ca": self.tr("Catalan"),
            "cs": self.tr("Czech"),
            "da": self.tr("Danish"),
            "de": self.tr("German"),
            "el": self.tr("Greek"),
            "en": self.tr("English"),
            "es": self.tr("Spanish"),
            "fi": self.tr("Finnish"),
            "fr": self.tr("French"),
            "he": self.tr("Hebrew"),
            "hr": self.tr("Croatian"),
            "hu": self.tr("Hungarian"),
            "it": self.tr("Italian"),
            "ja": self.tr("Japanese"),
            "lt": self.tr("Lithuanian"),
            "nb": self.tr("Norwegian (Bokmaal)"),
            "nl": self.tr("Dutch"),
            "pl": self.tr("Polish"),
            "pt": self.tr("Portuguese"),
            "pt_BR": self.tr("Brazil Portuguese"),
            "ro": self.tr("Romanian"),
            "ru": self.tr("Russian"),
            "sk": self.tr("Slovak"),
            "sv": self.tr("Swedish"),
            "tr": self.tr("Turkish"),
            "uk": self.tr("Ukrainian"),
            "zh_TW": self.tr("Chinese Traditional"),
            "zh_CN": self.tr("Chinese Simplified"),
        }
        lang_list = sorted(self.language_dico.values())
        # English as fallback language
        if locale not in self.language_dico:
            locale = "en"
        self.setLanguage = self.settings.value("Language") or locale
        self.language_combo.addItems(lang_list)
        self.language_combo.setCurrentIndex(self.language_combo.findText(self.language_dico[self.setLanguage]))
        self.language_combo.currentIndexChanged.connect(self.language)
        self.lang_changed = False
        # Unit system
        self.units_changed = False
        self.temp_unit = self.settings.value("Unit")
        if self.temp_unit is None or self.temp_unit == "":
            self.temp_unit = "metric"
            self.units_changed = True
        self.units_label = QLabel(self.tr("Temperature unit"))
        self.units_combo = QComboBox()
        self.units_dico = {"metric": "°C", "imperial": "°F", " ": "°K"}
        units_list = sorted(self.units_dico.values())
        self.units_combo.addItems(units_list)
        self.units_combo.setCurrentIndex(self.units_combo.findText(self.units_dico[self.temp_unit]))
        self.units_combo.currentIndexChanged.connect(self.units)
        # Decimal in trayicon
        self.temp_decimal_label = QLabel(
            QCoreApplication.translate(
                "If the temperature will be shown with a decimal or rounded in tray icon",
                "Temperature accuracy in system tray",
                "Settings dialogue",
            )
        )
        self.temp_decimal_combo = QComboBox()
        temp_decimal_combo_dico = {"False": "0°", "True": "0.1°"}
        temp_decimal_combo_list = [temp_decimal_combo_dico["False"], temp_decimal_combo_dico["True"]]
        self.temp_decimal_combo.addItems(temp_decimal_combo_list)
        temp_decimal_bool_str = self.settings.value("Decimal") or "False"
        self.temp_decimal_combo.setCurrentIndex(
            self.temp_decimal_combo.findText(temp_decimal_combo_dico[temp_decimal_bool_str])
        )
        self.temp_decimal_combo.currentIndexChanged.connect(self.temp_decimal)
        self.temp_decimal_changed = False
        # Interval of updates
        self.interval_label = QLabel(self.tr("Update interval"))
        self.interval_min = QLabel(self.tr("minutes"))
        self.interval_combo = QComboBox()
        self.interval_list = ["15", "30", "45", "60", "90", "120"]
        self.interval_combo.addItems(self.interval_list)
        self.interval_combo.setCurrentIndex(
            self.interval_combo.findText(self.interval_list[self.interval_list.index(self.interval_set)])
        )
        self.interval_combo.currentIndexChanged.connect(self.interval)
        self.interval_changed = False
        # OK Cancel Apply Buttons
        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addStretch()
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Apply | QDialogButtonBox.Cancel)
        self.buttonBox.setContentsMargins(0, 30, 0, 0)
        self.buttonLayout.addWidget(self.buttonBox)
        self.buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.apply_settings)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
        # Autostart
        self.autostart_label = QLabel(self.tr("Launch at startup"))
        self.autostart_checkbox = QCheckBox()
        autostart_bool = self.settings.value("Autostart") or "False"
        autostart_bool = eval(autostart_bool)
        self.autostart_checkbox.setChecked(autostart_bool)
        self.autostart_checkbox.stateChanged.connect(self.autostart)
        self.autostart_changed = False
        # Tray temp° color
        self.temp_colorLabel = QLabel(self.tr("Font colour in the tray"))
        self.temp_colorButton = QPushButton()
        self.temp_colorButton.setStyleSheet("QWidget {{ background-color: {0} }}".format(self.temp_tray_color))
        self.temp_colorButton.setMaximumSize(QSize(44, 24))
        self.temp_colorButton.clicked.connect(self.color_chooser)
        self.temp_color_resetButton = QPushButton(self.tr("Reset"))
        self.temp_color_resetButton.setToolTip(self.tr("Reset font colour to system default"))
        self.temp_color_resetButton.clicked.connect(self.color_reset)
        # Display notifications
        self.notifier_label = QLabel(self.tr("Notification on weather update"))
        self.notifier_checkbox = QCheckBox()
        notifier_bool = self.settings.value("Notifications") or "True"
        notifier_bool = eval(notifier_bool)
        self.notifier_checkbox.setChecked(notifier_bool)
        self.notifier_checkbox.stateChanged.connect(self.notifier)
        self.notifier_changed = False
        # Icon & Temp
        self.tray_icon_temp_label = QLabel(
            QCoreApplication.translate(
                "Settings dialogue",
                "System tray icon",
                """Setting to choose the type of the icon on the tray (only icon,
            only text, icon&text""",
            )
        )
        self.tray_icon_combo = QComboBox()
        tray_icon_temp = QCoreApplication.translate(
            "Settings dialogue", "Icon & temperature", "Setting to choose the type of the icon on the tray"
        )
        tray_icon = QCoreApplication.translate(
            "Settings dialogue", "Icon", "Setting to choose the type of the icon on the tray"
        )
        tray_temp = QCoreApplication.translate(
            "Settings dialogue", "Temperature", "Setting to choose the type of the icon on the tray"
        )
        self.tray_dico = {"icon&temp": tray_icon_temp, "icon": tray_icon, "temp": tray_temp}
        set_tray_icon = self.settings.value("TrayType") or "icon&temp"
        tray_icon_list = sorted(self.tray_dico.values())
        self.tray_icon_combo.addItems(tray_icon_list)
        self.tray_icon_combo.setCurrentIndex(self.tray_icon_combo.findText(self.tray_dico[set_tray_icon]))
        self.tray_icon_combo.currentIndexChanged.connect(self.tray)
        self.tray_changed = False
        # Font size
        fontsize = self.settings.value("FontSize") or "18"
        self.fontsize_label = QLabel(
            QCoreApplication.translate(
                "Settings dialog", "Font size in tray", "Setting for the font size of the temperature in the tray icon"
            )
        )
        self.fontsize_spinbox = QSpinBox()
        self.fontsize_spinbox.setRange(12, 32)
        self.fontsize_spinbox.setValue(int(fontsize))
        if fontsize is None or fontsize == "":
            self.settings.setValue("FontSize", "18")
        self.fontsize_changed = False
        self.fontsize_spinbox.valueChanged.connect(self.fontsize_change)
        # Proxy
        self.proxy_label = QLabel(QCoreApplication.translate("Checkbox", "Connection by proxy", "Settings dialogue"))
        self.proxy_chbox = QCheckBox()
        proxy_bool = self.settings.value("Proxy") or "False"
        self.proxy_bool = eval(proxy_bool)
        self.proxy_chbox.setChecked(self.proxy_bool)
        self.proxy_chbox.stateChanged.connect(self.proxy)
        self.proxy_changed = False
        self.proxy_button = QPushButton(
            QCoreApplication.translate("Label of button to open the proxy dialogue", "Settings", "Settings dialogue")
        )
        self.proxy_button.clicked.connect(self.proxy_settings)
        self.proxy_button.setEnabled(self.proxy_bool)
        # Openweathermap key
        self.owmkey_label = QLabel(
            QCoreApplication.translate(
                "The key that user can generate in his OpenWeatherMap profile",
                "OpenWeatherMap key",
                "Settings dialogue",
            )
        )
        self.owmkey_create = QLabel(
            QCoreApplication.translate(
                "Link to create a profile in OpenWeatherMap",
                '<a href="http://home.openweathermap.org/users/sign_up">Create key</a>',
                "Settings dialogue",
            )
        )
        self.owmkey_create.setOpenExternalLinks(True)
        apikey = self.settings.value("APPID") or ""
        self.owmkey_text = QLineEdit()
        self.owmkey_text.setText(apikey)
        self.owmkey_text.textChanged.connect(self.apikey_changed)
        # ----------
        self.panel = QGridLayout()
        self.panel.addWidget(self.city_title, 0, 0)
        self.panel.addWidget(self.city_combo, 0, 1)
        self.panel.addWidget(self.city_button, 0, 2)
        self.panel.addWidget(self.language_label, 1, 0)
        self.panel.addWidget(self.language_combo, 1, 1)
        self.panel.addWidget(self.units_label, 2, 0)
        self.panel.addWidget(self.units_combo, 2, 1)
        self.panel.addWidget(self.temp_decimal_label, 3, 0)
        self.panel.addWidget(self.temp_decimal_combo, 3, 1)
        self.panel.addWidget(self.interval_label, 4, 0)
        self.panel.addWidget(self.interval_combo, 4, 1)
        self.panel.addWidget(self.interval_min, 4, 2)
        self.panel.addWidget(self.autostart_label, 5, 0)
        self.panel.addWidget(self.autostart_checkbox, 5, 1)
        self.panel.addWidget(self.temp_colorLabel, 6, 0)
        self.panel.addWidget(self.temp_colorButton, 6, 1)
        self.panel.addWidget(self.temp_color_resetButton, 6, 2)
        self.panel.addWidget(self.notifier_label, 7, 0)
        self.panel.addWidget(self.notifier_checkbox, 7, 1)
        self.panel.addWidget(self.tray_icon_temp_label, 8, 0)
        self.panel.addWidget(self.tray_icon_combo, 8, 1)
        self.panel.addWidget(self.fontsize_label, 9, 0)
        self.panel.addWidget(self.fontsize_spinbox, 9, 1)
        self.panel.addWidget(self.proxy_label, 10, 0)
        self.panel.addWidget(self.proxy_chbox, 10, 1)
        self.panel.addWidget(self.proxy_button, 10, 2)
        self.panel.addWidget(self.owmkey_label, 11, 0)
        self.panel.addWidget(self.owmkey_text, 11, 1)
        self.panel.addWidget(self.owmkey_create, 11, 2)

        self.layout.addLayout(self.panel)
        self.layout.addLayout(self.buttonLayout)
        self.statusbar = QLabel()
        self.layout.addWidget(self.statusbar)
        self.nokey_message = QCoreApplication.translate(
            "Warning message after pressing Ok", "Please enter your OpenWeatherMap key", "Settings dialogue"
        )
        self.nocity_message = QCoreApplication.translate(
            "Warning message after pressing OK", "Please add a city", "Settings dialogue"
        )
        self.setLayout(self.layout)
        self.setWindowTitle(self.tr("Meteo-qt Configuration"))

    def units(self):
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
        self.units_changed = True

    def language(self):
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
        self.lang_changed = True

    def city_default(self):
        allitems = [self.city_combo.itemText(i) for i in range(self.city_combo.count())]
        city_name = self.city_combo.currentText()
        citytosave = city_name.split("_")
        if len(citytosave) < 3:
            return
        self.id_before = citytosave[2]
        self.city_before = citytosave[0]
        self.country_before = citytosave[1]
        self.city_list_before = allitems[:]
        self.city_list_before.pop(self.city_list_before.index(city_name))
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def interval(self):
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
        self.interval_changed = True

    def edit_cities_list(self):
        apikey = self.owmkey_text.text()
        apiid = "&APPID=" + apikey
        if apikey == "":
            self.statusbar.setText(self.nokey_message)
            return
        dialog = citylistdlg.CityListDlg(self.citylist, self.accurate_url, apiid, self)
        dialog.citieslist_signal.connect(self.cities_list)
        dialog.exec_()

    def cities_list(self, cit_list):
        if len(cit_list) > 0:
            citytosave = cit_list[0].split("_")
            self.id_before = citytosave[2]
            self.city_before = citytosave[0]
            self.country_before = citytosave[1]
            if len(cit_list) > 1:
                self.city_list_before = cit_list[1:]
            else:
                self.city_list_before = str("")
        else:
            self.id_before = ""
            self.city_before = ""
            self.country_before = ""
            self.city_list_before = []
            self.clear_combo = True
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
        self.first = False
        self.add_cities_incombo()

    def autostart(self, state):
        self.autostart_state = state
        self.autostart_changed = True
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def autostart_apply(self):
        dir_auto = "/.config/autostart/"
        d_file = "meteo-qt.desktop"
        home = os.getenv("HOME")
        total_path = home + dir_auto + d_file
        if self.autostart_state == 2:
            desktop_file = [
                "[Desktop Entry]\n",
                "Exec=meteo-qt\n",
                "Name=meteo-qt\n",
                "Type=Application\n",
                "Version=1.0\n",
                "X-LXQt-Need-Tray=true\n",
            ]
            if not os.path.exists(home + dir_auto):
                os.system("mkdir -p {}".format(os.path.dirname(total_path)))
            with open(total_path, "w") as out_file:
                out_file.writelines(desktop_file)
            self.settings.setValue("Autostart", "True")
            logging.debug("Write desktop file in ~/.config/autostart")
        elif self.autostart_state == 0:
            if os.path.exists(total_path):
                os.remove(total_path)
            self.settings.setValue("Autostart", "False")
            logging.debug("Remove desktop file from ~/.config/autostart")
        else:
            return

    def color_chooser(self):
        col = QColorDialog.getColor()
        if col.isValid():
            self.temp_colorButton.setStyleSheet("QWidget {{ background-color: {0} }}".format(col.name()))
            # focus to next elem to show immediatley the colour
            # in the button (in some DEs)
            self.temp_color_resetButton.setFocus()
            self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
            self.color_before = col.name()
        else:
            logging.debug("Invalid color:" + str(col))

    def color_reset(self):
        self.temp_colorButton.setStyleSheet("QWidget { background-color:  }")
        self.color_before = ""
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def notifier(self, state):
        self.notifier_state = state
        self.notifier_changed = True
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def notifier_apply(self):
        if self.notifier_state == 2:
            self.settings.setValue("Notifications", "True")
            logging.debug("Write: Notifications = True")
        elif self.notifier_state == 0:
            self.settings.setValue("Notifications", "False")
            logging.debug("Write: Notifications = False")

    def temp_decimal(self, state):
        self.temp_decimal_state = state
        self.temp_decimal_changed = True
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def tray(self):
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
        self.tray_changed = True

    def tray_apply(self):
        tray = self.tray_icon_combo.currentText()
        self.settings.setValue("Tray", tray)
        logging.debug("Write >" + "Tray >" + str(tray))
        settray = [key for key, value in self.tray_dico.items() if value == tray]
        self.settings.setValue("TrayType", settray[0])

    def fontsize_change(self, size):
        self.fontsize_changed = True
        self.fontsize_value = size
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def fontsize_apply(self):
        logging.debug("Apply fontsize: " + str(self.fontsize_value))
        self.settings.setValue("FontSize", str(self.fontsize_value))

    def proxy(self, state):
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
        if state == 2:
            self.proxy_bool = True
            self.proxy_button.setEnabled(True)
        else:
            self.proxy_bool = False
            self.proxy_button.setEnabled(False)

    def proxy_settings(self):
        dialog = proxydlg.Proxy(self)
        dialog.exec_()

    def apikey_changed(self):
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)

    def apply_settings(self):
        self.accepted()

    def accepted(self):
        apikey = self.owmkey_text.text()
        city_name = self.city_combo.currentText()
        if apikey == "":
            self.statusbar.setText(self.nokey_message)
            return
        else:
            self.statusbar.setText("")
            self.settings.setValue("APPID", str(self.owmkey_text.text()))
        if city_name == "":
            self.statusbar.setText(self.nocity_message)
            return
        else:
            self.statusbar.setText("")
        self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
        if hasattr(self, "id_before"):
            self.settings.setValue("ID", self.id_before)
            logging.debug("write " + "ID" + str(self.id_before))
        if hasattr(self, "city_before"):
            self.settings.setValue("City", self.city_before)
            logging.debug("write " + "City" + str(self.city_before))
        if hasattr(self, "country_before"):
            self.settings.setValue("Country", self.country_before)
            logging.debug("write " + "Country" + str(self.country_before))
        if hasattr(self, "city_list_before"):
            self.settings.setValue("CityList", str(self.city_list_before))
            logging.debug("write " + "CityList" + str(self.city_list_before))
        if hasattr(self, "color_before"):
            self.settings.setValue("TrayColor", self.color_before)
            if self.color_before == "":
                self.color_before = "None"
            logging.debug("Write font color for temp in tray: {0}".format(self.color_before))
        if self.autostart_changed:
            self.autostart_apply()
        if self.interval_changed:
            time = self.interval_combo.currentText()
            self.settings.setValue("Interval", time)
            logging.debug("Write " + "Interval " + str(time))
        if self.lang_changed:
            lang = self.language_combo.currentText()
            setlang = [key for key, value in self.language_dico.items() if value == lang]
            self.settings.setValue("Language", setlang[0])
            logging.debug("Write " + "Language " + str(setlang[0]))
        if self.units_changed:
            unit = self.units_combo.currentText()
            setUnit = [key for key, value in self.units_dico.items() if value == unit]
            self.settings.setValue("Unit", setUnit[0])
            logging.debug("Write " + "Unit " + str(setUnit[0]))
        if self.temp_decimal_changed:
            decimal = self.temp_decimal_combo.currentText()
            decimal_bool_str = "False"
            if decimal == "0.1°":
                decimal_bool_str = "True"
            self.settings.setValue("Decimal", decimal_bool_str)
            logging.debug("Write: Decimal in tray icon = " + decimal_bool_str)
        if self.notifier_changed:
            self.notifier_apply()
        if self.tray_changed:
            self.tray_apply()
        if self.fontsize_changed:
            self.fontsize_apply()
        proxy_url = self.settings.value("Proxy_url") or ""
        if proxy_url == "":
            self.proxy_bool = False
        self.settings.setValue("Proxy", str(self.proxy_bool))
        self.applied_signal.emit()

    def accept(self):
        self.accepted()
        apikey = self.owmkey_text.text()
        city_name = self.city_combo.currentText()
        if apikey == "":
            self.statusbar.setText(self.nokey_message)
            return
        if city_name == "":
            self.statusbar.setText(self.nocity_message)
            return
        QDialog.accept(self)

    def add_cities_incombo(self):
        list_cities = ""
        self.city_combo.clear()
        if self.clear_combo:
            return
        if self.first:
            list_cities = self.settings.value("CityList")
            if list_cities is not None:
                self.city_list_before = list_cities[:]
            self.citylist = [self.set_city + "_" + self.settings.value("Country") + "_" + self.settings.value("ID")]
        else:
            self.citylist = [self.city_before + "_" + self.country_before + "_" + self.id_before]
            list_cities = self.city_list_before[:]
        if list_cities is None:
            list_cities = []
        if list_cities != "" and list_cities is not None:
            if type(list_cities) is str:
                list_cities = eval(list_cities)
            self.citylist = self.citylist + list_cities
        duplicate = []
        for i in self.citylist:
            if i not in duplicate:
                duplicate.append(i)
        self.citylist = duplicate[:]
        self.city_combo.addItems(self.citylist)
        if len(list_cities) > 0:
            maxi = len(max(list_cities, key=len))
            self.city_combo.setMinimumSize(maxi * 8, 23)
예제 #45
0
class EditorAssembly(QWidget):
    """
    Class implementing the editor assembly widget containing the navigation
    combos and the editor widget.
    """
    def __init__(self, dbs, fn=None, vm=None, filetype="", editor=None,
                 tv=None):
        """
        Constructor
        
        @param dbs reference to the debug server object
        @param fn name of the file to be opened (string). If it is None,
            a new (empty) editor is opened
        @param vm reference to the view manager object
            (ViewManager.ViewManager)
        @param filetype type of the source file (string)
        @param editor reference to an Editor object, if this is a cloned view
        @param tv reference to the task viewer object
        """
        super(EditorAssembly, self).__init__()
        
        self.__layout = QGridLayout(self)
        self.__layout.setContentsMargins(0, 0, 0, 0)
        self.__layout.setSpacing(1)
        
        self.__globalsCombo = QComboBox()
        self.__membersCombo = QComboBox()
        from .Editor import Editor
        self.__editor = Editor(dbs, fn, vm, filetype, editor, tv)
        
        self.__layout.addWidget(self.__globalsCombo, 0, 0)
        self.__layout.addWidget(self.__membersCombo, 0, 1)
        self.__layout.addWidget(self.__editor, 1, 0, 1, -1)
        
        self.__module = None
        
        self.__globalsCombo.activated[int].connect(self.__globalsActivated)
        self.__membersCombo.activated[int].connect(self.__membersActivated)
        self.__editor.cursorLineChanged.connect(self.__editorCursorLineChanged)
        
        self.__parseTimer = QTimer(self)
        self.__parseTimer.setSingleShot(True)
        self.__parseTimer.setInterval(5 * 1000)
        self.__parseTimer.timeout.connect(self.__parseEditor)
        self.__editor.textChanged.connect(self.__resetParseTimer)
        self.__editor.refreshed.connect(self.__resetParseTimer)
        
        self.__selectedGlobal = ""
        self.__selectedMember = ""
        self.__globalsBoundaries = {}
        self.__membersBoundaries = {}
        
        QTimer.singleShot(0, self.__parseEditor)
    
    def shutdownTimer(self):
        """
        Public method to stop and disconnect the timer.
        """
        self.__parseTimer.stop()
        self.__parseTimer.timeout.disconnect(self.__parseEditor)
        self.__editor.textChanged.disconnect(self.__resetParseTimer)
        self.__editor.refreshed.disconnect(self.__resetParseTimer)
    
    def getEditor(self):
        """
        Public method to get the reference to the editor widget.
        
        @return reference to the editor widget (Editor)
        """
        return self.__editor
    
    def __globalsActivated(self, index, moveCursor=True):
        """
        Private method to jump to the line of the selected global entry and to
        populate the members combo box.
        
        @param index index of the selected entry (integer)
        @keyparam moveCursor flag indicating to move the editor cursor
            (boolean)
        """
        # step 1: go to the line of the selected entry
        lineno = self.__globalsCombo.itemData(index)
        if lineno is not None:
            if moveCursor:
                txt = self.__editor.text(lineno - 1).rstrip()
                pos = len(txt.replace(txt.strip(), ""))
                self.__editor.gotoLine(
                    lineno, pos if pos == 0 else pos + 1, True)
                self.__editor.setFocus()
            
            # step 2: populate the members combo, if the entry is a class
            self.__membersCombo.clear()
            self.__membersBoundaries = {}
            self.__membersCombo.addItem("")
            memberIndex = 0
            entryName = self.__globalsCombo.itemText(index)
            if self.__module:
                if entryName in self.__module.classes:
                    entry = self.__module.classes[entryName]
                elif entryName in self.__module.modules:
                    entry = self.__module.modules[entryName]
                    # step 2.0: add module classes
                    items = {}
                    for cl in entry.classes.values():
                        if cl.isPrivate():
                            icon = UI.PixmapCache.getIcon("class_private.png")
                        elif cl.isProtected():
                            icon = UI.PixmapCache.getIcon(
                                "class_protected.png")
                        else:
                            icon = UI.PixmapCache.getIcon("class.png")
                        items[cl.name] = (icon, cl.lineno, cl.endlineno)
                    for key in sorted(items.keys()):
                        itm = items[key]
                        self.__membersCombo.addItem(itm[0], key, itm[1])
                        memberIndex += 1
                        self.__membersBoundaries[(itm[1], itm[2])] = \
                            memberIndex
                else:
                    return
                
                # step 2.1: add class methods
                from Utilities.ModuleParser import Function
                items = {}
                for meth in entry.methods.values():
                    if meth.modifier == Function.Static:
                        icon = UI.PixmapCache.getIcon("method_static.png")
                    elif meth.modifier == Function.Class:
                        icon = UI.PixmapCache.getIcon("method_class.png")
                    elif meth.isPrivate():
                        icon = UI.PixmapCache.getIcon("method_private.png")
                    elif meth.isProtected():
                        icon = UI.PixmapCache.getIcon("method_protected.png")
                    else:
                        icon = UI.PixmapCache.getIcon("method.png")
                    items[meth.name] = (icon, meth.lineno, meth.endlineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__membersCombo.addItem(itm[0], key, itm[1])
                    memberIndex += 1
                    self.__membersBoundaries[(itm[1], itm[2])] = memberIndex
                
                # step 2.2: add class instance attributes
                items = {}
                for attr in entry.attributes.values():
                    if attr.isPrivate():
                        icon = UI.PixmapCache.getIcon("attribute_private.png")
                    elif attr.isProtected():
                        icon = UI.PixmapCache.getIcon(
                            "attribute_protected.png")
                    else:
                        icon = UI.PixmapCache.getIcon("attribute.png")
                    items[attr.name] = (icon, attr.lineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__membersCombo.addItem(itm[0], key, itm[1])
                
                # step 2.3: add class attributes
                items = {}
                icon = UI.PixmapCache.getIcon("attribute_class.png")
                for glob in entry.globals.values():
                    items[glob.name] = (icon, glob.lineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__membersCombo.addItem(itm[0], key, itm[1])
    
    def __membersActivated(self, index, moveCursor=True):
        """
        Private method to jump to the line of the selected members entry.
        
        @param index index of the selected entry (integer)
        @keyparam moveCursor flag indicating to move the editor cursor
            (boolean)
        """
        lineno = self.__membersCombo.itemData(index)
        if lineno is not None and moveCursor:
            txt = self.__editor.text(lineno - 1).rstrip()
            pos = len(txt.replace(txt.strip(), ""))
            self.__editor.gotoLine(lineno, pos if pos == 0 else pos + 1, True)
            self.__editor.setFocus()
    
    def __resetParseTimer(self):
        """
        Private slot to reset the parse timer.
        """
        self.__parseTimer.stop()
        self.__parseTimer.start()
    
    def __parseEditor(self):
        """
        Private method to parse the editor source and repopulate the globals
        combo.
        """
        from Utilities.ModuleParser import Module, getTypeFromTypeName
        
        self.__module = None
        sourceType = getTypeFromTypeName(self.__editor.determineFileType())
        if sourceType != -1:
            src = self.__editor.text()
            if src:
                fn = self.__editor.getFileName()
                if fn is None:
                    fn = ""
                self.__module = Module("", fn, sourceType)
                self.__module.scan(src)
                
                # remember the current selections
                self.__selectedGlobal = self.__globalsCombo.currentText()
                self.__selectedMember = self.__membersCombo.currentText()
                
                self.__globalsCombo.clear()
                self.__membersCombo.clear()
                self.__globalsBoundaries = {}
                self.__membersBoundaries = {}
                
                self.__globalsCombo.addItem("")
                index = 0
                
                # step 1: add modules
                items = {}
                for module in self.__module.modules.values():
                    items[module.name] = (UI.PixmapCache.getIcon("module.png"),
                                          module.lineno, module.endlineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__globalsCombo.addItem(itm[0], key, itm[1])
                    index += 1
                    self.__globalsBoundaries[(itm[1], itm[2])] = index
                
                # step 2: add classes
                items = {}
                for cl in self.__module.classes.values():
                    if cl.isPrivate():
                        icon = UI.PixmapCache.getIcon("class_private.png")
                    elif cl.isProtected():
                        icon = UI.PixmapCache.getIcon("class_protected.png")
                    else:
                        icon = UI.PixmapCache.getIcon("class.png")
                    items[cl.name] = (icon, cl.lineno, cl.endlineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__globalsCombo.addItem(itm[0], key, itm[1])
                    index += 1
                    self.__globalsBoundaries[(itm[1], itm[2])] = index
                
                # step 3: add functions
                items = {}
                for func in self.__module.functions.values():
                    if func.isPrivate():
                        icon = UI.PixmapCache.getIcon("method_private.png")
                    elif func.isProtected():
                        icon = UI.PixmapCache.getIcon("method_protected.png")
                    else:
                        icon = UI.PixmapCache.getIcon("method.png")
                    items[func.name] = (icon, func.lineno, func.endlineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__globalsCombo.addItem(itm[0], key, itm[1])
                    index += 1
                    self.__globalsBoundaries[(itm[1], itm[2])] = index
                
                # step 4: add attributes
                items = {}
                for glob in self.__module.globals.values():
                    if glob.isPrivate():
                        icon = UI.PixmapCache.getIcon("attribute_private.png")
                    elif glob.isProtected():
                        icon = UI.PixmapCache.getIcon(
                            "attribute_protected.png")
                    else:
                        icon = UI.PixmapCache.getIcon("attribute.png")
                    items[glob.name] = (icon, glob.lineno)
                for key in sorted(items.keys()):
                    itm = items[key]
                    self.__globalsCombo.addItem(itm[0], key, itm[1])
                
                # reset the currently selected entries without moving the
                # text cursor
                index = self.__globalsCombo.findText(self.__selectedGlobal)
                if index != -1:
                    self.__globalsCombo.setCurrentIndex(index)
                    self.__globalsActivated(index, moveCursor=False)
                index = self.__membersCombo.findText(self.__selectedMember)
                if index != -1:
                    self.__membersCombo.setCurrentIndex(index)
                    self.__membersActivated(index, moveCursor=False)
    
    def __editorCursorLineChanged(self, lineno):
        """
        Private slot handling a line change of the cursor of the editor.
        
        @param lineno line number of the cursor (integer)
        """
        lineno += 1     # cursor position is zero based, code info one based
        
        # step 1: search in the globals
        for (lower, upper), index in self.__globalsBoundaries.items():
            if upper == -1:
                upper = 1000000     # it is the last line
            if lower <= lineno <= upper:
                break
        else:
            index = 0
        self.__globalsCombo.setCurrentIndex(index)
        self.__globalsActivated(index, moveCursor=False)
        
        # step 2: search in members
        for (lower, upper), index in self.__membersBoundaries.items():
            if upper == -1:
                upper = 1000000     # it is the last line
            if lower <= lineno <= upper:
                break
        else:
            index = 0
        self.__membersCombo.setCurrentIndex(index)
        self.__membersActivated(index, moveCursor=False)
예제 #46
0
class EditDialog(QDialog):
    """
    Widget for netlist line creation and edition.
    """
    def __init__(self, parent=None, netline=None):
        """
        Widget for netlist line creation and edition.
        if 'netline' is None, a new line is created.
        """
        super(EditDialog, self).__init__(parent)

        self.initUI(netline)

    def initUI(self, netline):

        # -------------------------------

        if netline is None:
            netline = {
                'arguments': None,
                'component': None,
                'dictionary': None,
                'label': None,
                'nodes': None
            }
        self.netline = netline

        # -------------------------------

        self.netlistQlabel = QLabel('', self)

        # -------------------------------

        self.titlegrid = QGridLayout()
        self.titlegrid.addWidget(QLabel('Label'), 0, 0)
        self.titlegrid.addWidget(QLabel('Dictionary'), 0, 2)
        self.titlegrid.addWidget(QLabel('Component'), 0, 4)

        # -------------------------------

        self.label = LabelWidget(self.netline['label'])
        self.label.textChanged[str].connect(self.onChanged_label)
        self.titlegrid.addWidget(self.label, 0, 1)

        # -------------------------------

        self.Qdico = QComboBox(self.parent())
        self.Qdico.activated[str].connect(self.onActivated_Qdico)
        self.titlegrid.addWidget(self.Qdico, 0, 3)
        self.Qdico.addItem('Select below...')
        for dico in PHSdictionary.__all__:
            self.Qdico.addItem(dico)

        # -------------------------------

        self.Qcomp = QComboBox(self.parent())
        self.Qcomp.activated[str].connect(self.onActivated_Qcomp)
        self.titlegrid.addWidget(self.Qcomp, 0, 5)
        self.Qcomp.addItem('Select dictionary...')

        # -------------------------------

        self.hnodes = QHBoxLayout()
        self.hnodes.addWidget(QLabel('Nodes'))

        self.nodesgrid = QGridLayout()
        self.nodesgrid.addWidget(QLineEdit(), 0, 0)

        self.hnodes.addLayout(self.nodesgrid)

        self.hnodes.addStretch()

        # -------------------------------

        self.hargs = QHBoxLayout()
        self.hargs.addWidget(QLabel('Parameters'))

        self.argsgrid = QGridLayout()
        self.argsgrid.addWidget(QLineEdit(), 0, 0)

        self.hargs.addLayout(self.argsgrid)

        self.hargs.addStretch()

        # -------------------------------

        index = self.Qdico.findText(self.netline['dictionary'],
                                    Qt.MatchFixedString)
        if index >= 0:
            self.Qdico.setCurrentIndex(index)

        self.init_comp()

        # -------------------------------

        # OK and Cancel buttons
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        # -------------------------------

        vbox = QVBoxLayout()

        scrollnetlistQlabel = QScrollArea()
        scrollnetlistQlabel.setWidget(self.netlistQlabel)
        scrollnetlistQlabel.setFixedHeight(100)
        scrollnetlistQlabel.setWidgetResizable(True)

        vbox.addWidget(scrollnetlistQlabel)

        vbox.addLayout(self.titlegrid)

        scrollnodes = QScrollArea()
        widgetnodes = QWidget()
        widgetnodes.setLayout(self.hnodes)
        scrollnodes.setWidget(widgetnodes)
        scrollnodes.setFixedHeight(100)
        scrollnodes.setWidgetResizable(True)

        scrollargs = QScrollArea()
        widgetargs = QWidget()
        widgetargs.setLayout(self.hargs)
        scrollargs.setWidget(widgetargs)
        scrollargs.setFixedHeight(100)
        scrollargs.setWidgetResizable(True)

        vbox.addWidget(scrollnodes)
        vbox.addWidget(scrollargs)
        vbox.addStretch(1)
        vbox.addWidget(buttons)
        self.setLayout(vbox)
        self.setWindowTitle('Edit component')

    def onChanged_label(self, text):
        self.netline['label'] = str(text)
        self.update_Qlabel()

    def update_Qlabel(self):
        text = print_netlist_line(self.netline)
        self.netlistQlabel.setText(text)
        self.netlistQlabel.adjustSize()

    ###########################################################################
    def onActivated_Qdico(self, text):
        if str(text) == 'Select below...':

            self.netline.update({
                'dictionary': None,
                'arguments': None,
                'component': None,
                'nodes': None
            })
        else:
            self.netline.update({
                'dictionary': str(text),
                'arguments': None,
                'component': None,
                'nodes': None
            })
        self.update_Qlabel()
        self.init_comp()

    ###########################################################################

    def get_dico(self):
        if self.netline['dictionary'] is None:
            return None
        else:
            return getattr(PHSdictionary, self.netline['dictionary'])

    def get_comp(self):
        if (self.netline['dictionary'] is None
                or self.netline['component'] is None):
            return None
        else:
            compname = (self.netline['component'][0].upper() +
                        self.netline['component'][1:].lower())
            return getattr(self.get_dico(), compname)

    def init_comp(self):

        while self.Qcomp.itemText(0) != '':
            self.Qcomp.removeItem(0)

        if self.netline['dictionary'] is None:
            self.Qcomp.addItem('Select dictionary...')
            self.netline['component'] = None

        else:
            self.Qcomp.addItem('Select below...')

            dico = self.get_dico()
            for component in dico.__all__:
                self.Qcomp.addItem(component)
            index = self.Qcomp.findText(self.netline['component'],
                                        Qt.MatchFixedString)
            if index >= 0:
                self.Qcomp.setCurrentIndex(index)

        self.init_parameters()

    def onActivated_Qcomp(self, text):
        if str(text) in ['Select dictionary...', 'Select below...']:
            self.netline.update({
                'component': None,
                'arguments': None,
                'nodes': None
            })
        else:
            self.netline.update({
                'component': str(text).lower(),
                'arguments': None,
                'nodes': None
            })
        self.init_parameters()

    ###########################################################################

    def init_parameters(self):

        i = 0
        item = self.nodesgrid.itemAtPosition(0, 0)
        while item is not None:
            w = item.widget()
            self.nodesgrid.removeWidget(w)
            w.deleteLater()
            w = None
            i += 1
            item = self.nodesgrid.itemAtPosition(0, i)

        i = 0
        item = self.argsgrid.itemAtPosition(0, 0)
        while item is not None:
            w = item.widget()
            self.argsgrid.removeWidget(w)
            w.deleteLater()
            w = None
            i += 1
            item = self.argsgrid.itemAtPosition(0, i)

        if (self.netline['dictionary'] is None
                or self.netline['component'] is None):
            self.nodesgrid.addWidget(QLineEdit(), 0, 0)
            self.argsgrid.addWidget(QLineEdit(), 0, 0)
        else:

            comp = self.get_comp()

            if self.netline['nodes'] is None:
                nodes = comp.metadata()['nodes']
                self.netline['nodes'] = nodes
            else:
                nodes = self.netline['nodes']

            for i, node in enumerate(nodes):
                w = self.widget_generator(comp.metadata()['nodes'][i])(self)
                onchange = self.onchange_generator('nodes', i)
                w.qle.textChanged[str].connect(onchange)
                w.qle.setText(node)
                self.nodesgrid.addWidget(w, 0, i)

            if self.netline['arguments'] is None:
                arguments = comp.metadata()['arguments']
                self.netline['arguments'] = arguments
            else:
                arguments = self.netline['arguments']

            for i, arg in enumerate(arguments.keys()):
                label = list(comp.metadata()['arguments'].keys())[i]
                w = self.widget_generator(label)(self)
                onchange = self.onchange_generator('arguments', arg)
                w.qle.textChanged[str].connect(onchange)
                obj = arguments[arg]
                if isinstance(obj, str):
                    w.qle.setText("'%s'" % obj)
                else:
                    w.qle.setText(str(obj))
                self.argsgrid.addWidget(w, 0, i)

        self.update_Qlabel()

    def widget_generator(self, label):
        class MyWidget(QWidget):
            def __init__(self, parent=None):
                super(MyWidget, self).__init__(parent)
                QWidget.__init__(self)
                hbox = QHBoxLayout()
                hbox.addWidget(QLabel(str(label) + ':'))
                self.qle = QLineEdit(self)
                self.qle.setMinimumWidth(100)
                hbox.addWidget(self.qle)
                self.setLayout(hbox)

        return MyWidget

    def onchange_generator(self, target, index):
        def onchange_node(text):
            tup = self.netline['nodes']
            lis = list(tup)
            lis[index] = str(text)
            self.netline['nodes'] = tuple(lis)
            self.update_Qlabel()

        def onchange_arg(text):
            try:
                value = ast.literal_eval(text)
            except (ValueError, SyntaxError):
                value = str(text)
            self.netline['arguments'][index] = value
            self.update_Qlabel()

        if target == 'nodes':
            return onchange_node
        elif target == 'arguments':
            return onchange_arg

    # static method to create the dialog and return (netline, accepted)
    @staticmethod
    def getNetline(parent=None, netline=None):
        dialog = EditDialog(parent, netline)
        result = dialog.exec_()
        netline = dialog.netline
        dialog.deleteLater()
        return (netline, result == QDialog.Accepted)
예제 #47
0
class Tran2gpsGui(QWidget):
	def __init__(self):
		super().__init__()
		self.init_ui()

	def init_ui(self):
		input_label = QLabel('原始数据:')

		src_label = QLabel('数据来源')
		self.src_combo = QComboBox()
		self.src_combo.addItems(['服务器log', '数据库','纯WiFi','纯LBS'])

		api_label = QLabel('API')
		self.api_combo = QComboBox()
		self.api_combo.addItems(['高德'])  # 目前仅一个选项
		self.api_combo.setEnabled(False)

		run_btn = QPushButton('转换')
		clr_btn = QPushButton('清空结果')

		lb_wifi = QLabel('纯WiFi:')
		lb_lbs = QLabel('纯LBS:')
		lb_mix = QLabel('混合:')
		lb_wifi.setFixedWidth(40)
		lb_lbs.setFixedWidth(40)
		lb_mix.setFixedWidth(40)

		hBox = QHBoxLayout()
		hBox.addWidget(src_label)
		hBox.addWidget(self.src_combo)
		hBox.addStretch()
		hBox.addWidget(api_label)
		hBox.addWidget(self.api_combo)
		hBox.addStretch()
		hBox.addWidget(run_btn)
		hBox.addWidget(clr_btn)

		self.in_text = QTextEdit()
		self.in_text.setAcceptRichText(False)

		self.req_wifi_text = QTextEdit()
		self.req_wifi_text.setAcceptRichText(False)
		self.req_wifi_text.setReadOnly(True)
		self.out_wifi_text = QTextEdit()
		self.out_wifi_text.setAcceptRichText(False)
		self.out_wifi_text.setReadOnly(True)
		hbox_wifi = QHBoxLayout()
		hbox_wifi.addWidget(lb_wifi)
		hbox_wifi.addWidget(self.req_wifi_text)
		hbox_wifi.addWidget(self.out_wifi_text)

		self.req_lbs_text = QTextEdit()
		self.req_lbs_text.setAcceptRichText(False)
		self.req_lbs_text.setReadOnly(True)
		self.out_lbs_text = QTextEdit()
		self.out_lbs_text.setAcceptRichText(False)
		self.out_lbs_text.setReadOnly(True)
		hbox_lbs = QHBoxLayout()
		hbox_lbs.addWidget(lb_lbs)
		hbox_lbs.addWidget(self.req_lbs_text)
		hbox_lbs.addWidget(self.out_lbs_text)

		self.req_mix_text = QTextEdit()
		self.req_mix_text.setAcceptRichText(False)
		self.req_mix_text.setReadOnly(True)
		self.out_mix_text = QTextEdit()
		self.out_mix_text.setAcceptRichText(False)
		self.out_mix_text.setReadOnly(True)
		hbox_mix = QHBoxLayout()
		hbox_mix.addWidget(lb_mix)
		hbox_mix.addWidget(self.req_mix_text)
		hbox_mix.addWidget(self.out_mix_text)

		self.req_wifi_text.setPlainText('WiFi请求')
		self.out_wifi_text.setPlainText('WiFi结果')
		self.req_lbs_text.setPlainText('LBS请求')
		self.out_lbs_text.setPlainText('LBS结果')
		self.req_mix_text.setPlainText('WiFi+LBS请求')
		self.out_mix_text.setPlainText('WiFi+LBS结果')
		self.req_wifi_text.setEnabled(False)
		self.out_wifi_text.setEnabled(False)
		self.req_lbs_text.setEnabled(False)
		self.out_lbs_text.setEnabled(False)
		self.req_mix_text.setEnabled(False)
		self.out_mix_text.setEnabled(False)

		vBox = QVBoxLayout()
		vBox.addWidget(input_label)
		vBox.addWidget(self.in_text)
		vBox.addLayout(hBox)
		vBox.addLayout(hbox_wifi)
		vBox.addLayout(hbox_lbs)
		vBox.addLayout(hbox_mix)

		run_btn.clicked.connect(self.runButtonClicked)
		clr_btn.clicked.connect(self.clrButtonClicked)

		self.setLayout(vBox)
		self.setWindowTitle('LBS/WiFi位置查询')
		self.show()

	def runButtonClicked(self):
		self.req_wifi_text.setEnabled(True)
		self.out_wifi_text.setEnabled(True)
		self.req_lbs_text.setEnabled(True)
		self.out_lbs_text.setEnabled(True)
		self.req_mix_text.setEnabled(True)
		self.out_mix_text.setEnabled(True)
	
		src = self.src_combo.currentText()

		log = self.in_text.toPlainText()
		if log == '':
			if src == self.src_combo.itemText(0):
				self.in_text.setPlainText('[示例数据]' + EXAMPLE_SRVLOG)
				log = EXAMPLE_SRVLOG
			elif src == self.src_combo.itemText(1):
				self.in_text.setPlainText('[示例数据]' + EXAMPLE_DB)
				log = EXAMPLE_DB
			elif src == self.src_combo.itemText(2):
				self.in_text.setPlainText('[示例数据]' + EXAMPLE_INPUT_WIFI)
				log = EXAMPLE_INPUT_WIFI
			elif src == self.src_combo.itemText(3):
				self.in_text.setPlainText('[示例数据]' + EXAMPLE_INPUT_LBS)
				log = EXAMPLE_INPUT_LBS

		try:
			req, res = tran2GPS_2.transfer(log, src, 'WiFi')
			self.req_wifi_text.setPlainText(''.join(req))
			self.out_wifi_text.setPlainText(''.join(res))
		except Exception as e:
			print(e)
			self.req_wifi_text.setPlainText('错误')
			self.out_wifi_text.setPlainText('错误')

		try:
			req, res = tran2GPS_2.transfer(log, src, 'LBS')
			self.req_lbs_text.setPlainText(''.join(req))
			self.out_lbs_text.setPlainText(''.join(res))
		except Exception as e:
			print(e)
			self.req_lbs_text.setPlainText('错误')
			self.out_lbs_text.setPlainText('错误')

		try:
			req, res = tran2GPS_2.transfer(log, src, 'mix')
			self.req_mix_text.setPlainText(''.join(req))
			self.out_mix_text.setPlainText(''.join(res))
		except Exception as e:
			print(e)
			self.req_mix_text.setPlainText('错误')
			self.out_mix_text.setPlainText('错误')

	def clrButtonClicked(self):
		self.in_text.setPlainText('')

		self.req_wifi_text.setPlainText('WiFi请求')
		self.out_wifi_text.setPlainText('WiFi结果')
		self.req_lbs_text.setPlainText('LBS请求')
		self.out_lbs_text.setPlainText('LBS结果')
		self.req_mix_text.setPlainText('WiFi+LBS请求')
		self.out_mix_text.setPlainText('WiFi+LBS结果')
		self.req_wifi_text.setEnabled(False)
		self.out_wifi_text.setEnabled(False)
		self.req_lbs_text.setEnabled(False)
		self.out_lbs_text.setEnabled(False)
		self.req_mix_text.setEnabled(False)
		self.out_mix_text.setEnabled(False)
예제 #48
0
class Montages(QWidget):

    # Attributes
    CONF_SUBSECTION = 'montages'
    IMG_PATH = 'images'
    shortcut = None

    # Signals
    filters_transform_changed = pyqtSignal(name='filters_transform_changed')

    def __init__(self, parent):
        super(Montages, self).__init__(parent)

        self.transform_list_stack = self.parent()
        self.preview = self.transform_list_stack.parent().signal_preview
        self.main = self.transform_list_stack.main

        self.title = 'Montages'

        # Transform
        self.preview_transform = None

        # Master layout
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        # Filter design widget layout
        montage_layout = QVBoxLayout()
        montage_layout.setContentsMargins(0, 0, 0, 0)

        # Montage selector
        self.montage_selector_label = QLabel('Select montage type:', self)
        self.montage_selector = QComboBox(self)
        self.montage_selector.addItem('Unipolar')

        # Channel selector for montage
        self.channel_selector_label = QLabel('Select channel:', self)
        self.channel_selector = QComboBox(self)

        # Set button
        self.set_button = QPushButton('Set', self)

        # Asseble the layout
        montage_layout.addWidget(self.montage_selector_label)
        montage_layout.addWidget(self.montage_selector)
        montage_layout.addWidget(self.channel_selector_label)
        montage_layout.addWidget(self.channel_selector)
        montage_layout.addWidget(self.set_button)

        layout.addLayout(montage_layout)
        layout.setAlignment(Qt.AlignTop)

        self.setLayout(layout)

        # Connect signals
        self.montage_selector.currentIndexChanged.connect(self.set_m_layout)
        self.channel_selector.currentIndexChanged.connect(
            self.set_second_channel)
        self.set_button.clicked.connect(self.set_preview_transform)

    def set_m_layout(self, int):
        return

    def set_second_channel(self, ch_idx):
        if ch_idx < 0:
            return
        self.second_channel = self.channel_selector.itemText(ch_idx)
        self.second_channel_pos = np.where(
            sm.PDS.data_map['channels'] == self.second_channel)[0][0]

    def set_channels(self):
        # TODO: Show only channels that can be montaged!!! - same fs
        self.channel_selector.clear()
        for channel in sm.ODS.data_map['channels']:
            self.channel_selector.addItem(channel)

    def create_transform(self, vc):

        # Design the filter
        selected_channel = self.channel_selector.currentText()

        # Greate the transform object
        transform = MontageTransform()
        transform.second_channel = self.second_channel
        transform.second_channel_pos = self.second_channel_pos
        transform.name = '-' + selected_channel
        vc.add_channels.append(selected_channel)
        vc.data_array_pos.append(self.second_channel_pos)

        return transform

    # ??? Should be part of transforms API??
    def set_preview_transform(self):

        vc = self.preview.preview_pvc
        self.preview.preview_temp_transform = self.create_transform(vc)
        self.preview.update_trans_sig()

    # ----- Transforms API -----
    def get_transform_title(self):
        """Return widget title"""
        return self.title

    def register_transform(self):
        """
        Register transform in Transforms plugin.
        """

        # Connect signals
        self.main.sig_file_opened.connect(self.set_channels)

        return
예제 #49
0
class LoginScreen(QWidget):
    """
    The login screen lets the user select a user profile or create a new one.
    """

    login_successful = pyqtSignal(str, UserProfile, name="login_successful")

    def __init__(self, *args, **kwargs):
        """
        Load the user profiles and create the login controls.
        """
        super().__init__(*args, **kwargs)

        # Load the user profile collection.
        try:
            self.user_profile_collection = UserProfileCollection.from_dict(global_settings["users"])
        except KeyError:
            self.user_profile_collection = UserProfileCollection()

        # Create and set the widget layout.
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignCenter)
        self.setLayout(layout)

        # Fill the select-user combobox with the loaded profile names.
        self.select_user_combobox = QComboBox()
        layout.addWidget(self.select_user_combobox)
        self.select_user_combobox.addItem("")
        names = self.user_profile_collection.names()
        names = [(name.lower(), name) for name in names]  # convert to lower case for sorting
        for _, name in sorted(names):
            self.select_user_combobox.addItem(name)

        # Add the login button.
        self.login_btn = QPushButton(text="Login", enabled=False)
        layout.addWidget(self.login_btn)

        # Add the create-user link.
        txt = QLabel(text="<a href='#'>Create new user</a>")
        layout.addWidget(txt)
        txt.setContextMenuPolicy(Qt.PreventContextMenu)

        # Connect signals and slots. This must be done after initializing all class members.
        self.select_user_combobox.currentIndexChanged.connect(self.on_selection_changed)
        self.login_btn.clicked.connect(self.on_login)
        txt.linkActivated.connect(self.on_show_create_user_dialog)

    @pyqtSlot(int, name="on_selection_changed")
    @log_exceptions
    def on_selection_changed(self, i):
        """
        Disable the login button if no username is selected, enable it otherwise.
        :param i: The current selected index in the selection combobox.
        """
        self.login_btn.setEnabled(i != 0)

    @pyqtSlot(name="on_login")
    @log_exceptions
    def on_login(self):
        """
        If something is selected in the select-user combobox, the login_successful is emitted.
        """
        if self.select_user_combobox.currentIndex() != 0:
            name = self.select_user_combobox.currentText()
            profile = self.user_profile_collection[name]
            self.login_successful.emit(name, profile)
        else:
            logging.warning("LoginScreen.on_login(): Tried to login without selecting a user.")

    @pyqtSlot(name="on_show_create_user_dialog")
    @log_exceptions
    def on_show_create_user_dialog(self):
        """
        Show the dialog to create a new user.
        """
        names = self.user_profile_collection.names()
        db_locations = self.user_profile_collection.db_locations()
        w = CreateUserDialog(names, db_locations, parent=self)
        w.setAttribute(Qt.WA_DeleteOnClose, True)
        w.accepted.connect(self.on_create_user)
        w.show()

    @pyqtSlot(dict, name="on_create_user")
    @log_exceptions
    def on_create_user(self, data):
        """
        Add the user to the profile collection.
        """
        try:
            name = data.pop("display_name")

            profile = UserProfile()
            for key, value in data.items():
                profile[key] = value

            # Add the profile to the collection.
            self.user_profile_collection[name] = profile

            # Add the new name to the combobox while keeping the alphabetical order.
            for i in range(self.select_user_combobox.count()):
                if name.lower() < self.select_user_combobox.itemText(i).lower():
                    self.select_user_combobox.insertItem(i, name)
                    break
            else:
                self.select_user_combobox.addItem(name)
            self.select_user_combobox.setCurrentText(name)

            # Save the created user.
            global_settings["users"] = self.user_profile_collection

        except (KeyError, IndexError, OSError) as ex:
            logging.warning(str(ex))