コード例 #1
0
    def change_deltagen_port(self):
        box = QMessageBox(self)
        box.setText(
            _('Port zwischen 3000-3999 angeben. '
              'Muss mit DeltaGen>Preferences>Tools>External Commands übereinstimmen.'
              ))
        box.setWindowTitle(_('DeltaGen Kommando Port'))

        port = QSpinBox(box)
        port.setMinimum(3000)
        port.setMaximum(3999)
        port.setValue(KnechtSettings.dg.get('port', DG_TCP_PORT))
        box.layout().addWidget(port,
                               box.layout().rowCount() - 1, 0, 1,
                               box.layout().columnCount())
        box.layout().addWidget(
            box.layout().takeAt(box.layout().rowCount() - 1).widget(),
            box.layout().rowCount(), 0, 1,
            box.layout().columnCount())
        box.exec_()

        if 3000 <= port.value() <= 3999:
            KnechtSettings.dg['port'] = port.value()
            box = QMessageBox(self)
            box.setText(
                _('Anwendung neu starten um geänderten Port zu übernehmen.'))
            box.setWindowTitle(_('Neustart erforderlich'))
            box.exec_()
コード例 #2
0
ファイル: Main.py プロジェクト: HSU-S21-CS232/p03-bta10
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.threadpool = QThreadPool()

        self.totalTickets = QSpinBox()
        self.totalTickets.setRange(0, 500)
        self.serviceTickets = QSpinBox()
        self.serviceTickets.setRange(0, 250)
        self.incidentTickets = QSpinBox()
        self.incidentTickets.setRange(0, 250)
        self.unassignedTickets = QSpinBox()
        self.unassignedTickets.setRange(0, 200)
        self.reasonOne = QLineEdit()
        self.reasonTwo = QLineEdit()
        self.reasonThree = QLineEdit()
        self.additionalNotes = QTextEdit()

        self.generate_btn = QPushButton("Generate PDF")
        self.generate_btn.pressed.connect(self.generate)

        layout = QFormLayout()
        layout.addRow("Number of tickets today", self.totalTickets)
        layout.addRow("Service tickets", self.serviceTickets)
        layout.addRow("Incident tickets", self.incidentTickets)
        layout.addRow("Unassigned tickets", self.unassignedTickets)
        layout.addRow("Reason for most tickets", self.reasonOne)
        layout.addRow("Second reason for most tickets", self.reasonTwo)
        layout.addRow("Third reason for most tickets", self.reasonThree)

        layout.addRow("additionalNotes", self.additionalNotes)
        layout.addRow(self.generate_btn)

        self.setLayout(layout)

    def generate(self):
        self.generate_btn.setDisabled(True)
        data = {
            'totalTickets': str(self.totalTickets.value()),
            'serviceTickets': str(self.serviceTickets.value()),
            'incidentTickets': str(self.incidentTickets.value()),
            'unassignedTickets': str(self.unassignedTickets.value()),
            'reasonOne': self.reasonOne.text(),
            'reasonTwo': self.reasonTwo.text(),
            'reasonThree': self.reasonThree.text(),
            'additionalNotes': self.additionalNotes.toPlainText()
        }
        g = Generator(data)
        g.signals.file_saved_as.connect(self.generated)
        g.signals.error.connect(print)  # Print errors to console.
        self.threadpool.start(g)

    def generated(self, outfile):
        self.generate_btn.setDisabled(False)
        try:
            os.startfile(outfile)
        except Exception:
            # If startfile not available, show dialog.
            QMessageBox.information(self, "Finished", "PDF has been generated")
コード例 #3
0
ファイル: pysignal_test.py プロジェクト: linzhun/pyside2
    class SpinBoxPySignal(UsesQApplication):
        """Tests the connection of python signals to QSpinBox qt slots."""

        def setUp(self):
            super(SpinBoxPySignal, self).setUp()
            self.obj = Dummy()
            self.spin = QSpinBox()
            self.spin.setValue(0)

        def tearDown(self):
            super(SpinBoxPySignal, self).tearDown()
            del self.obj
            del self.spin

        def testValueChanged(self):
            """Emission of a python signal to QSpinBox setValue(int)"""
            QObject.connect(self.obj, SIGNAL("dummy(int)"), self.spin, SLOT("setValue(int)"))
            self.assertEqual(self.spin.value(), 0)

            self.obj.emit(SIGNAL("dummy(int)"), 4)
            self.assertEqual(self.spin.value(), 4)

        def testValueChangedMultiple(self):
            """Multiple emissions of a python signal to QSpinBox setValue(int)"""
            QObject.connect(self.obj, SIGNAL("dummy(int)"), self.spin, SLOT("setValue(int)"))
            self.assertEqual(self.spin.value(), 0)

            self.obj.emit(SIGNAL("dummy(int)"), 4)
            self.assertEqual(self.spin.value(), 4)

            self.obj.emit(SIGNAL("dummy(int)"), 77)
            self.assertEqual(self.spin.value(), 77)
コード例 #4
0
ファイル: main.py プロジェクト: basepipe/thecarlton
 def create_new_show(self):
     w = QDialog()
     w.setWindowTitle("Create New Show")
     w.setLayout(QFormLayout())
     show_name = QLineEdit("New Show")
     w.layout().addRow(QLabel("New Show Title:"), show_name)
     prod_days = QSpinBox()
     w.layout().addRow(QLabel("Days of production:"), prod_days)
     calendar_input = QCalendarWidget()
     w.layout().addRow(QLabel("Start date:"))
     w.layout().addRow(calendar_input)
     if self.shows:  # If a show has already been created.
         previous_show = self.shows[-1]
         prod_days.setValue(previous_show.prod_days)
     accept = QPushButton("Create")
     accept.clicked.connect(w.accept)
     reject = QPushButton("Cancel")
     reject.clicked.connect(w.reject)
     w.layout().addRow(accept, reject)
     if w.exec_() == QDialog.Accepted:
         print("New show name:", show_name.text(), "Days of pre-production",
               prod_days.value())
         selected_date = calendar_input.selectedDate()
         start_date = datetime.date(selected_date.year(),
                                    selected_date.month(),
                                    selected_date.day())
         self.shows.append(
             Show(show_name.text(), prod_days.value(), start_date))
コード例 #5
0
ファイル: pysignal_test.py プロジェクト: zhoub/pyside2
    class SpinBoxPySignal(UsesQApplication):
        """Tests the connection of python signals to QSpinBox qt slots."""
        def setUp(self):
            super(SpinBoxPySignal, self).setUp()
            self.obj = Dummy()
            self.spin = QSpinBox()
            self.spin.setValue(0)

        def tearDown(self):
            super(SpinBoxPySignal, self).tearDown()
            del self.obj
            del self.spin

        def testValueChanged(self):
            """Emission of a python signal to QSpinBox setValue(int)"""
            QObject.connect(self.obj, SIGNAL('dummy(int)'), self.spin,
                            SLOT('setValue(int)'))
            self.assertEqual(self.spin.value(), 0)

            self.obj.emit(SIGNAL('dummy(int)'), 4)
            self.assertEqual(self.spin.value(), 4)

        def testValueChangedMultiple(self):
            """Multiple emissions of a python signal to QSpinBox setValue(int)"""
            QObject.connect(self.obj, SIGNAL('dummy(int)'), self.spin,
                            SLOT('setValue(int)'))
            self.assertEqual(self.spin.value(), 0)

            self.obj.emit(SIGNAL('dummy(int)'), 4)
            self.assertEqual(self.spin.value(), 4)

            self.obj.emit(SIGNAL('dummy(int)'), 77)
            self.assertEqual(self.spin.value(), 77)
コード例 #6
0
ファイル: chrono.py プロジェクト: Almazys/chrono
    def createDurationDialog(self):
        popup = QDialog(self)
        popup.setFixedSize(150, 150)
        popup.setWindowTitle("Nouvelle durée")
        layout = QVBoxLayout()

        hourLayout = QHBoxLayout()
        hourLabel = QLabel("Heures:")
        hourSpin = QSpinBox()
        hourLayout.addWidget(hourLabel)
        hourLayout.addWidget(hourSpin)

        minuteLayout = QHBoxLayout()
        minuteLabel = QLabel("Minutes:")
        minuteSpin = QSpinBox()
        minuteLayout.addWidget(minuteLabel)
        minuteLayout.addWidget(minuteSpin)

        secondLayout = QHBoxLayout()
        secondLabel = QLabel("Secondes:")
        secondSpin = QSpinBox()
        secondLayout.addWidget(secondLabel)
        secondLayout.addWidget(secondSpin)

        layout.addLayout(hourLayout)
        layout.addLayout(minuteLayout)
        layout.addLayout(secondLayout)

        button = QPushButton("Ok")
        button.clicked.connect(lambda: self.createDuration(
            popup, hourSpin.value(), minuteSpin.value(), secondSpin.value()))
        layout.addWidget(button)

        popup.setLayout(layout)
        popup.exec_()
コード例 #7
0
class StatInitDialog(QDialog):

    def __init__(self, stats):
        QDialog.__init__(self)
        self.stats = stats
        self.setWindowTitle("Initialization")
        self.setMinimumWidth(200)
        self.layout = QFormLayout()
        self.kill_spinbox = QSpinBox()
        self.death_spinbox = QSpinBox()
        self.kill_spinbox.setRange(0,1000000)
        self.death_spinbox.setRange(0,1000000)
        self.layout.addRow(QLabel("Kills"), self.kill_spinbox)
        self.layout.addRow(QLabel("Deaths"), self.death_spinbox)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        self.layout.addWidget(self.buttonBox)
        self.setLayout(self.layout)
        self.buttonBox.accepted.connect(self.ok)
        self.buttonBox.rejected.connect(self.cancel)

    def ok(self):
        kills = self.kill_spinbox.value()
        deaths = self.death_spinbox.value()
        self.stats.set_initial_stats(kills, deaths)
        self.accept()

    def cancel(self):
        print("Cancelling the stat initialization")
        self.reject()
コード例 #8
0
class ElaWidget(ToolWidget):
    def __init__(self, image, parent=None):
        super(ElaWidget, self).__init__(parent)

        params_layout = QHBoxLayout()
        params_layout.addWidget(QLabel(self.tr('Quality:')))
        self.quality_spin = QSpinBox()
        self.quality_spin.setRange(0, 100)
        self.quality_spin.setSuffix(self.tr(' %'))
        self.quality_spin.valueChanged.connect(self.process)
        params_layout.addWidget(self.quality_spin)

        params_layout.addWidget(QLabel(self.tr('Scale:')))
        self.scale_spin = QSpinBox()
        self.scale_spin.setRange(1, 100)
        self.scale_spin.valueChanged.connect(self.process)
        params_layout.addWidget(self.scale_spin)

        self.equalize_check = QCheckBox(self.tr('Equalized'))
        self.equalize_check.stateChanged.connect(self.process)
        params_layout.addWidget(self.equalize_check)

        params_layout.addStretch()
        default_button = QPushButton(self.tr('Default'))
        default_button.clicked.connect(self.default)
        params_layout.addWidget(default_button)

        self.image = image
        self.viewer = ImageViewer(self.image, self.image)
        self.default()
        self.process()

        main_layout = QVBoxLayout()
        main_layout.addLayout(params_layout)
        main_layout.addWidget(self.viewer)
        self.setLayout(main_layout)

    def process(self):
        equalize = self.equalize_check.isChecked()
        self.scale_spin.setEnabled(not equalize)
        start = time()
        quality = self.quality_spin.value()
        scale = self.scale_spin.value()
        compressed = compress_jpeg(self.image, quality)
        if not equalize:
            ela = cv.convertScaleAbs(cv.subtract(compressed, self.image), None,
                                     scale)
        else:
            ela = cv.merge([
                cv.equalizeHist(c)
                for c in cv.split(cv.absdiff(compressed, self.image))
            ])
        self.viewer.update_processed(ela)
        self.info_message.emit(
            self.tr('Error Level Analysis = {}'.format(elapsed_time(start))))

    def default(self):
        self.quality_spin.setValue(75)
        self.scale_spin.setValue(20)
コード例 #9
0
ファイル: echo.py プロジェクト: weskerfoot/sherloq
class EchoWidget(ToolWidget):
    def __init__(self, image, parent=None):
        super(EchoWidget, self).__init__(parent)

        self.radius_spin = QSpinBox()
        self.radius_spin.setRange(1, 15)
        self.radius_spin.setSuffix(self.tr(' px'))
        self.radius_spin.setValue(2)
        self.radius_spin.setToolTip(self.tr('Laplacian filter radius'))

        self.contrast_spin = QSpinBox()
        self.contrast_spin.setRange(0, 100)
        self.contrast_spin.setSuffix(self.tr(' %'))
        self.contrast_spin.setValue(85)
        self.contrast_spin.setToolTip(self.tr('Output tonality compression'))

        self.gray_check = QCheckBox(self.tr('Grayscale'))
        self.gray_check.setToolTip(self.tr('Desaturated output mode'))

        self.image = image
        self.viewer = ImageViewer(self.image, self.image, None)
        self.process()

        self.radius_spin.valueChanged.connect(self.process)
        self.contrast_spin.valueChanged.connect(self.process)
        self.gray_check.stateChanged.connect(self.process)

        params_layout = QHBoxLayout()
        params_layout.addWidget(QLabel(self.tr('Radius:')))
        params_layout.addWidget(self.radius_spin)
        params_layout.addWidget(QLabel(self.tr('Contrast:')))
        params_layout.addWidget(self.contrast_spin)
        params_layout.addWidget(self.gray_check)
        params_layout.addStretch()

        main_layout = QVBoxLayout()
        main_layout.addLayout(params_layout)
        main_layout.addWidget(self.viewer)
        self.setLayout(main_layout)

    def process(self):
        start = time()
        kernel = 2 * self.radius_spin.value() + 1
        contrast = int(self.contrast_spin.value() / 100 * 255)
        lut = create_lut(0, contrast)
        laplace = []
        for channel in cv.split(self.image):
            deriv = np.fabs(cv.Laplacian(channel, cv.CV_64F, None, kernel))
            deriv = cv.normalize(deriv, None, 0, 255, cv.NORM_MINMAX,
                                 cv.CV_8UC1)
            laplace.append(cv.LUT(deriv, lut))
        result = cv.merge(laplace)
        if self.gray_check.isChecked():
            result = bgr_to_gray3(result)
        self.viewer.update_processed(result)
        self.info_message.emit('Echo Edge Filter = {}'.format(
            elapsed_time(start)))
コード例 #10
0
class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.amtLabel = QLabel('Loan Amount')
        self.roiLabel = QLabel('Rate of Interest')
        self.yrsLabel = QLabel('No. of Years')
        self.emiLabel = QLabel('EMI per month')
        self.emiValue = QLCDNumber()
        self.emiValue.setSegmentStyle(QLCDNumber.Flat)
        self.emiValue.setFixedSize(QSize(130, 30))
        self.emiValue.setDigitCount(8)
        self.amtText = QLineEdit('10000')
        self.roiSpin = QSpinBox()
        self.roiSpin.setMinimum(1)
        self.roiSpin.setMaximum(15)
        self.yrsSpin = QSpinBox()
        self.yrsSpin.setMinimum(1)
        self.yrsSpin.setMaximum(20)
        self.roiDial = QDial()
        self.roiDial.setNotchesVisible(True)
        self.roiDial.setMaximum(15)
        self.roiDial.setMinimum(1)
        self.roiDial.setValue(1)
        self.yrsSlide = QSlider(Qt.Horizontal)
        self.yrsSlide.setMaximum(20)
        self.yrsSlide.setMinimum(1)
        self.calculateButton = QPushButton('Calculate EMI')
        self.myGridLayout = QGridLayout()
        self.myGridLayout.addWidget(self.amtLabel, 0, 0)
        self.myGridLayout.addWidget(self.roiLabel, 1, 0)
        self.myGridLayout.addWidget(self.yrsLabel, 2, 0)
        self.myGridLayout.addWidget(self.amtText, 0, 1)
        self.myGridLayout.addWidget(self.roiSpin, 1, 1)
        self.myGridLayout.addWidget(self.yrsSpin, 2, 1)
        self.myGridLayout.addWidget(self.roiDial, 1, 2)
        self.myGridLayout.addWidget(self.yrsSlide, 2, 2)
        self.myGridLayout.addWidget(self.calculateButton, 3, 1)
        self.setLayout(self.myGridLayout)
        self.setWindowTitle("A simple EMI calculator")
        self.roiDial.valueChanged.connect(self.roiSpin.setValue)
        self.connect(self.roiSpin, SIGNAL("valueChanged(int)"), self.roiDial.setValue)
        self.yrsSlide.valueChanged.connect(self.yrsSpin.setValue)
        self.connect(self.yrsSpin, SIGNAL("valueChanged(int)"),self.yrsSlide, SLOT("setValue(int)"))
        self.connect(self.calculateButton, SIGNAL("clicked()"),self.showEMI)

    def showEMI(self):
        loanAmount = float(self.amtText.text())
        rateInterest = float(float(self.roiSpin.value() / 12) / 100)
        noMonths = int(self.yrsSpin.value() * 12)
        emi = (loanAmount * rateInterest) * ((((1 + rateInterest) ** noMonths) / (((1 + rateInterest) ** noMonths) - 1)))
        self.emiValue.display(emi)
        self.myGridLayout.addWidget(self.emiLabel, 4, 0)
        self.myGridLayout.addWidget(self.emiValue, 4, 2)
コード例 #11
0
        def testSetValueIndirect(self):
            """Indirect signal emission: QSpinBox using valueChanged(int)/setValue(int)"""
            spinSend = QSpinBox()
            spinRec = QSpinBox()

            spinRec.setValue(5)

            QObject.connect(spinSend, SIGNAL('valueChanged(int)'), spinRec, SLOT('setValue(int)'))
            self.assertEqual(spinRec.value(), 5)
            spinSend.setValue(3)
            self.assertEqual(spinRec.value(), 3)
            self.assertEqual(spinSend.value(), 3)
コード例 #12
0
ファイル: panels.py プロジェクト: rholson1/peyecoder
class Code(QWidget):
    TRIAL_STATUS = ('on', 'off')

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

        self.callback = callback

        trial_label = QLabel('Trial:')
        self.trial_box = QSpinBox()
        self.trial_box.setFixedWidth(64)
        self.trial_box.setValue(1)
        #self.trial_box.setFocusPolicy(Qt.NoFocus)

        trial_status_label = QLabel('Trial Status:')
        self.trial_status = QComboBox()
        self.trial_status.addItems(self.TRIAL_STATUS)
        self.trial_status.setFocusPolicy(Qt.NoFocus)

        response_label = QLabel('Response:')
        self.response_box = QComboBox()
        self.response_box.setFocusPolicy(Qt.NoFocus)

        self.record_button = QPushButton('Record Event')
        self.record_button.clicked.connect(self.record_event)
        self.record_button.setEnabled(False)
        self.record_button.setFocusPolicy(Qt.NoFocus)

        layout = QHBoxLayout()
        layout.addWidget(trial_label)
        layout.addWidget(self.trial_box)
        layout.addWidget(trial_status_label)
        layout.addWidget(self.trial_status)
        layout.addWidget(response_label)
        layout.addWidget(self.response_box)
        layout.addStretch()
        layout.addWidget(self.record_button)

        self.setLayout(layout)

    def set_responses(self, responses):
        self.response_box.clear()
        self.response_box.addItems(responses)

    def record_event(self):
        event = Event(trial=self.trial_box.value(),
                      status=self.trial_status.currentText() == 'on',
                      response=self.response_box.currentText())
        if self.trial_status.currentText() == 'off':
            self.trial_box.setValue(self.trial_box.value() + 1)
            self.trial_status.setCurrentText('on')
        self.callback(event)
コード例 #13
0
class RelayCloneDialog(QDialog):
    def __init__(self):
        super().__init__(GlobalAccess().get_main_window())

        self.setWindowTitle(_('Clone relay legs'))
        self.setWindowIcon(QIcon(config.ICON))
        self.setSizeGripEnabled(False)
        self.setModal(True)
        self.layout = QFormLayout(self)

        self.min_bib = QSpinBox()
        self.min_bib.setMaximum(10000000)
        self.min_bib.setValue(1001)
        self.layout.addRow(QLabel(_('Minimal bib')), self.min_bib)

        self.max_bib = QSpinBox()
        self.max_bib.setMaximum(10000000)
        self.max_bib.setValue(2999)
        self.layout.addRow(QLabel(_('Maximal bib')), self.max_bib)

        self.increment = QSpinBox()
        self.increment.setMaximum(10000000)
        self.increment.setValue(2000)
        self.layout.addRow(QLabel(_('Increment')), self.increment)

        def cancel_changes():
            self.close()

        def apply_changes():
            try:
                self.apply_changes_impl()
            except Exception as e:
                logging.error(str(e))
                logging.exception(e)
            self.close()

        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_ok = button_box.button(QDialogButtonBox.Ok)
        self.button_ok.setText(_('OK'))
        self.button_ok.clicked.connect(apply_changes)
        self.button_cancel = button_box.button(QDialogButtonBox.Cancel)
        self.button_cancel.setText(_('Cancel'))
        self.button_cancel.clicked.connect(cancel_changes)
        self.layout.addRow(button_box)

        self.show()

    def apply_changes_impl(self):
        min_bib = self.min_bib.value()
        max_bib = self.max_bib.value()
        increment = self.increment.value()
        clone_relay_legs(min_bib, max_bib, increment)
コード例 #14
0
        def testSetValueIndirect(self):
            """Indirect signal emission: QSpinBox using valueChanged(int)/setValue(int)"""
            spinSend = QSpinBox()
            spinRec = QSpinBox()

            spinRec.setValue(5)

            QObject.connect(spinSend, SIGNAL('valueChanged(int)'), spinRec,
                            SLOT('setValue(int)'))
            self.assertEqual(spinRec.value(), 5)
            spinSend.setValue(3)
            self.assertEqual(spinRec.value(), 3)
            self.assertEqual(spinSend.value(), 3)
コード例 #15
0
ファイル: coordinate_widget.py プロジェクト: thane98/paragon
class CoordinateWidget(QWidget, PropertyWidget):
    position_changed = Signal(int, int)

    def __init__(self, target_property_name):
        QWidget.__init__(self)
        PropertyWidget.__init__(self, target_property_name)
        self.layout = QHBoxLayout()
        self.x_spinbox = QSpinBox()
        self.y_spinbox = QSpinBox()
        self.x_spinbox.setRange(-128, 127)
        self.y_spinbox.setRange(-128, 127)
        self.x_spinbox.setFixedWidth(60)
        self.y_spinbox.setFixedWidth(60)
        self.layout.addWidget(self.x_spinbox)
        self.layout.addWidget(self.y_spinbox)
        self.layout.setAlignment(QtGui.Qt.AlignLeft)
        self.setLayout(self.layout)
        self.x_spinbox.valueChanged.connect(lambda v: self._on_edit(v, 0))
        self.y_spinbox.valueChanged.connect(lambda v: self._on_edit(v, 1))
        self.is_disable_write_back = False

    def _on_edit(self, value, index):
        if self.target:
            buffer = self.target[self.target_property_name].value
            if buffer[index] != value:
                if not self.is_disable_write_back:
                    buffer[index] = self._signed_to_unsigned(value)
                self.position_changed.emit(self.x_spinbox.value(),
                                           self.y_spinbox.value())

    def _on_target_changed(self):
        if self.target:
            buffer = self.target[self.target_property_name].value
            self.x_spinbox.setValue(self._unsigned_to_signed(buffer[0]))
            self.y_spinbox.setValue(self._unsigned_to_signed(buffer[1]))
        else:
            self.x_spinbox.setValue(0)
            self.y_spinbox.setValue(0)

    @staticmethod
    def _unsigned_to_signed(value):
        packed = ctypes.c_byte(value)
        return packed.value

    @staticmethod
    def _signed_to_unsigned(value):
        packed = ctypes.c_ubyte(value)
        return packed.value

    def set_disable_write_back(self, is_disabled: bool):
        self.is_disable_write_back = is_disabled
コード例 #16
0
class ToggleButton:
    def __init__(self, frame_text: str, checkbox_text: str = 'Default'):
        self.box = QVBoxLayout()
        self.lbl = QLabel(frame_text)

        self.checkbox = QCheckBox(checkbox_text)
        self.checkbox.setCheckState(Qt.Unchecked)

        self.numeric = QSpinBox()
        self.numeric.setValue(-1)

        self.box.addWidget(self.lbl)
        self.box.addWidget(self.numeric)
        self.box.addWidget(self.checkbox)

        self.checkbox.stateChanged.connect(self.checkbox_toggle)
        self.numeric.valueChanged.connect(self.numeric_change)

        self.use_default = False
        self.value = -1

    @Slot()
    def checkbox_toggle(self, checked):
        self.use_default = self.checkbox.checkState() == Qt.Checked
        self.numeric.setDisabled(self.use_default)

    @Slot()
    def numeric_change(self, checked):
        self.value = self.numeric.value()
コード例 #17
0
class SpinBoxAction(QWidget):
    def __init__(self,
                 parent=None,
                 text: str = "",
                 min: int = 0,
                 max: int = 10,
                 val: int = 5):
        super().__init__(parent=parent)
        self.setLayout(QtWidgets.QHBoxLayout(self))
        self.label = QLabel(text)
        self.layout().addWidget(self.label)
        self.layout().setMargin(1)
        self.combo = QSpinBox(self)
        self.layout().addWidget(self.combo)
        self.setRange(min, max)
        self.combo.setValue(val)

    def setText(self, text: str) -> None:
        self.label.setText(text)

    def setRange(self, min: int, max: int) -> None:
        self.combo.setMinimum(min)
        self.combo.setMaximum(max)

    def getSelectedItem(self) -> int:
        return self.combo.value()
コード例 #18
0
    class Config(SignalNode.Config):
        """Config widget displayed for ArtificialDelay."""
        def __init__(self, parent=None):
            super().__init__(parent=parent)

            self.delay = QSpinBox()
            self.delay.setSuffix(" ms")
            self.delay.setMinimum(0)
            self.delay.setMaximum(1000000)
            self.delay.valueChanged.connect(self.updateModel)

            layout = QFormLayout()
            self.setLayout(layout)

            layout.addRow("Delay:", self.delay)

        def updateModel(self):
            n = self.node()
            if n is None:
                return

            n.setDelay(self.delay.value())

        def updateView(self):
            n = self.node()
            if n is None:
                return

            self.delay.blockSignals(True)
            self.delay.setValue(n.delay())
            self.delay.blockSignals(False)
コード例 #19
0
class LabeledSpinBox(QWidget):
    valueChanged = Signal(int)

    def __init__(self, label_string, minimum=1, maximum=100, starting_value=0):
        super(LabeledSpinBox, self).__init__()
        self.spinbox = QSpinBox()
        self.spinbox.setRange(minimum, maximum)
        self.spinbox.setSuffix('/{}'.format(maximum))
        self.spinbox.setValue(starting_value)
        self.spinbox.valueChanged.connect(self._valueChanged)
        self.label = QLabel()
        self.label.setText(label_string)

        SpinBoxLayout = QHBoxLayout(self)
        SpinBoxLayout.addWidget(self.label)
        SpinBoxLayout.addWidget(self.spinbox)

    def setValue(self, value, quiet=False):
        if quiet:
            self.spinbox.blockSignals(True)
            self.spinbox.setValue(value)
            self.spinbox.blockSignals(False)
        else:
            self.spinbox.setValue(value)

    def value(self):
        return self.spinbox.value()

    def setRange(self, minimum, maximum):
        self.spinbox.setRange(minimum, maximum)
        self.spinbox.setSuffix("/{}".format(maximum))

    def _valueChanged(self, value):
        self.valueChanged.emit(value)
コード例 #20
0
ファイル: change_channel.py プロジェクト: ruthearagard/tivopy
class ChangeChannel(QDialog):
    change_channel = Signal(int, bool)
    """Allows the user to change the channel."""
    def __init__(self):
        super(ChangeChannel, self).__init__()

        self.setModal(True)

        self.stop_recording = QCheckBox(self)
        self.channel = QSpinBox(self)

        self.channel.setRange(0, 9999)

        self.button_boxes = QDialogButtonBox(QDialogButtonBox.Ok
                                             | QDialogButtonBox.Cancel)

        self.button_boxes.accepted.connect(self.accepted)
        self.button_boxes.rejected.connect(lambda: self.close())

        self.layout = QFormLayout(self)
        self.layout.addRow("Channel:", self.channel)
        self.layout.addRow("Stop recording if in progress:",
                           self.stop_recording)
        self.layout.addRow(self.button_boxes)

        self.setWindowTitle("Change TiVo channel")
        self.resize(320, 100)

    @Slot()
    def accepted(self):
        self.change_channel.emit(self.channel.value(),
                                 self.stop_recording.isChecked())
        self.close()
コード例 #21
0
class ValueEdit(QWidget):
    def __init__(self, title, unit, number_type='double', parent=None):
        super(ValueEdit, self).__init__(parent)
        self.title = QLabel(title)
        self.title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.unit = QLabel(unit)
        self.unit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        if number_type == 'double':
            self.edit = QDoubleSpinBox()
        elif number_type == 'int':
            self.edit = QSpinBox()
        else:
            raise ValueError(
                'Editor can either be for double or integer values')

        self.edit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.edit.setKeyboardTracking(False)
        self.edit.setAlignment(Qt.AlignRight)
        self.edit.setButtonSymbols(QAbstractSpinBox.NoButtons)

    def set_range_decimals(self, min, max, decimals=3):
        self.edit.setRange(min, max)
        if isinstance(self.edit, QDoubleSpinBox):
            self.edit.setDecimals(decimals)

    def set_single_step_size(self, step=.1):
        self.edit.setSingleStep(step)

    def value(self):
        return self.edit.value()

    @Slot(float)
    def setValue(self, value):
        self.edit.setValue(value)
コード例 #22
0
ファイル: utility.py プロジェクト: Vidocapt/sherloq
class ParamSlider(QWidget):
    valueChanged = Signal(int)

    def __init__(self,
                 interval,
                 ticks=10,
                 reset=0,
                 suffix=None,
                 label=None,
                 bold=False,
                 parent=None):
        super(ParamSlider, self).__init__(parent)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(interval[0], interval[1])
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval((interval[1] - interval[0] + 1) / ticks)
        self.slider.setSingleStep(1)
        self.slider.setPageStep(1)
        self.slider.setValue(reset)
        self.slider.mouseDoubleClickEvent = self.doubleClicked

        self.spin = QSpinBox()
        self.spin.setRange(interval[0], interval[1])
        self.spin.setValue(reset)
        self.spin.setSuffix(suffix)
        self.spin.setFixedWidth(50)

        self.reset = reset
        self.slider.valueChanged.connect(self.spin.setValue)
        self.spin.valueChanged.connect(self.slider.setValue)
        self.slider.valueChanged.connect(self.valueChanged)

        layout = QHBoxLayout()
        if label is not None:
            lab = QLabel(label)
            modify_font(lab, bold=bold)
            layout.addWidget(lab)
        layout.addWidget(self.slider)
        layout.addWidget(self.spin)
        self.setLayout(layout)
        self.setMaximumWidth(200)

    def doubleClicked(self, _):
        self.slider.setValue(self.reset)
        self.spin.setValue(self.reset)

    def value(self):
        return self.slider.value()

    def setValue(self, value):
        self.spin.setValue(value)
        self.slider.setValue(value)
        self.valueChanged.emit(value)

    def sync(self):
        self.spin.setValue(self.slider.value())
        self.slider.setValue(self.spin.value())
        self.valueChanged.emit(self.slider.value())
コード例 #23
0
 def disable_or_enable_distance_field(count_spin_box: QSpinBox,
                                      distance_spin_box: QDoubleSpinBox):
     """
     Disables or enabled the matching distance field of the row/column count spin box in the pixel grid options
     depending on if the number of rows/columns has been set to zero.
     :param count_spin_box: The row/column count spin box.
     :param distance_spin_box: The matching row height/column width spin box.
     """
     distance_spin_box.setEnabled(count_spin_box.value() != 0)
コード例 #24
0
class QFlightSlotEditor(QGroupBox):
    def __init__(self, package_model: PackageModel, flight: Flight,
                 game: Game):
        super().__init__("Slots")
        self.package_model = package_model
        self.flight = flight
        self.game = game
        self.inventory = self.game.aircraft_inventory.for_control_point(
            flight.from_cp)
        available = self.inventory.available(self.flight.unit_type)
        max_count = self.flight.count + available
        if max_count > 4:
            max_count = 4

        layout = QGridLayout()

        self.aircraft_count = QLabel("Aircraft count:")
        self.aircraft_count_spinner = QSpinBox()
        self.aircraft_count_spinner.setMinimum(1)
        self.aircraft_count_spinner.setMaximum(max_count)
        self.aircraft_count_spinner.setValue(flight.count)
        self.aircraft_count_spinner.valueChanged.connect(
            self._changed_aircraft_count)

        layout.addWidget(self.aircraft_count, 0, 0)
        layout.addWidget(self.aircraft_count_spinner, 0, 1)

        layout.addWidget(QLabel("Squadron:"), 1, 0)
        layout.addWidget(QLabel(str(self.flight.squadron)), 1, 1)

        layout.addWidget(QLabel("Assigned pilots:"), 2, 0)
        self.roster_editor = FlightRosterEditor(flight.roster)
        layout.addLayout(self.roster_editor, 2, 1)

        self.setLayout(layout)

    def _changed_aircraft_count(self):
        old_count = self.flight.count
        new_count = int(self.aircraft_count_spinner.value())
        self.game.aircraft_inventory.return_from_flight(self.flight)
        self.flight.resize(new_count)
        try:
            self.game.aircraft_inventory.claim_for_flight(self.flight)
        except ValueError:
            # The UI should have prevented this, but if we ran out of aircraft
            # then roll back the inventory change.
            difference = new_count - self.flight.count
            available = self.inventory.available(self.flight.unit_type)
            logging.error(
                f"Could not add {difference} additional aircraft to "
                f"{self.flight} because {self.flight.departure} has only "
                f"{available} {self.flight.unit_type} remaining")
            self.game.aircraft_inventory.claim_for_flight(self.flight)
            self.flight.resize(old_count)
            return
        self.roster_editor.resize(new_count)
コード例 #25
0
ファイル: settings.py プロジェクト: sportorg/pysport
class MainTab(Tab):
    def __init__(self, parent):
        self.widget = QWidget()
        self.layout = QFormLayout(parent)

        self.label_lang = QLabel(_('Languages'))
        self.item_lang = AdvComboBox()
        self.item_lang.addItems(get_languages())
        self.item_lang.setCurrentText(Config().configuration.get(
            'current_locale', 'ru_RU'))
        self.layout.addRow(self.label_lang, self.item_lang)

        self.item_auto_save = QSpinBox()
        self.item_auto_save.setMaximum(3600 * 24)
        self.item_auto_save.setValue(
            Config().configuration.get('autosave_interval'))
        self.layout.addRow(_('Auto save') + ' (sec)', self.item_auto_save)

        self.item_show_toolbar = QCheckBox(_('Show toolbar'))
        self.item_show_toolbar.setChecked(
            Config().configuration.get('show_toolbar'))
        self.layout.addRow(self.item_show_toolbar)

        self.item_open_recent_file = QCheckBox(_('Open recent file'))
        self.item_open_recent_file.setChecked(
            Config().configuration.get('open_recent_file'))
        self.layout.addRow(self.item_open_recent_file)

        self.item_use_birthday = QCheckBox(_('Use birthday'))
        self.item_use_birthday.setChecked(
            Config().configuration.get('use_birthday'))
        self.layout.addRow(self.item_use_birthday)

        self.item_check_updates = QCheckBox(_('Check updates'))
        self.item_check_updates.setChecked(
            Config().configuration.get('check_updates'))
        # self.layout.addRow(self.item_check_updates)

        self.widget.setLayout(self.layout)

    def save(self):
        Config().configuration.set('current_locale',
                                   self.item_lang.currentText())
        Config().configuration.set('autosave_interval',
                                   self.item_auto_save.value())
        Config().configuration.set('show_toolbar',
                                   self.item_show_toolbar.isChecked())
        Config().configuration.set('open_recent_file',
                                   self.item_open_recent_file.isChecked())
        Config().configuration.set('use_birthday',
                                   self.item_use_birthday.isChecked())
        Config().configuration.set('check_updates',
                                   self.item_check_updates.isChecked())
コード例 #26
0
ファイル: main.py プロジェクト: basepipe/thecarlton
 def add_position(self):
     w = QDialog()
     w.setWindowTitle("Create New Position")
     w.setLayout(QFormLayout())
     pos_name = QLineEdit("New Position")
     w.layout().addRow(QLabel("Position Name:"), pos_name)
     pre_pro_days = QSpinBox()
     post_pro_days = QSpinBox()
     w.layout().addRow(QLabel("Days of pre-production:"), pre_pro_days)
     w.layout().addRow(QLabel("Days of immediate post-production:"),
                       post_pro_days)
     accept = QPushButton("Create")
     accept.clicked.connect(w.accept)
     reject = QPushButton("Cancel")
     reject.clicked.connect(w.reject)
     w.layout().addRow(accept, reject)
     if w.exec_() == QDialog.Accepted:
         print("Days of pre-production", pre_pro_days.value(),
               "Days of post-productions", post_pro_days.value())
         new_pos_item = QListWidgetItem(pos_name.text())
         new_pos_item.setFlags(new_pos_item.flags() | Qt.ItemIsEditable)
         self.pos_list_widget.addItem(new_pos_item)
コード例 #27
0
class RelayNumberDialog(QDialog):
    def __init__(self):
        super().__init__(GlobalAccess().get_main_window())

    def exec_(self):
        self.init_ui()
        return super().exec_()

    def init_ui(self):
        self.setWindowTitle(_('Relay number'))
        self.setWindowIcon(QIcon(config.ICON))
        self.setSizeGripEnabled(False)
        self.setModal(True)
        self.layout = QFormLayout(self)

        self.number_label = QLabel(_('First relay number'))
        self.number_item = QSpinBox()
        self.number_item.setMinimum(1001)
        self.number_item.setMaximum(9999)

        next_number = get_next_relay_number_protocol()
        self.number_item.setValue(next_number)

        self.layout.addRow(self.number_label, self.number_item)

        def cancel_changes():
            self.close()

        def apply_changes():
            try:
                self.apply_changes_impl()
            except Exception as e:
                logging.error(str(e))
            self.close()

        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel)
        self.button_ok = button_box.button(QDialogButtonBox.Ok)
        self.button_ok.setText(_('OK'))
        self.button_ok.clicked.connect(apply_changes)
        self.button_cancel = button_box.button(QDialogButtonBox.Cancel)
        self.button_cancel.setText(_('Cancel'))
        self.button_cancel.clicked.connect(cancel_changes)
        self.layout.addRow(button_box)

        self.show()

    def apply_changes_impl(self):
        set_next_relay_number(self.number_item.value())
コード例 #28
0
def test_GIVEN_advanced_option_in_field_WHEN_filling_in_advanced_options_THEN_spinbox_is_created(
        qtbot, file):
    group = file.create_group("group")
    field_name = "test"

    advanced_options = [field_name]
    spinner = QSpinBox()

    items = {advanced_options[0]: spinner}.items()
    value = 4

    group.create_dataset(name=field_name, data=value)

    fill_in_advanced_options(items, group)

    assert spinner.value() == value
コード例 #29
0
class NewIntegerSequenceDateTimeConvertSpecDialog(QDialog):
    def __init__(self, *args, **kwargs):
        super(NewIntegerSequenceDateTimeConvertSpecDialog,
              self).__init__(*args, **kwargs)

        self.setWindowTitle("New integer sequence datetime")

        QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel

        self.buttonBox = QDialogButtonBox(QBtn)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.datetime = QDateTimeEdit()
        self.start_integer = QSpinBox()
        self.duration = QLineEdit("1h")
        self.duration.textChanged.connect(self._validate)

        self.layout = QVBoxLayout()
        self.form = QFormLayout()
        self.form.addRow("Initial datetime", self.datetime)
        self.form.addRow("Initial integer", self.start_integer)
        self.form.addRow("Timestep duration", self.duration)
        self.layout.addLayout(self.form)
        self.layout.addWidget(self.buttonBox)
        self.setLayout(self.layout)

        self._validate()

    def _validate(self):
        try:
            Duration(self.duration.text())
        except ParameterValueFormatError:
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
            return
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)

    def get_spec(self):
        start_datetime = DateTime(self.datetime.dateTime().toString(
            Qt.ISODate))
        duration = Duration(self.duration.text())
        start_int = self.start_integer.value()
        return IntegerSequenceDateTimeConvertSpec(start_datetime, start_int,
                                                  duration)
コード例 #30
0
class VDlgEditCounter(VDialogEdit):
    def __init__(self, parent, current_val):
        """
        Counter editor

        :param parent: gui's main window
        :param current_val: current field actual value (to set by default)
        """
        VDialogEdit.__init__(self, parent, current_val)

        self.spin_box = QSpinBox()
        self.spin_box.setMinimum(-10)
        if current_val:
            self.spin_box.setValue(int(current_val))

        self.main_layout.addWidget(self.spin_box, 0, 0, 1, 2)

    def new_value(self):
        return self.spin_box.value()
コード例 #31
0
class WindowGroup(AbstractProcessGroup):
    def __init__(self, title, fs):
        AbstractProcessGroup.__init__(self, title, fs)
        self.setupWindowLayout()

    def setupWindowLayout(self):
        winLayout = QHBoxLayout(self)
        wiinSettLayout = QFormLayout()
        winLayout.addLayout(wiinSettLayout)
        self.winLenEdit = QSpinBox()
        self.winLenEdit.setMaximum(10000)  #do poprawki
        self.winLenEdit.setValue(self.fs / 10)
        wiinSettLayout.addRow('Lenght (samples)', self.winLenEdit)


##        self.winOverEdit = QSpinBox()
##        self.winOverEdit.setMaximum(10000)
##        wiinSettLayout.addRow('Overlapping (samples)', self.winOverEdit)
##        self.winBackOverEdit = QSpinBox()
##        self.winBackOverEdit.setMaximum(10000)
##        wiinSettLayout.addRow('Back Overlapping (samples)', self.winBackOverEdit)

    def process(self, inData):
        self.winLen = self.winLenEdit.value()
        ##        winOver = self.winOverEdit.value()
        segNmbr = int(np.shape(inData)[1] / (self.winLen))
        progStep = 100.0 / len(inData)
        prog = 0

        outData = np.copy(inData)
        outData = [np.array_split(ch, segNmbr) for ch in outData]
        chi = 0
        for ch in outData:
            for seg in ch:
                proc = self.operation(seg)
                seg.fill(proc)
            prog = prog + progStep
            self.progress.emit(int(prog))
            chi += 1

        outData = [np.concatenate(ch) for ch in outData]
        return outData
コード例 #32
0
class EditSlider(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(0, 0, 0, 0)
        hlayout.setSpacing(2)

        self.edit = QSpinBox()
        self.edit.setMinimumWidth(40)
        self.edit.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.slider = QSlider(Qt.Horizontal)

        hlayout.addWidget(self.edit)
        hlayout.addWidget(self.slider)

        self.setLayout(hlayout)

        self.slider.valueChanged.connect(self.setValue)
        self.edit.valueChanged.connect(self.setValue)

    def setRange(self, min_val, max_val):
        self.edit.setRange(min_val, max_val)
        self.slider.setRange(min_val, max_val)

    def value(self) -> int:
        return self.edit.value()

    def setValue(self, value: int):

        if self.sender() != self.slider and self.sender() != self.edit:
            self.edit.setValue(value)
            self.slider.setValue(value)
            return

        if self.sender() == self.slider:
            self.edit.setValue(value)

        if self.sender() == self.edit:
            self.slider.setValue(value)
コード例 #33
0
        def testSetValue(self):
            """Direct signal emission: QSpinBox using valueChanged(int)/setValue(int)"""
            spinSend = QSpinBox()
            spinRec = QSpinBox()

            spinRec.setValue(5)
            spinSend.setValue(42)

            QObject.connect(spinSend, SIGNAL('valueChanged(int)'), spinRec, SLOT('setValue(int)'))
            self.assertEqual(spinRec.value(), 5)
            self.assertEqual(spinSend.value(), 42)
            spinSend.emit(SIGNAL('valueChanged(int)'), 3)

            self.assertEqual(spinRec.value(), 3)
            #Direct emission shouldn't change the value of the emitter
            self.assertEqual(spinSend.value(), 42)

            spinSend.emit(SIGNAL('valueChanged(int)'), 66)
            self.assertEqual(spinRec.value(), 66)
            self.assertEqual(spinSend.value(), 42)
コード例 #34
0
ファイル: MainWindow.py プロジェクト: goph-R/TilePad
class MainWindow(QMainWindow):

    def __init__(self, app, parent=None):
        super(MainWindow, self).__init__(parent)
        self.imagesDir = app.dir + '/images/'
        self.setWindowIcon(QIcon(self.imagesDir + 'icon.png'))
        self.path = ''

        self.settings = QSettings()
        self.lastDir = self.settings.value('lastDir', '')

        self.setMinimumWidth(540)

        self.supportedFormats = []
        for f in QImageReader.supportedImageFormats():
            self.supportedFormats.append(str(f.data(), encoding="utf-8"))

        self.fileWatcher = QFileSystemWatcher()
        self.fileWatcher.fileChanged.connect(self.fileChanged)

        # widgets
        self.showPixmapWidget = None

        self.tileWidthSpinBox = QSpinBox()
        self.tileWidthSpinBox.setValue(16)
        self.tileWidthSpinBox.setFixedWidth(50)
        self.tileWidthSpinBox.setMinimum(1)

        self.tileHeightSpinBox = QSpinBox()
        self.tileHeightSpinBox.setValue(16)
        self.tileHeightSpinBox.setFixedWidth(50)
        self.tileHeightSpinBox.setMinimum(1)

        self.paddingSpinBox = QSpinBox()
        self.paddingSpinBox.setFixedWidth(50)
        self.paddingSpinBox.setMinimum(1)

        self.transparentCheckbox = QCheckBox("Transparent")
        self.transparentCheckbox.setChecked(True)
        self.transparentCheckbox.stateChanged.connect(self.transparentChanged)

        self.backgroundColorEdit = ColorEdit()
        self.backgroundColorEdit.setEnabled(False)
        self.backgroundColorLabel = QLabel("Background color:")
        self.backgroundColorLabel.setEnabled(False)

        self.forcePotCheckBox = QCheckBox("Force PoT")
        self.forcePotCheckBox.setChecked(True)
        self.forcePotCheckBox.stateChanged.connect(self.forcePotChanged)

        self.reorderTilesCheckBox = QCheckBox("Reorder tiles")

        self.generateAndExportButton = QPushButton("Generate and export")
        self.generateAndExportButton.setFixedHeight(32)
        self.generateAndExportButton.clicked.connect(self.generateAndExportClicked)
        self.generateAndExportButton.setEnabled(False)

        self.pixmapWidget = PixmapWidget()
        self.pixmapWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.pixmapWidget.setPixmap(self.createDropTextPixmap())
        self.pixmapWidget.dropSignal.connect(self.fileDropped)
        self.pixmapWidget.setMinimumHeight(300)

        # load settings
        self.tileWidthSpinBox.setValue(int(self.settings.value('tileWidth', 16)))
        self.tileHeightSpinBox.setValue(int(self.settings.value('tileHeight', 16)))
        self.paddingSpinBox.setValue(int(self.settings.value('padding', 1)))
        self.forcePotCheckBox.setChecked(True if self.settings.value('forcePot', 'true') == 'true' else False)
        self.reorderTilesCheckBox.setChecked(True if self.settings.value('reorderTiles', 'false') == 'true' else False)
        self.transparentCheckbox.setChecked(True if self.settings.value('transparent', 'false') == 'true' else False)
        self.backgroundColorEdit.setColorText(str(self.settings.value('backgroundColor', '#FF00FF')))
        self.restoreGeometry(QByteArray(self.settings.value('MainWindow/geometry')))
        self.restoreState(QByteArray(self.settings.value('MainWindow/windowState')))

        # layout
        hl1 = QHBoxLayout()
        hl1.setContentsMargins(5, 5, 5, 5)
        hl1.addWidget(QLabel("Tile width:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileWidthSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Tile height:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileHeightSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Padding:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.paddingSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.forcePotCheckBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.reorderTilesCheckBox)
        hl1.addStretch()

        hl2 = QHBoxLayout()
        hl2.setContentsMargins(5, 5, 5, 5)
        hl2.addWidget(self.transparentCheckbox)
        hl2.addSpacing(15)
        hl2.addWidget(self.backgroundColorLabel)
        hl2.addSpacing(5)
        hl2.addWidget(self.backgroundColorEdit)
        hl2.addStretch()

        hl3 = QHBoxLayout()
        hl3.setContentsMargins(5, 5, 5, 5)
        hl3.addWidget(self.generateAndExportButton)

        vl = QVBoxLayout()
        vl.setContentsMargins(0, 0, 0, 0)
        vl.setSpacing(0)
        vl.addLayout(hl1)
        vl.addLayout(hl2)
        vl.addWidget(self.pixmapWidget)
        vl.addLayout(hl3)

        w = QWidget()
        w.setLayout(vl)
        self.setCentralWidget(w)

        self.setTitle()

    def setTitle(self):
        p = ' - ' + os.path.basename(self.path) if self.path else ''
        self.setWindowTitle(QCoreApplication.applicationName() + ' ' + QCoreApplication.applicationVersion() + p)

    def createDropTextPixmap(self):
        pixmap = QPixmap(481, 300)
        pixmap.fill(QColor("#333333"))
        painter = QPainter(pixmap)
        font = QFont("Arial")
        font.setPixelSize(28)
        font.setBold(True)
        fm = QFontMetrics(font)
        painter.setFont(font)
        painter.setPen(QPen(QColor("#888888"), 1))
        text = "Drop the tileset image here"
        x = (pixmap.width()-fm.width(text))/2
        y = (pixmap.height()+fm.height())/2
        painter.drawText(x, y, text)
        del painter
        return pixmap

    def fileDropped(self, path):
        path = str(path)
        name, ext = os.path.splitext(path)
        ext = ext[1:]
        if not ext in self.supportedFormats:
            QMessageBox.warning(self, "Warning", "The dropped file is not supported")
            return
        pixmap = QPixmap(path)
        if pixmap.isNull():
            QMessageBox.warning(self, "Warning", "Can't load the image")
            return
        if self.path:
            self.fileWatcher.removePath(self.path)
        self.path = path
        self.fileWatcher.addPath(self.path)
        self.pixmapWidget.setPixmap(pixmap)
        self.generateAndExportButton.setEnabled(True)
        self.setTitle()
        self.activateWindow()

    def fileChanged(self, path):
        #self.fileDropped(path)
        pass

    def transparentChanged(self):
        e = self.transparentCheckbox.isChecked()
        self.backgroundColorEdit.setEnabled(not e)
        self.backgroundColorLabel.setEnabled(not e)

    def forcePotChanged(self):
        e = self.forcePotCheckBox.isChecked()
        self.reorderTilesCheckBox.setEnabled(e)

    def generateAndExportClicked(self):

        g = Generator()
        g.tileWidth = self.tileWidthSpinBox.value()
        g.tileHeight = self.tileHeightSpinBox.value()
        g.forcePot = self.forcePotCheckBox.isChecked()
        g.isTransparent = self.transparentCheckbox.isChecked()
        g.bgColor = self.backgroundColorEdit.getColor()
        g.reorder = self.reorderTilesCheckBox.isChecked()
        g.padding = self.paddingSpinBox.value()

        target = g.create(self.pixmapWidget.pixmap);

        # export
        self.lastDir = os.path.dirname(self.path)
        targetPath = QFileDialog.getSaveFileName(self, 'Export', self.lastDir, 'PNG (*.png)')
        if targetPath:
            target.save(targetPath[0])
            showPixmap = QPixmap.fromImage(target)
            if self.showPixmapWidget:
                self.showPixmapWidget.deleteLater()
                del self.showPixmapWidget
            self.showPixmapWidget = PixmapWidget()
            self.showPixmapWidget.setWindowIcon(self.windowIcon())
            self.showPixmapWidget.setWindowTitle(os.path.basename(targetPath[0]))
            self.showPixmapWidget.resize(showPixmap.width(), showPixmap.height())
            self.showPixmapWidget.setPixmap(showPixmap)
            self.showPixmapWidget.show()

    def closeEvent(self, event):
        if self.showPixmapWidget:
            self.showPixmapWidget.close()

        # save settings
        self.settings.setValue('tileWidth', self.tileWidthSpinBox.value())
        self.settings.setValue('tileHeight', self.tileHeightSpinBox.value())
        self.settings.setValue('padding', self.paddingSpinBox.value())
        self.settings.setValue('forcePot', self.forcePotCheckBox.isChecked())
        self.settings.setValue('reorderTiles', self.reorderTilesCheckBox.isChecked())
        self.settings.setValue('transparent', self.transparentCheckbox.isChecked())
        self.settings.setValue('backgroundColor', self.backgroundColorEdit.getColor().name())
        self.settings.setValue('lastDir', self.lastDir)
        self.settings.setValue('MainWindow/geometry', self.saveGeometry())
        self.settings.setValue('MainWindow/windowState', self.saveState())

        super(MainWindow, self).closeEvent(event)
コード例 #35
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.renderArea = RenderArea()

        self.shapeComboBox = QComboBox()
        self.shapeComboBox.addItem("Polygon", RenderArea.Polygon)
        self.shapeComboBox.addItem("Rectangle", RenderArea.Rect)
        self.shapeComboBox.addItem("Rounded Rectangle", RenderArea.RoundedRect)
        self.shapeComboBox.addItem("Ellipse", RenderArea.Ellipse)
        self.shapeComboBox.addItem("Pie", RenderArea.Pie)
        self.shapeComboBox.addItem("Chord", RenderArea.Chord)
        self.shapeComboBox.addItem("Path", RenderArea.Path)
        self.shapeComboBox.addItem("Line", RenderArea.Line)
        self.shapeComboBox.addItem("Polyline", RenderArea.Polyline)
        self.shapeComboBox.addItem("Arc", RenderArea.Arc)
        self.shapeComboBox.addItem("Points", RenderArea.Points)
        self.shapeComboBox.addItem("Text", RenderArea.Text)
        self.shapeComboBox.addItem("Pixmap", RenderArea.Pixmap)

        shapeLabel = QLabel("&Shape:")
        shapeLabel.setBuddy(self.shapeComboBox)

        self.penWidthSpinBox = QSpinBox()
        self.penWidthSpinBox.setRange(0, 20)
        self.penWidthSpinBox.setSpecialValueText("0 (cosmetic pen)")

        penWidthLabel = QLabel("Pen &Width:")
        penWidthLabel.setBuddy(self.penWidthSpinBox)

        self.penStyleComboBox = QComboBox()
        self.penStyleComboBox.addItem("Solid", Qt.SolidLine)
        self.penStyleComboBox.addItem("Dash", Qt.DashLine)
        self.penStyleComboBox.addItem("Dot", Qt.DotLine)
        self.penStyleComboBox.addItem("Dash Dot", Qt.DashDotLine)
        self.penStyleComboBox.addItem("Dash Dot Dot", Qt.DashDotDotLine)
        self.penStyleComboBox.addItem("None", Qt.NoPen)

        penStyleLabel = QLabel("&Pen Style:")
        penStyleLabel.setBuddy(self.penStyleComboBox)

        self.penCapComboBox = QComboBox()
        self.penCapComboBox.addItem("Flat", Qt.FlatCap)
        self.penCapComboBox.addItem("Square", Qt.SquareCap)
        self.penCapComboBox.addItem("Round", Qt.RoundCap)

        penCapLabel = QLabel("Pen &Cap:")
        penCapLabel.setBuddy(self.penCapComboBox)

        self.penJoinComboBox = QComboBox()
        self.penJoinComboBox.addItem("Miter", Qt.MiterJoin)
        self.penJoinComboBox.addItem("Bevel", Qt.BevelJoin)
        self.penJoinComboBox.addItem("Round", Qt.RoundJoin)

        penJoinLabel = QLabel("Pen &Join:")
        penJoinLabel.setBuddy(self.penJoinComboBox)

        self.brushStyleComboBox = QComboBox()
        self.brushStyleComboBox.addItem("Linear Gradient",
                Qt.LinearGradientPattern)
        self.brushStyleComboBox.addItem("Radial Gradient",
                Qt.RadialGradientPattern)
        self.brushStyleComboBox.addItem("Conical Gradient",
                Qt.ConicalGradientPattern)
        self.brushStyleComboBox.addItem("Texture", Qt.TexturePattern)
        self.brushStyleComboBox.addItem("Solid", Qt.SolidPattern)
        self.brushStyleComboBox.addItem("Horizontal", Qt.HorPattern)
        self.brushStyleComboBox.addItem("Vertical", Qt.VerPattern)
        self.brushStyleComboBox.addItem("Cross", Qt.CrossPattern)
        self.brushStyleComboBox.addItem("Backward Diagonal", Qt.BDiagPattern)
        self.brushStyleComboBox.addItem("Forward Diagonal", Qt.FDiagPattern)
        self.brushStyleComboBox.addItem("Diagonal Cross", Qt.DiagCrossPattern)
        self.brushStyleComboBox.addItem("Dense 1", Qt.Dense1Pattern)
        self.brushStyleComboBox.addItem("Dense 2", Qt.Dense2Pattern)
        self.brushStyleComboBox.addItem("Dense 3", Qt.Dense3Pattern)
        self.brushStyleComboBox.addItem("Dense 4", Qt.Dense4Pattern)
        self.brushStyleComboBox.addItem("Dense 5", Qt.Dense5Pattern)
        self.brushStyleComboBox.addItem("Dense 6", Qt.Dense6Pattern)
        self.brushStyleComboBox.addItem("Dense 7", Qt.Dense7Pattern)
        self.brushStyleComboBox.addItem("None", Qt.NoBrush)

        brushStyleLabel = QLabel("&Brush Style:")
        brushStyleLabel.setBuddy(self.brushStyleComboBox)

        otherOptionsLabel = QLabel("Other Options:")
        self.antialiasingCheckBox = QCheckBox("&Antialiasing")
        self.transformationsCheckBox = QCheckBox("&Transformations")

        self.shapeComboBox.activated.connect(self.shapeChanged)
        self.penWidthSpinBox.valueChanged.connect(self.penChanged)
        self.penStyleComboBox.activated.connect(self.penChanged)
        self.penCapComboBox.activated.connect(self.penChanged)
        self.penJoinComboBox.activated.connect(self.penChanged)
        self.brushStyleComboBox.activated.connect(self.brushChanged)
        self.antialiasingCheckBox.toggled.connect(self.renderArea.setAntialiased)
        self.transformationsCheckBox.toggled.connect(self.renderArea.setTransformed)

        mainLayout = QGridLayout()
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(3, 1)
        mainLayout.addWidget(self.renderArea, 0, 0, 1, 4)
        mainLayout.setRowMinimumHeight(1, 6)
        mainLayout.addWidget(shapeLabel, 2, 1, Qt.AlignRight)
        mainLayout.addWidget(self.shapeComboBox, 2, 2)
        mainLayout.addWidget(penWidthLabel, 3, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penWidthSpinBox, 3, 2)
        mainLayout.addWidget(penStyleLabel, 4, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penStyleComboBox, 4, 2)
        mainLayout.addWidget(penCapLabel, 5, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penCapComboBox, 5, 2)
        mainLayout.addWidget(penJoinLabel, 6, 1, Qt.AlignRight)
        mainLayout.addWidget(self.penJoinComboBox, 6, 2)
        mainLayout.addWidget(brushStyleLabel, 7, 1, Qt.AlignRight)
        mainLayout.addWidget(self.brushStyleComboBox, 7, 2)
        mainLayout.setRowMinimumHeight(8, 6)
        mainLayout.addWidget(otherOptionsLabel, 9, 1, Qt.AlignRight)
        mainLayout.addWidget(self.antialiasingCheckBox, 9, 2)
        mainLayout.addWidget(self.transformationsCheckBox, 10, 2)
        self.setLayout(mainLayout)

        self.shapeChanged()
        self.penChanged()
        self.brushChanged()
        self.antialiasingCheckBox.setChecked(True)

        self.setWindowTitle("Basic Drawing")

    def shapeChanged(self):
        shape = self.shapeComboBox.itemData(self.shapeComboBox.currentIndex(),
                IdRole)
        self.renderArea.setShape(shape)

    def penChanged(self):
        width = self.penWidthSpinBox.value()
        style = Qt.PenStyle(self.penStyleComboBox.itemData(
                self.penStyleComboBox.currentIndex(), IdRole))
        cap = Qt.PenCapStyle(self.penCapComboBox.itemData(
                self.penCapComboBox.currentIndex(), IdRole))
        join = Qt.PenJoinStyle(self.penJoinComboBox.itemData(
                self.penJoinComboBox.currentIndex(), IdRole))

        self.renderArea.setPen(QPen(Qt.blue, width, style, cap, join))

    def brushChanged(self):
        style = Qt.BrushStyle(self.brushStyleComboBox.itemData(
                self.brushStyleComboBox.currentIndex(), IdRole))

        if style == Qt.LinearGradientPattern:
            linearGradient = QLinearGradient(0, 0, 100, 100)
            linearGradient.setColorAt(0.0, Qt.white)
            linearGradient.setColorAt(0.2, Qt.green)
            linearGradient.setColorAt(1.0, Qt.black)
            self.renderArea.setBrush(QBrush(linearGradient))
        elif style == Qt.RadialGradientPattern:
            radialGradient = QRadialGradient(50, 50, 50, 70, 70)
            radialGradient.setColorAt(0.0, Qt.white)
            radialGradient.setColorAt(0.2, Qt.green)
            radialGradient.setColorAt(1.0, Qt.black)
            self.renderArea.setBrush(QBrush(radialGradient))
        elif style == Qt.ConicalGradientPattern:
            conicalGradient = QConicalGradient(50, 50, 150)
            conicalGradient.setColorAt(0.0, Qt.white)
            conicalGradient.setColorAt(0.2, Qt.green)
            conicalGradient.setColorAt(1.0, Qt.black)
            self.renderArea.setBrush(QBrush(conicalGradient))
        elif style == Qt.TexturePattern:
            self.renderArea.setBrush(QBrush(QPixmap(':/images/brick.png')))
        else:
            self.renderArea.setBrush(QBrush(Qt.green, style))