Exemplo n.º 1
0
class ErrorTypeInput(QWidget):
    def __init__(self, validation, defaultType, defaultSigmas):
        super().__init__()
        layout = QGridLayout()
        layout.setContentsMargins(5, 4, 0, 0)

        self._typeGroup = QButtonGroup()
        for i, option in enumerate(string.ERROR_TYPE_OPTIONS):
            button = QRadioButton(option)
            button.option = option
            button.setChecked(option == defaultType)
            self._typeGroup.addButton(button, i)
            layout.addWidget(button, 0, i)
        self._typeGroup.buttonReleased.connect(validation)

        self._sigmasGroup = QButtonGroup()
        for i, option in enumerate(string.ERROR_SIGMA_OPTIONS):
            button = QRadioButton(string.get_error_sigmas_str(option))
            button.option = option
            button.setChecked(option == defaultSigmas)
            self._sigmasGroup.addButton(button, i)
            layout.addWidget(button, 1, i)
        self._sigmasGroup.buttonReleased.connect(validation)

        self.setLayout(layout)

    def getErrorType(self):
        return string.ERROR_TYPE_OPTIONS[self._typeGroup.checkedId()]

    def getErrorSigmas(self):
        return string.ERROR_SIGMA_OPTIONS[self._sigmasGroup.checkedId()]
Exemplo n.º 2
0
 def openCameras(self):
     self.setBScale(False)
     self.setBDraw(False)
     for info in QCameraInfo.availableCameras():
         self.m_camera.append(info)
     if len(self.m_camera) < 2:
         messageBox_info('please get your binocular cameras', self)
     else:
         self.camerasSelectDialog = QDialog(self)
         self.camerasSelectDialog.setMinimumWidth(950)
         self.camerasSelectDialog.setWindowTitle('Select your disired cameras')
         camerasSelectDialogLayout = QGridLayout()
         leftLabel = QLabel('left')
         rightLabel = QLabel('right')
         leftCameraButtonGroup = QButtonGroup(self.camerasSelectDialog)
         rightCameraButtonGroup = QButtonGroup(self.camerasSelectDialog)
         camerasSelectDialogLayout.addWidget(leftLabel, 1, 0)
         camerasSelectDialogLayout.addWidget(rightLabel, 2, 0)
         for i in range(len(self.m_camera)):
             capLabel = QLabel()
             capLabel.setFixedSize(400, 300)
             cap = cv2.VideoCapture(i)
             _, then_cap = cap.read()
             cap.release()
             cv2.destroyAllWindows()
             capLabel.setPixmap(QPixmap.fromImage(npndarray2qimage(then_cap)))
             camerasSelectDialogLayout.addWidget(capLabel, 0, i+1)
             indexStr = 'Index: %d'%i
             optionalLeftCameraRadioButton = QRadioButton(indexStr)
             leftCameraButtonGroup.addButton(optionalLeftCameraRadioButton, i)
             optionalRightCameraRadioButton = QRadioButton(indexStr)
             rightCameraButtonGroup.addButton(optionalRightCameraRadioButton, i)
             if i == 0:
                 optionalLeftCameraRadioButton.setChecked(True)
                 optionalRightCameraRadioButton.setChecked(True)
             camerasSelectDialogLayout.addWidget(optionalLeftCameraRadioButton, 1, i+1)
             camerasSelectDialogLayout.addWidget(optionalRightCameraRadioButton, 2, i+1)
         button = QDialogButtonBox(self.camerasSelectDialog)
         button.addButton('OK', QDialogButtonBox.YesRole)
         button.addButton('Cancel', QDialogButtonBox.NoRole)
         button.accepted.connect(self.camerasSelectDialog.accept)
         button.rejected.connect(self.camerasSelectDialog.reject)
         camerasSelectDialogLayout.addWidget(button, 3, 0, 1, -1)
         self.camerasSelectDialog.setLayout(camerasSelectDialogLayout)
         res = self.camerasSelectDialog.exec_()
         if res == QDialog.Accepted:
             if self.leftCameraId > -1:
                 self.left_cap.release()
             if self.rightCameraId > -1:
                 self.right_cap.release()
             cv2.destroyAllWindows()
             self.leftCameraId = leftCameraButtonGroup.checkedId()
             self.rightCameraId = rightCameraButtonGroup.checkedId()
             self.cfg.set('binocular_cameras', 'leftCameraId', str(self.leftCameraId))
             self.cfg.set('binocular_cameras', 'rightCameraId', str(self.rightCameraId))
             self.cfg.write(open('SWQT.ini', 'w'))
             self.left_cap = cv2.VideoCapture(self.leftCameraId)
             self.right_cap = cv2.VideoCapture(self.rightCameraId)
     self.m_camera.clear()
Exemplo n.º 3
0
    def getColorPolygonAndBrushStyle(
            initial_color: Union[QColor, Qt.GlobalColor, QGradient] = QColor(),
            initial_polygon: NodePolygon = NodePolygon.Circle,
            initial_brushstyle: Qt.BrushStyle = Qt.NoBrush,
            parent: Optional[QWidget] = None, title: str = '',
            options: Union[QColorDialog.ColorDialogOptions,
                           QColorDialog.ColorDialogOption] = QColorDialog.ColorDialogOptions()) \
            -> (QColor, NodePolygon):

        dlg = QColorDialog(parent)

        # Add buttons to select polygon
        polygons_group = QButtonGroup(parent)
        polygons_layout = QHBoxLayout(parent)
        for p in NodePolygon:
            if p == NodePolygon.Custom:
                continue

            button = QToolButton(parent)
            button.setCheckable(True)
            button.setText(p.name)
            button.setIcon(QIcon(nodePolygonToPixmap(p, button.iconSize())))

            if p == initial_polygon:
                button.setChecked(True)
            polygons_group.addButton(button)
            polygons_group.setId(button, p.value)
            polygons_layout.addWidget(button)
        dlg.layout().insertLayout(dlg.layout().count()-1, polygons_layout)

        # Add buttons to select brush style
        brushstyle_group = QButtonGroup(parent)
        brushstyle_layout = QHBoxLayout(parent)
        for p in NODE_BRUSH_STYLES:
            button = QToolButton(parent)
            button.setCheckable(True)
            button.setIcon(QIcon(nodeBrushStyleToPixmap(p, button.iconSize())))

            if p == initial_brushstyle:
                button.setChecked(True)
            brushstyle_group.addButton(button)
            brushstyle_group.setId(button, p)
            brushstyle_layout.addWidget(button)
        dlg.layout().insertLayout(dlg.layout().count()-1, brushstyle_layout)

        if title:
            dlg.setWindowTitle(title)
        dlg.setOptions(options)
        dlg.setCurrentColor(initial_color)
        dlg.exec_()
        return (dlg.selectedColor(),
                NodePolygon(polygons_group.checkedId()),
                brushstyle_group.checkedId(),
                )
Exemplo n.º 4
0
class Pattern(QWidget):
    def __init__(self):
        super(Pattern, self).__init__()
        self.setObjectName('Pattern')
        self.setStyleSheet(GetQssFile.readQss('../resource/qss/pattern.qss'))

        self.log = logging.getLogger('StarCraftII')

        # set widget of layout
        self.frame = QFrame(self)
        self.frame.setGeometry(QDesktopWidget().screenGeometry())
        self.main_layout = QHBoxLayout(self)
        self.human_machine = QRadioButton(strings.HUMAN_VS_MACHINE, self.frame)
        self.machine_machine = QRadioButton(strings.MACHINE_VS_MACHINE,
                                            self.frame)
        self.vs_group = QButtonGroup(self.frame)
        self.main_layout.addWidget(self.human_machine,
                                   alignment=Qt.AlignCenter)
        self.main_layout.addWidget(self.machine_machine,
                                   alignment=Qt.AlignCenter)
        self.main_layout.addStretch(1)
        self.setLayout(self.main_layout)

        # initialization
        self.initUI()

    def initUI(self):
        font = QFont()
        font.setWeight(50)
        font.setPixelSize(15)
        self.human_machine.setFont(font)
        self.machine_machine.setFont(font)
        self.vs_group.addButton(self.human_machine, 1)
        self.vs_group.addButton(self.machine_machine, 2)
        self.vs_group.buttonClicked.connect(self.radioClicked)

    # the slot function of radio group
    def radioClicked(self):
        sender = self.sender()
        if sender == self.vs_group:
            message = ""
            if self.vs_group.checkedId() == 1:
                message = "change pattern: human vs. machine"
                # print(message)
                self.log.info(message)
                globalInformation.set_value('pattern',
                                            strings.HUMAN_VS_MACHINE)
            elif self.vs_group.checkedId() == 2:
                message = "change pattern: machine vs. machine"
                # print(message)
                self.log.info(message)
                globalInformation.set_value('pattern',
                                            strings.MACHINE_VS_MACHINE)
            Signal.get_signal().emit_signal_str(message)
Exemplo n.º 5
0
class GenderBox(QGroupBox):
    def __init__(self, window=None):
        super(GenderBox, self).__init__()
        self.window = window

        self.radios = (QRadioButton("Male:"), QRadioButton("Female:"))
        self.radios[0].setChecked(True)
        self.gender = 0

        hbox = QHBoxLayout()

        self.gender_buttons = QButtonGroup()
        for idx, radio in enumerate(self.radios):
            hbox.addWidget(radio)
            self.gender_buttons.addButton(radio, idx)
            radio.clicked.connect(self.radio_button_clicked)

        self.setLayout(hbox)

    def radio_button_clicked(self):
        self.gender = int(self.gender_buttons.checkedId()) * 5
        if self.window:
            self.window.gender_changed(self.gender)

    def value(self):
        return self.gender

    def setValue(self, value):
        self.radios[0].setChecked(not value)
        self.radios[1].setChecked(value)
Exemplo n.º 6
0
class RadioButtons(WidgetBridge, Choices):
    _qttype = QGroupBox

    def customize(self, widget):
        assert self.choices, "RadioButtons: Cannot build widget bridge without choices"
        # We give the GroupBox a container so we can add stretch at the end.
        self.container = QWidget(self.parent)
        hbox = QHBoxLayout(self.container)
        self.buttongroup = QButtonGroup(self.parent)
        if "direction" in self.config and \
                self.config["direction"].lower() == "vertical":
            box = QVBoxLayout()
        else:
            box = QHBoxLayout()
        ix = 1
        for text in self.choicesdict().values():
            rb = QRadioButton(text, self.parent)
            box.addWidget(rb)
            self.buttongroup.addButton(rb, ix)
            ix += 1
        widget.setLayout(box)
        hbox.addWidget(widget)
        hbox.addStretch(1)
        hbox.setContentsMargins(QMargins(0, 0, 0, 0))

    def apply(self, value):
        for b in self.buttongroup.buttons():
            b.setChecked(False)
        b = self.buttongroup.button(self.index(value) + 1)
        if b:
            b.setChecked(True)

    def retrieve(self):
        ix = self.buttongroup.checkedId()
        return self.at(ix - 1) if ix > 0 else None
Exemplo n.º 7
0
class OptionDlgRadio(OptionDlgItem):
    """Holds widget for exclusive radio button group.
    """
    def __init__(self, dlg, key, headText, textList, writeChg=True):
        # textList is list of tuples: optionText, labelText
        OptionDlgItem.__init__(self, dlg, key, writeChg)
        self.optionList = [x[0] for x in textList]
        buttonBox = QGroupBox(headText, dlg.parentGroup())
        self.control = QButtonGroup(buttonBox)
        layout = QVBoxLayout(buttonBox)
        buttonBox.setLayout(layout)
        optionSetting = dlg.option.strData(key)
        id = 0
        for optionText, labelText in textList:
            button = QRadioButton(labelText, buttonBox)
            layout.addWidget(button)
            self.control.addButton(button, id)
            id += 1
            if optionText == optionSetting:
                button.setChecked(True)
        dlg.addItem(self, buttonBox)

    def updateData(self):
        """Update Option class based on button status.
        """
        data = self.optionList[self.control.checkedId()]
        if data != self.dlg.option.strData(self.key):
            self.dlg.option.changeData(self.key, data, self.writeChg)
Exemplo n.º 8
0
class RadioButtons(QWidget):
    def __init__(self, options, validation, default, rows=None, cols=None):
        super().__init__()

        self.options = options
        self.group = QButtonGroup()
        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        for i, option in enumerate(options):
            button = QRadioButton(option)
            button.option = option
            button.setChecked(option == default)
            self.group.addButton(button, i)
            x, y = self._calculate_coordinates(i, rows, cols)
            layout.addWidget(button, x, y)

        self.group.buttonReleased.connect(validation)

        self.setLayout(layout)

    @staticmethod
    def _calculate_coordinates(i, rows, cols):
        if cols is None:
            return 0, i
        if rows is None:
            return i, 0
        return i // rows, i % cols

    def selection(self):
        return self.options[self.group.checkedId()]
Exemplo n.º 9
0
class RadioButtonWidget(QWidget):
    def __init__(self, label, instruction, button_list):
        super().__init__()
        self.title_label = QLabel(label)
        self.radio_group_box = QGroupBox(instruction)

        self.radio_button_list = []
        for button in button_list:
            self.radio_button_list.append(QRadioButton(button))
        self.radio_button_list[0].setChecked(True)

        self.radio_button_layout = QVBoxLayout()
        self.radio_button_group = QButtonGroup()
        for index, button in enumerate(self.radio_button_list, start=1):
            self.radio_button_layout.addWidget(button)
            self.radio_button_group.addButton(button)
            self.radio_button_group.setId(button, index)

        self.radio_group_box.setLayout(self.radio_button_layout)
        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.title_label)
        self.main_layout.addWidget(self.radio_group_box)
        self.setLayout(self.main_layout)

    def selected_button(self):
        return self.radio_button_group.checkedId()
Exemplo n.º 10
0
class RadioDemo(QWidget):
    """主窗口"""
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setWindowTitle("QRadioButton 使用")
        self.resize(320, -1)

        # 没有定义Group的RadioButton, 直接放在布局管理vbox中, 成一组
        vbox = QVBoxLayout()
        self.label = QLabel()
        vbox.addWidget(self.label)
        vbox.addStretch()

        # 单选按钮1, 默认选中
        self.radio_btn_1 = QRadioButton()
        self.radio_btn_1.setChecked(True)
        self.radio_btn_1.setText("单选按钮1")
        self.radio_btn_1.toggled.connect(
            lambda: self.state_btn(self.radio_btn_1))
        # 单选按钮2
        self.radio_btn_2 = QRadioButton()
        self.radio_btn_2.setText("单选按钮2")
        self.radio_btn_2.toggled.connect(
            lambda: self.state_btn(self.radio_btn_2))

        vbox.addWidget(self.radio_btn_1)
        vbox.addWidget(self.radio_btn_2)

        # 定义了Group的RadioButton, 应该为一组
        # 单选按钮3
        self.radio_btn_3 = QRadioButton()
        self.radio_btn_3.setChecked(True)
        self.radio_btn_3.setText("单选按钮3")
        # self.radio_btn_3.toggled.connect(lambda:self.state_btn(self.radio_btn_3))
        # 单选按钮4
        self.radio_btn_4 = QRadioButton()
        self.radio_btn_4.setText("单选按钮4")
        # self.radio_btn_4.toggled.connect(lambda:self.state_btn(self.radio_btn_4))

        self.btn_group = QButtonGroup(vbox)
        # self.btn_group.setParent()
        self.btn_group.addButton(self.radio_btn_3, 3)
        self.btn_group.addButton(self.radio_btn_4, 4)
        self.btn_group.buttonClicked.connect(self.state_btn2)

        vbox.addWidget(self.radio_btn_3)
        vbox.addWidget(self.radio_btn_4)

        self.setLayout(vbox)

    def state_btn(self, radio_btn):
        self.label.setText("%s, check=%s" %
                           (radio_btn.text(), radio_btn.isChecked()))

    def state_btn2(self, radio_btn):
        self.label.setText("分组器单击触发, 控件id: %d,  %s, check=%s" %
                           (self.btn_group.checkedId(), radio_btn.text(),
                            radio_btn.isChecked()))
Exemplo n.º 11
0
class ImportTypeWidget(QtWidgets.QWidget):

    def __init__(self, session, parent=None):
        """
        Initialize the base information box.
        :type session: Session
        :type parent: QtWidgets.QWidget
        """
        super().__init__(parent)
        self.session = session

        self.fileSystemRadioButton = QRadioButton('Import an ontology from a local document',self)
        self.fileSystemRadioButton.setChecked(True)
        self.checkedId = 0
        self.webRadioButton = QRadioButton('Import an ontology from a document on the web',self)

        self.buttonGroup = QButtonGroup(self)
        self.buttonGroup.addButton(self.fileSystemRadioButton,id=0)
        self.buttonGroup.addButton(self.webRadioButton, id=1)
        self.buttonGroup.setExclusive(True)
        connect(self.buttonGroup.buttonClicked, self.onButtonClicked)

        formlayout = QtWidgets.QFormLayout()
        formlayout.addRow(self.fileSystemRadioButton)
        formlayout.addRow(self.webRadioButton)

        groupbox = QtWidgets.QGroupBox('Import type', self)
        groupbox.setLayout(formlayout)
        outerFormLayout = QtWidgets.QFormLayout()
        outerFormLayout.addRow(groupbox)
        self.setLayout(outerFormLayout)


    #############################################
    #   SLOTS
    #################################
    @QtCore.pyqtSlot(QAbstractButton)
    def onButtonClicked(self, button):
        """
        Executed when a radio button is clicked
        """
        self.checkedId = self.buttonGroup.checkedId()

    def getSelectedRadioId(self):
        return self.buttonGroup.checkedId()
Exemplo n.º 12
0
    def __onAppendMeasuresDone(self, buttons: QtWidgets.QButtonGroup,
                               count_input: QtWidgets.QSpinBox) -> None:
        track = self.track.track
        if buttons.checkedId() == 1:
            with self.project.apply_mutations('%s: Fill track to end' %
                                              track.name):
                duration = audioproc.MusicalDuration()
                for mref in track.measure_list:
                    duration += mref.measure.duration

                cnt = int((self.project.duration - duration) /
                          track.measure_list[-1].measure.duration)
                for _ in range(cnt):
                    track.append_measure()

        else:
            assert buttons.checkedId() == 2
            cnt = count_input.value()
            with self.project.apply_mutations('%s: Append %d measures' %
                                              (track.name, cnt)):
                for _ in range(cnt):
                    track.append_measure()
Exemplo n.º 13
0
class InputRadioGroup(QWidget):
    """Create an horizontal radio group"""
    def __init__(self, parent=None, option_list=None, default_select=0):
        super().__init__(parent=parent)
        layout = QHBoxLayout(self)
        self.group = QButtonGroup()
        for idx, op in enumerate(option_list):
            self.op = QRadioButton(_(op))
            if idx == default_select:
                self.op.setChecked(True)
            layout.addWidget(self.op)
            self.group.addButton(self.op)
        self.setLayout(layout)

    @pyqtProperty(str)
    def currentItemData(self):
        return str(abs(int(self.group.checkedId())) - 1)
Exemplo n.º 14
0
class RadioGroup(object):
    def __init__(self,
                 value_text_tuples: Iterable[Tuple[str, Any]],
                 default: Any = None) -> None:
        # There's no reason for the caller to care about the internal IDs
        # we use. So let's make them up here as positive integers.
        self.default_value = default
        if not value_text_tuples:
            raise ValueError("No values passed to RadioGroup")
        if contains_duplicates([x[0] for x in value_text_tuples]):
            raise ValueError("Duplicate values passed to RadioGroup")
        possible_values = [x[0] for x in value_text_tuples]
        if self.default_value not in possible_values:
            self.default_value = possible_values[0]
        self.bg = QButtonGroup()  # exclusive by default
        self.buttons = []
        self.map_id_to_value = {}
        self.map_value_to_button = {}
        for i, (value, text) in enumerate(value_text_tuples):
            id_ = i + 1  # start with 1
            button = QRadioButton(text)
            self.bg.addButton(button, id_)
            self.buttons.append(button)
            self.map_id_to_value[id_] = value
            self.map_value_to_button[value] = button

    def get_value(self) -> Any:
        buttongroup_id = self.bg.checkedId()
        if buttongroup_id == NOTHING_SELECTED:
            return None
        return self.map_id_to_value[buttongroup_id]

    def set_value(self, value: Any) -> None:
        if value not in self.map_value_to_button:
            value = self.default_value
        button = self.map_value_to_button[value]
        button.setChecked(True)

    def add_buttons_to_layout(self, layout: QLayout) -> None:
        for button in self.buttons:
            layout.addWidget(button)
Exemplo n.º 15
0
class RadioGroup(object):
    def __init__(self,
                 value_text_tuples: Iterable[Tuple[str, Any]],
                 default: Any = None) -> None:
        # There's no reason for the caller to care about the internal IDs
        # we use. So let's make them up here as positive integers.
        self.default_value = default
        if not value_text_tuples:
            raise ValueError("No values passed to RadioGroup")
        if contains_duplicates([x[0] for x in value_text_tuples]):
            raise ValueError("Duplicate values passed to RadioGroup")
        possible_values = [x[0] for x in value_text_tuples]
        if self.default_value not in possible_values:
            self.default_value = possible_values[0]
        self.bg = QButtonGroup()  # exclusive by default
        self.buttons = []
        self.map_id_to_value = {}
        self.map_value_to_button = {}
        for i, (value, text) in enumerate(value_text_tuples):
            id_ = i + 1  # start with 1
            button = QRadioButton(text)
            self.bg.addButton(button, id_)
            self.buttons.append(button)
            self.map_id_to_value[id_] = value
            self.map_value_to_button[value] = button

    def get_value(self) -> Any:
        buttongroup_id = self.bg.checkedId()
        if buttongroup_id == NOTHING_SELECTED:
            return None
        return self.map_id_to_value[buttongroup_id]

    def set_value(self, value: Any) -> None:
        if value not in self.map_value_to_button:
            value = self.default_value
        button = self.map_value_to_button[value]
        button.setChecked(True)

    def add_buttons_to_layout(self, layout: QLayout) -> None:
        for button in self.buttons:
            layout.addWidget(button)
Exemplo n.º 16
0
class RadioButton(QWidget):
    def __init__(self, label, button_list):
        super().__init__()

        self.title_label = QLabel(label)
        self.radio_group_box = QGroupBox()
        self.radio_button_group = QButtonGroup()

        self.radio_button_list = []

        for button in button_list:
            self.radio_button_list.append(QRadioButton(button))

        self.radio_button_list[0].setChecked(True)

        self.radio_button_layout = QVBoxLayout()

        counter = 1

        for button in self.radio_button_list:
            self.radio_button_layout.addWidget(button)
            self.radio_button_group.addButton(button)
            self.radio_button_group.setId(button, counter)

            counter += 1

        self.radio_group_box.setLayout(self.radio_button_layout)

        self.main_radio_button_layout = QVBoxLayout()
        self.main_radio_button_layout.addWidget(self.title_label)
        self.main_radio_button_layout.addWidget(self.radio_group_box)
        self.setLayout(self.main_radio_button_layout)

    def selected_button(self):
        return self.radio_button_group.checkedId()

    def check_first(self):
        self.radio_button_list[0].setChecked(True)
Exemplo n.º 17
0
class RadioFrame(QFrame):
    def __init__(self, parent=None):
        super(RadioFrame, self).__init__(parent)

        radio1 = QRadioButton("Radio1")
        radio2 = QRadioButton("Radio2")

        self.group = QButtonGroup()
        self.group.addButton(radio1, 1)
        self.group.addButton(radio2, 2)
        radio1.toggle()

        button = QPushButton("Check")
        button.clicked.connect(self.buttonClicked)

        layout = QVBoxLayout()
        layout.addWidget(radio1)
        layout.addWidget(radio2)
        layout.addWidget(button)

        self.setLayout(layout)

    def buttonClicked(self):
        print("Radio: %d" % self.group.checkedId())
Exemplo n.º 18
0
class ListManager(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowTitleHint)
        self.setWindowTitle('List Manager')
        self.setFixedSize(400, 300)
        self.ListViewer = QListView()
        self.ListViewer.clicked.connect(self.ClickList)
        self.ListViewer.doubleClicked.connect(self.Ok)
        self.OkButton = QPushButton('OK')
        self.OkButton.clicked.connect(self.Ok)
        self.CancelButton = QPushButton('Cancel')
        self.CancelButton.clicked.connect(self.Cancel)
        sortorderlable = QLabel('Sort Order')
        self.SortOrder = [QRadioButton("Asc"), QRadioButton("Desc")]
        self.OrderGroup = QButtonGroup()
        sortalglable = QLabel('Sort Algorithm')
        self.SortAlg = [QRadioButton("Path"), QRadioButton("Natural")]
        self.AlgGroup = QButtonGroup()

        hbox1 = QHBoxLayout()
        hbox2 = QHBoxLayout()
        vbox1 = QVBoxLayout()
        vbox2 = QVBoxLayout()
        vbox3 = QVBoxLayout()
        mainbox = QVBoxLayout()

        vbox1.addWidget(sortorderlable)
        for i in range(len(self.SortOrder)):
            vbox1.addWidget(self.SortOrder[i])
            self.OrderGroup.addButton(self.SortOrder[i], i)
            self.SortOrder[i].clicked.connect(self.ClickRadioButton)
        vbox2.addWidget(sortalglable)
        for i in range(len(self.SortAlg)):
            vbox2.addWidget(self.SortAlg[i])
            self.AlgGroup.addButton(self.SortAlg[i], i)
            self.SortAlg[i].clicked.connect(self.ClickRadioButton)

        vbox3.addLayout(vbox1)
        vbox3.addLayout(vbox2)
        vbox3.addStretch(1)
        hbox1.addWidget(self.ListViewer)
        hbox1.addLayout(vbox3)
        hbox2.addStretch(1)
        hbox2.addWidget(self.OkButton)
        hbox2.addWidget(self.CancelButton)
        mainbox.addLayout(hbox1)
        mainbox.addLayout(hbox2)
        self.setLayout(mainbox)
        self.list = []
        self.path = ''

    def showEvent(self, event):
        self.center()
        self.LoadListToView()

    def closeEvent(self, event):
        self.Cancel()

    def center(self):
        frameGm = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

    def LoadListToView(self):
        if self.list:
            self.index = self.list.index(self.path)
            self.Model = QStandardItemModel(self.ListViewer)
            for file in self.list:
                item = QStandardItem(file)
                item.setEditable(False)
                self.Model.appendRow(item)
            self.ListViewer.setModel(self.Model)
            self.ListViewer.setCurrentIndex(self.Model.index(self.index, 0))

    def ClickList(self, index):
        self.path = self.Model.data(index)
        self.index = self.list.index(self.path)

    def ClickRadioButton(self):
        if self.list:
            self.list = self.Sort(self.list, self.OrderGroup.checkedId(),
                                  self.AlgGroup.checkedId())
            self.LoadListToView()

    def Ok(self):
        self.accept()

    def Cancel(self):
        self.reject()

    def Sort(self, list, sortid, algid):
        if list:
            if sortid == 0:
                isreverse = False
            else:
                isreverse = True

            if algid == 0:
                sortalg = ns.PATH
            else:
                sortalg = 0

            return natsorted(list, alg=sortalg, reverse=isreverse)
        else:
            return list
Exemplo n.º 19
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version
        capabilities = client.client.features.capabilities
        have_shamir = Capability.Shamir in capabilities

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # Backup type
        gb_backuptype = QGroupBox()
        hbox_backuptype = QHBoxLayout()
        gb_backuptype.setLayout(hbox_backuptype)
        vbox.addWidget(gb_backuptype)
        gb_backuptype.setTitle(_('Select backup type:'))
        bg_backuptype = QButtonGroup()

        rb_single = QRadioButton(gb_backuptype)
        rb_single.setText(_('Single seed (BIP39)'))
        bg_backuptype.addButton(rb_single)
        bg_backuptype.setId(rb_single, BackupType.Bip39)
        hbox_backuptype.addWidget(rb_single)
        rb_single.setChecked(True)

        rb_shamir = QRadioButton(gb_backuptype)
        rb_shamir.setText(_('Shamir'))
        bg_backuptype.addButton(rb_shamir)
        bg_backuptype.setId(rb_shamir, BackupType.Slip39_Basic)
        hbox_backuptype.addWidget(rb_shamir)
        rb_shamir.setEnabled(Capability.Shamir in capabilities)
        rb_shamir.setVisible(False)  # visible with "expert settings"

        rb_shamir_groups = QRadioButton(gb_backuptype)
        rb_shamir_groups.setText(_('Super Shamir'))
        bg_backuptype.addButton(rb_shamir_groups)
        bg_backuptype.setId(rb_shamir_groups, BackupType.Slip39_Advanced)
        hbox_backuptype.addWidget(rb_shamir_groups)
        rb_shamir_groups.setEnabled(Capability.ShamirGroups in capabilities)
        rb_shamir_groups.setVisible(False)  # visible with "expert settings"

        # word count
        word_count_buttons = {}

        gb_numwords = QGroupBox()
        hbox1 = QHBoxLayout()
        gb_numwords.setLayout(hbox1)
        vbox.addWidget(gb_numwords)
        gb_numwords.setTitle(_("Select seed/share length:"))
        bg_numwords = QButtonGroup()
        for count in (12, 18, 20, 24, 33):
            rb = QRadioButton(gb_numwords)
            word_count_buttons[count] = rb
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, count)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        def configure_word_counts():
            if model == "1":
                checked_wordcount = 24
            else:
                checked_wordcount = 12

            if method == TIM_RECOVER:
                if have_shamir:
                    valid_word_counts = (12, 18, 20, 24, 33)
                else:
                    valid_word_counts = (12, 18, 24)
            elif rb_single.isChecked():
                valid_word_counts = (12, 18, 24)
                gb_numwords.setTitle(_('Select seed length:'))
            else:
                valid_word_counts = (20, 33)
                checked_wordcount = 20
                gb_numwords.setTitle(_('Select share length:'))

            word_count_buttons[checked_wordcount].setChecked(True)
            for c, btn in word_count_buttons.items():
                btn.setVisible(c in valid_word_counts)

        bg_backuptype.buttonClicked.connect(configure_word_counts)
        configure_word_counts()

        # set up conditional visibility:
        # 1. backup_type is only visible when creating new seed
        gb_backuptype.setVisible(method == TIM_NEW)
        # 2. word_count is not visible when recovering on TT
        if method == TIM_RECOVER and model != "1":
            gb_numwords.setVisible(False)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))
        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)
            rb_shamir.setVisible(True)
            rb_shamir_groups.setVisible(True)
        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and model == '1':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RecoveryDeviceType.ScrambledWords)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RecoveryDeviceType.Matrix)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=bg_numwords.checkedId(),
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            backup_type=bg_backuptype.checkedId(),
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
Exemplo n.º 20
0
class CarcassonneInputWidget(QWidget):

    enterPressed = QtCore.pyqtSignal()

    i18n("CarcassonneInputWidget", 'City')
    i18n("CarcassonneInputWidget", 'Road')
    i18n("CarcassonneInputWidget", 'Cloister')
    i18n("CarcassonneInputWidget", 'Field')
    i18n("CarcassonneInputWidget", 'Goods')
    i18n("CarcassonneInputWidget", 'Fair')

    def __init__(self, engine, bgcolors, parent=None):
        super(CarcassonneInputWidget, self).__init__(parent)
        self.engine = engine
        self.parent = parent
        self.bgcolors = bgcolors
        self.setStyleSheet("QGroupBox { font-size: 22px; font-weight: bold; }")
        self.initUI()

    def initUI(self):
        self.widgetLayout = QHBoxLayout(self)
        self.playerGroup = QGroupBox(self)
        self.widgetLayout.addWidget(self.playerGroup)
        self.playerButtonGroup = QButtonGroup(self)
        self.playerGroupLayout = QGridLayout(self.playerGroup)

        b = QRadioButton("", self.playerGroup)
#        self.playerGroupLayout.addWidget(b)
        self.playerButtonGroup.addButton(b, 0)
        self.playerButtons = [b]
        b.hide()
        for i, player in enumerate(self.engine.getListPlayers(), 1):
            b = QRadioButton(
                '{}. {}'.format(i, player), self.playerGroup)
            if len(self.engine.getListPlayers()) > 2:
                self.playerGroupLayout.addWidget(b, (i-1) % 2, (i-1)/2)
            else:
                self.playerGroupLayout.addWidget(b, 0, (i-1) % 2)
            self.playerButtonGroup.addButton(b, i)
            self.playerButtons.append(b)

        self.kindGroup = QGroupBox(self)
        self.widgetLayout.addWidget(self.kindGroup)
        self.kindButtonGroup = QButtonGroup(self)
        self.kindGroupLayout = QGridLayout(self.kindGroup)

        b = QRadioButton("", self.kindGroup)
#        self.kindGroupLayout.addWidget(b)
        self.kindButtonGroup.addButton(b, 0)
        self.kindButtons = [b]
        b.hide()

        self.scoreSpinBox = ScoreSpinBox(self)
        self.scoreSpinBox.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreSpinBox.setMaximumWidth(60)
        self.scoreSpinBox.setRange(0, 300)

        for i, kind in enumerate(self.engine.getEntryKinds(), 1):
            lbl = i18n("CarcassonneInputWidget", kind)
            b = QRadioButton('{}. {}'.format(i, lbl), self.kindGroup)
            self.kindGroupLayout.addWidget(b, (i-1) % 2, (i-1)/2)
            self.kindButtonGroup.addButton(b, i)
            b.clicked.connect(self.scoreSpinBox.setFocus)
            self.kindButtons.append(b)

        self.kindButtons[3].toggled.connect(self.setCloisterPoints)
        self.kindButtons[5].toggled.connect(self.setGoodsPoints)
        self.kindButtons[6].toggled.connect(self.setFairPoints)

        self.scoreGroup = QGroupBox(self)
        self.widgetLayout.addWidget(self.scoreGroup)
        self.scoreGroupLayout = QHBoxLayout(self.scoreGroup)

        self.scoreGroupLayout.addWidget(self.scoreSpinBox)

        self.reset()
        self.retranslateUI()

    def retranslateUI(self):
        self.playerGroup.setTitle(i18n(
            "CarcassonneInputWidget", "Select Player"))
        self.kindGroup.setTitle(i18n(
            "CarcassonneInputWidget", "Select kind of entry"))
        self.scoreGroup.setTitle(i18n(
            "CarcassonneInputWidget", "Points"))
        for i, kind in enumerate(self.engine.getEntryKinds(), 1):
            text = i18n(
                "CarcassonneInputWidget", kind)
            self.kindButtons[i].setText('{}. {}'.format(i, text))

    def placeCommitButton(self, cb):
        self.scoreGroupLayout.addWidget(cb)

    def getPlayer(self):
        pid = self.playerButtonGroup.checkedId()
        if not pid:
            return ""
        player = self.engine.getListPlayers()[pid-1]
        return str(player)

    def getKind(self):
        cid = self.kindButtonGroup.checkedId()
        if not cid:
            return ""
        kind = self.engine.getEntryKinds()[cid-1]
        return str(kind)

    def getScore(self): return self.scoreSpinBox.value()

    def reset(self):
        self.playerButtons[0].setChecked(True)
        self.kindButtons[0].setChecked(True)
        self.scoreSpinBox.setValue(0)
        self.setFocus()

    def keyPressEvent(self, event):
        numberkeys = [QtCore.Qt.Key_1, QtCore.Qt.Key_2, QtCore.Qt.Key_3,
                      QtCore.Qt.Key_4, QtCore.Qt.Key_5, QtCore.Qt.Key_6,
                      QtCore.Qt.Key_7, QtCore.Qt.Key_8, QtCore.Qt.Key_9]
        try:
            number = numberkeys.index(event.key()) + 1
        except ValueError:
            number = 0
        if (event.key() == QtCore.Qt.Key_Return):
            self.enterPressed.emit()
        elif number:
            if not self.getPlayer():
                if number <= len(self.engine.getPlayers()):
                    self.playerButtons[number].setChecked(True)
            elif not self.getKind():
                if number <= len(self.engine.getEntryKinds()):
                    self.kindButtons[number].setChecked(True)
                    self.scoreSpinBox.setFocus()

        return super(CarcassonneInputWidget, self).keyPressEvent(event)

    def setCloisterPoints(self, doit):
        if doit:
            self.scoreSpinBox.setValue(9)
            self.scoreSpinBox.setMaximum(9)
            self.scoreSpinBox.lineEdit().selectAll()
        else:
            self.scoreSpinBox.setValue(0)
            self.scoreSpinBox.setMaximum(300)

    def setGoodsPoints(self, doit):
        if doit:
            self.scoreSpinBox.setValue(10)
            self.scoreSpinBox.setReadOnly(True)

        else:
            self.scoreSpinBox.setReadOnly(False)
            self.scoreSpinBox.setValue(0)

    def setFairPoints(self, doit):
        if doit:
            self.scoreSpinBox.setValue(5)
            self.scoreSpinBox.setReadOnly(True)

        else:
            self.scoreSpinBox.setReadOnly(False)
            self.scoreSpinBox.setValue(0)

    def updatePlayerOrder(self):
        trash = QWidget()
        trash.setLayout(self.playerGroupLayout)

        self.playerButtonGroup = QButtonGroup(self)
        self.playerGroupLayout = QGridLayout(self.playerGroup)
        b = QRadioButton("", self.playerGroup)
        self.playerButtonGroup.addButton(b, 0)
        self.playerButtons = [b]
        b.hide()

        for i, player in enumerate(self.engine.getListPlayers(), 1):
            b = QRadioButton(
                '{}. {}'.format(i, player), self.playerGroup)
            if len(self.engine.getListPlayers()) > 2:
                self.playerGroupLayout.addWidget(b, (i-1) % 2, (i-1)/2)
            else:
                self.playerGroupLayout.addWidget(b, 0, (i-1) % 2)
            self.playerButtonGroup.addButton(b, i)
            self.playerButtons.append(b)

        self.reset()
Exemplo n.º 21
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.rb11 = QRadioButton('你是', self)
        self.rb12 = QRadioButton('我是', self)
        self.rb13 = QRadioButton('他是', self)
        self.rb21 = QRadioButton('大美女', self)
        self.rb22 = QRadioButton('大帅哥', self)
        self.rb23 = QRadioButton('小屁孩', self)

        bt1 = QPushButton('提交', self)

        self.resize(320, 180)
        self.setWindowTitle('关注微信公众号:学点编程吧--单选按钮')

        self.rb11.move(20, 20)
        self.rb12.move(20, 50)
        self.rb13.move(20, 80)
        self.rb21.move(90, 20)
        self.rb22.move(90, 50)
        self.rb23.move(90, 80)

        bt1.move(20, 120)

        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.rb11, 11)
        self.bg1.addButton(self.rb12, 12)
        self.bg1.addButton(self.rb13, 13)

        self.bg2 = QButtonGroup(self)
        self.bg2.addButton(self.rb21, 21)
        self.bg2.addButton(self.rb22, 22)
        self.bg2.addButton(self.rb23, 23)

        self.info1 = ''
        self.info2 = ''

        self.bg1.buttonClicked.connect(self.rbclicked)
        self.bg2.buttonClicked.connect(self.rbclicked)
        bt1.clicked.connect(self.submit)

        self.show()

    def submit(self):
        if self.info1 == '' or self.info2 == '':
            QMessageBox.information(self, 'What?', '貌似有没有选的啊,快去选一个吧!')
        else:
            QMessageBox.information(self, 'What?', self.info1 + self.info2)

    def rbclicked(self):
        sender = self.sender()
        if sender == self.bg1:
            if self.bg1.checkedId() == 11:
                self.info1 = '你是'
            elif self.bg1.checkedId() == 12:
                self.info1 = '我是'
            elif self.bg1.checkedId() == 13:
                self.info1 = '他是'
            else:
                self.info1 = ''
        else:
            if self.bg2.checkedId() == 21:
                self.info2 = '大美女'
            elif self.bg2.checkedId() == 22:
                self.info2 = '大帅哥'
            elif self.bg2.checkedId() == 23:
                self.info2 = '小屁孩'
            else:
                self.info2 = ''
Exemplo n.º 22
0
class AlterMessage(QDialog):

    close_signal = pyqtSignal()

    def __init__(self, mess, connfd):
        super(AlterMessage, self).__init__()
        self.connfd = connfd
        self.mess = mess.split('#')
        self.timekey = False
        self.data = ''
        self.initUI()

    def initUI(self):
        # 创建固定窗口大小
        self.setFixedSize(535, 600)
        # 窗口标题
        self.setWindowTitle('注册')
        # 无边框
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon(':/logo.png'))

        window_pale = QPalette()
        window_pale.setBrush(self.backgroundRole(),\
                QBrush(QPixmap("UI/image/altermessage.jpg")))
        self.setPalette(window_pale)

        #设置字体颜色
        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.white)
        # 程序名
        self.lbl_main = QLabel('修改货运信息', self)
        self.lbl_main.move(10, 10)
        self.lbl_main.setPalette(pe)

        # 创建发货地级联布局
        self.centralwidget = QWidget(self)
        self.centralwidget.setGeometry(90, 50, 400, 40)
        layout = QHBoxLayout(self.centralwidget)
        self.province_box = QComboBox(self, minimumWidth=30)  # 市级以上
        self.province_box.setMaxVisibleItems(35)
        self.city_box = QComboBox(self, minimumWidth=73)  # 市
        self.city_box.setMaxVisibleItems(35)
        self.county_box = QComboBox(self, minimumWidth=73)  # 市级以下
        self.county_box.setMaxVisibleItems(35)
        layout.addWidget(self.province_box)
        province = QLabel("省", self)
        province.setPalette(pe)
        layout.addWidget(province)
        layout.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout.addWidget(self.city_box)
        city = QLabel("市", self)
        city.setPalette(pe)
        layout.addWidget(city)
        layout.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout.addWidget(self.county_box)
        county = QLabel("区/县", self)
        county.setPalette(pe)
        layout.addWidget(county)

        # 创建目的地级联布局
        self.centralwidget2 = QWidget(self)
        self.centralwidget2.setGeometry(90, 96, 400, 40)
        layout2 = QHBoxLayout(self.centralwidget2)
        self.province_box2 = QComboBox(self, minimumWidth=30)  # 市级以上
        self.province_box2.setMaxVisibleItems(35)
        self.city_box2 = QComboBox(self, minimumWidth=73)  # 市
        self.city_box2.setMaxVisibleItems(35)
        self.county_box2 = QComboBox(self, minimumWidth=73)  # 市级以下
        self.county_box2.setMaxVisibleItems(35)
        layout2.addWidget(self.province_box2)
        province2 = QLabel("省", self)
        province2.setPalette(pe)
        layout2.addWidget(province2)
        layout2.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout2.addWidget(self.city_box2)
        city2 = QLabel("市", self)
        city2.setPalette(pe)
        layout2.addWidget(city2)
        layout2.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        layout2.addWidget(self.county_box2)
        county2 = QLabel("区/县", self)
        county2.setPalette(pe)
        layout2.addWidget(county2)
        self.initModel()
        self.initSignal()
        self.initData()

        for i in range(self.province_box.count()):
            if self.province_box.itemText(i) == self.mess[1]:
                self.province_box.setCurrentIndex(i)
                break
        for i in range(self.city_box.count()):
            if self.city_box.itemText(i) == self.mess[2]:
                self.city_box.setCurrentIndex(i)
                break
        for i in range(self.county_box.count()):
            if self.county_box.itemText(i) == self.mess[3]:
                self.county_box.setCurrentIndex(i)
                break
        for i in range(self.province_box2.count()):
            if self.province_box2.itemText(i) == self.mess[4]:
                self.province_box2.setCurrentIndex(i)
                break
        for i in range(self.city_box2.count()):
            if self.city_box2.itemText(i) == self.mess[5]:
                self.city_box2.setCurrentIndex(i)
                break
        for i in range(self.county_box2.count()):
            if self.county_box2.itemText(i) == self.mess[6]:
                self.county_box2.setCurrentIndex(i)
                break

        #设置字体颜色
        pe = QPalette()
        pe.setColor(QPalette.WindowText, Qt.darkGray)

        self.l = ['轻卡货车', '中型货车', '大型货车', '自卸货车', '半挂货车']
        x = 100
        self.bg1 = QButtonGroup(self)
        for i in range(len(self.l)):
            self.bu = QRadioButton(self.l[i], self)
            self.bu.setGeometry(x, 150, 75, 28)
            self.bu.setPalette(pe)
            self.bg1.addButton(self.bu, i)
            x += 80

        self.info1 = self.mess[7]
        self.bg1.buttonClicked.connect(self.rbclicked)
        self.bg1.buttons()[self.l.index(self.mess[7])].toggle()

        self.l2 = ['均货', '重货', '轻货', '整车', '零担']
        x = 100
        self.bg12 = QButtonGroup(self)
        for i in range(10, 10 + len(self.l2)):
            self.bu = QRadioButton(self.l2[i - 10], self)
            self.bu.setGeometry(x, 180, 75, 28)
            # self.bu.toggle()
            self.bu.setPalette(pe)
            self.bg12.addButton(self.bu, i)
            x += 80

        self.info12 = self.mess[8]
        self.bg12.buttonClicked.connect(self.rbclicked)
        self.bg12.buttons()[self.l2.index(self.mess[8])].toggle()

        self.l3 = ['普货', '鲜货', '冻货', '大件设备']
        x = 100
        self.bg13 = QButtonGroup(self)
        for i in range(20, 20 + len(self.l3)):
            self.bu = QRadioButton(self.l3[i - 20], self)
            self.bu.setGeometry(x, 210, 75, 28)
            self.bu.setPalette(pe)
            self.bg13.addButton(self.bu, i)
            x += 80

        self.info13 = self.mess[9]
        self.bg13.buttonClicked.connect(self.rbclicked)
        self.bg13.buttons()[self.l3.index(self.mess[9])].toggle()

        self.l4 = ['无要求','20-50万','50-100万',\
                                    '100-300万','300万以上']
        x = 100
        self.bg14 = QButtonGroup(self)
        for i in range(30, 30 + len(self.l4)):
            self.bu = QRadioButton(self.l4[i - 30], self)
            self.bu.setGeometry(x, 240, 75, 28)
            self.bu.setPalette(pe)
            self.bg14.addButton(self.bu, i)
            x += 80
        self.info14 = self.mess[10]
        self.bg14.buttonClicked.connect(self.rbclicked)
        self.bg14.buttons()[self.l4.index(self.mess[10])].toggle()

        conceal = "background:\
            transparent;border-width:0;border-style:outset"

        self.Edit_bulk = QLineEdit(self)
        self.Edit_bulk.setGeometry(100, 290, 100, 22)
        self.Edit_bulk.setPlaceholderText('方量')
        self.Edit_bulk.setStyleSheet(conceal)
        self.Edit_bulk.setValidator(QRegExpValidator\
                        (QRegExp(r"[0-9]+.?[0-9]?"),self))
        self.Edit_bulk.setMaxLength(6)
        self.Edit_bulk.setToolTip('方量最大长度6位')
        self.Edit_bulk.setText(self.mess[11])

        self.weight = QLineEdit(self)
        self.weight.setGeometry(245, 290, 100, 22)
        self.weight.setPlaceholderText('总吨位')
        self.weight.setStyleSheet(conceal)
        self.weight.setValidator(QRegExpValidator\
                    (QRegExp(r"[0-9]+.?[0-9]?"),self))
        self.weight.setMaxLength(6)
        self.weight.setToolTip('吨位最大长度6位')
        self.weight.setText(self.mess[12])

        self.Edit_total = QLineEdit(self)
        self.Edit_total.setGeometry(400, 290, 100, 22)
        self.Edit_total.setPlaceholderText('运费')
        self.Edit_total.setStyleSheet(conceal)
        self.Edit_total.setValidator(QRegExpValidator\
                                (QRegExp(r"[0-9]+"),self))
        self.Edit_total.setMaxLength(7)
        self.Edit_total.setToolTip('运费最大长度为6位的整数')
        self.Edit_total.setText(self.mess[13])

        self.text_describe = QTextEdit(self)
        self.text_describe.setGeometry(100, 340, 370, 150)
        self.text_describe.setToolTip('300字以内')
        self.text_describe.setStyleSheet(conceal)

        self.text_describe.setPlaceholderText('300字以内')
        self.text_describe.setPlainText(self.mess[15])

        self.Edit_phone = QLineEdit(self)
        self.Edit_phone.setGeometry(100, 518, 150, 22)
        self.Edit_phone.setPlaceholderText('手机号码')
        self.Edit_phone.setStyleSheet(conceal)
        self.Edit_phone.setValidator(QRegExpValidator\
                                (QRegExp(r"[0-9]+"),self))
        self.Edit_phone.setMaxLength(11)
        self.Edit_phone.setToolTip('联系电话11位')
        self.Edit_phone.setText(self.mess[14])

        l = ['请选择','12小时','24小时','3天内','5天内',\
                        '1周内','1月内','3月内','1年内','永久']
        self.combo = QComboBox(self)
        self.combo.addItems(l)
        self.combo.setGeometry(400, 518, 70, 20)
        validity = int(self.mess[17]) - int(self.mess[16])
        if validity == 43200:
            validity = '12小时'
        elif validity == 86400:
            validity = '24小时'
        elif validity == 259200:
            validity = '3天内'
        elif validity == 432000:
            validity = '5天内'
        elif validity == 604800:
            validity = '1周内'
        elif validity == 2592000:
            validity = '1月内'
        elif validity == 7776000:
            validity = '3月内'
        elif validity == 31536000:
            validity = '1年内'
        elif validity == 999999999:
            validity = '永久'
        for i in range(self.combo.count()):
            if self.combo.itemText(i) == validity:
                self.combo.setCurrentIndex(i)
                break

        color2 = "QPushButton{border:none;}"\
                "QPushButton:hover{border-image:url(%s);border:none;}"

        self.button_issue = QPushButton(' ', self)
        self.button_issue.setGeometry(100, 562, 230, 26)
        self.button_issue.setStyleSheet\
                            (color2 % 'UI/image/altermessage1.png')
        self.button_issue.clicked.connect(self.onissue)

        self.centralwidget = QWidget(self)
        self.centralwidget.setGeometry(350, 555, 150, 40)
        self.gridLayout = QGridLayout(self.centralwidget)
        # 定义获取焦点事件
        self.Edit_bulk.installEventFilter(self)
        self.Edit_total.installEventFilter(self)
        self.text_describe.installEventFilter(self)
        self.Edit_phone.installEventFilter(self)
        self.combo.installEventFilter(self)
        self.province_box.installEventFilter(self)
        self.city_box.installEventFilter(self)
        self.county_box.installEventFilter(self)
        self.province_box2.installEventFilter(self)
        self.city_box2.installEventFilter(self)
        self.county_box2.installEventFilter(self)

        self.button_little = QPushButton(' ', self)
        self.button_little.setGeometry(471, 0, 32, 25)
        self.button_little.setToolTip('最小化')
        self.button_little.setStyleSheet\
                            (color2 % 'UI/image/login3.png')

        self.button_close = QPushButton(' ', self)
        self.button_close.setGeometry(503, 0, 32, 25)
        self.button_close.setToolTip('关闭')
        self.button_close.setStyleSheet\
                            (color2 % 'UI/image/login2.png')

        self.button_little.clicked.connect(self.showMinimized)

    # 定义获取焦点事件
    def eventFilter(self, obj, event):
        if obj == self.Edit_bulk:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.Edit_total:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.text_describe:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.Edit_phone:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.combo:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.province_box:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.city_box:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.county_box:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.province_box2:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.city_box2:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False
        elif obj == self.county_box2:
            if event.type() == QEvent.FocusIn:
                self.issue_Error_hint()
            return False

    def period_of_validity(self):
        now_time = round(time.time())
        if self.combo.currentText() == '12小时':
            endtime = str(now_time + 43200)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '24小时':
            endtime = str(now_time + 86400)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '3天内':
            endtime = str(now_time + 259200)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '5天内':
            endtime = str(now_time + 432000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '1周内':
            endtime = str(now_time + 604800)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '1月内':
            endtime = str(now_time + 2592000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '3月内':
            endtime = str(now_time + 7776000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '1年内':
            endtime = str(now_time + 31536000)
            return str(now_time) + '#' + endtime
        elif self.combo.currentText() == '永久':
            endtime = str(now_time + 999999999)
            return str(now_time) + '#' + endtime

    def onissue(self):
        s_province = self.province_box.currentText()
        s_city = self.city_box.currentText()
        s_county = self.county_box.currentText()
        m_province = self.province_box2.currentText()
        m_city = self.city_box2.currentText()
        m_county = self.county_box2.currentText()

        if s_province == '请选择':
            self.issue_Error_hint('*没有选择起始位置')
            return
        elif m_province == '请选择':
            self.issue_Error_hint('*没有选择目的地')
            return
        elif not self.info1:
            self.issue_Error_hint('*没有选择要求车型')
            return
        elif not self.info12:
            self.issue_Error_hint('*没有选择货物类别')
            return
        elif not self.info13:
            self.issue_Error_hint('*没有选择货物性质')
            return
        elif not self.info14:
            self.issue_Error_hint('*没有选择要求保险')
            return
        elif not self.Edit_bulk.text():
            self.issue_Error_hint('*没有输入方量')
            return
        elif not self.weight.text():
            self.issue_Error_hint('*没有输入重量')
            return
        elif not self.Edit_total.text():
            self.issue_Error_hint('*没有输入总运费')
            return
        elif not self.text_describe.toPlainText():
            self.issue_Error_hint('*详细描述不能为空(没有请写无)')
            return
        elif self.combo.currentText() == '请选择':
            self.issue_Error_hint('*没有选择有效期')
            return
        for i in self.text_describe.toPlainText():
            if i in [' ', '#']:
                self.issue_Error_hint('*详细描述中不能有【空格】')
                return
            elif i in [' ', '#']:
                self.issue_Error_hint('*详细描述中不能有【#】')
                return

        data = 'UX ' + self.mess[0] + ' ' + s_province + '#' + s_city + '#' +\
            s_county + '#' + m_province + '#' + m_city + '#' + m_county\
             + '#' + self.info1 + '#' + self.info12 + '#' + self.info13\
             + '#' + self.info14 + '#' + self.Edit_bulk.text()\
             + '#' + self.weight.text() + '#' + self.Edit_total.text()\
             + '#' + self.Edit_phone.text() + '#' + \
            self.text_describe.toPlainText()
        if self.data == data:
            return self.issue_Error_hint('*不能发布重复信息')
        self.data = data
        data = data + '#' + self.period_of_validity()
        # 让这个变量为True
        self.timekey = True
        self.threadmess = MyThread(self.connfd, data)
        self.threadmess.messageSignal.connect(self.handle_return_message)
        self.threadmess.start()

    # 处理返回的情况处理
    def handle_return_message(self, mess):
        self.threadmess.deleteLater()
        if mess == 'UXNO NoData':
            self.issue_Error_hint('*修改失败')
        elif mess == 'UXOK ':
            self.issue_Error_hint('*修改成功')
        else:
            pass
        # 把按键检测变为False
        self.timekey = False

    def issue_Error_hint(self, show=' '):
        try:
            sip.delete(self.user_hint)
        except AttributeError:
            pass
        pe_red = QPalette()
        pe_red.setColor(QPalette.WindowText, Qt.red)
        self.user_hint = QLabel(show, self.centralwidget)
        self.user_hint.setPalette(pe_red)
        self.gridLayout.addWidget(self.user_hint, 0, 0, 1, 1)
        QApplication.processEvents()

    def rbclicked(self):
        sender = self.sender()
        if sender == self.bg1:
            if self.bg1.checkedId() == 0:
                self.info1 = self.l[0]
            elif self.bg1.checkedId() == 1:
                self.info1 = self.l[1]
            elif self.bg1.checkedId() == 2:
                self.info1 = self.l[2]
            elif self.bg1.checkedId() == 3:
                self.info1 = self.l[3]
            elif self.bg1.checkedId() == 4:
                self.info1 = self.l[4]
            else:
                self.info1 = ''
            self.issue_Error_hint()
        elif sender == self.bg12:
            if self.bg12.checkedId() == 10:
                self.info12 = self.l2[0]
            elif self.bg12.checkedId() == 11:
                self.info12 = self.l2[1]
            elif self.bg12.checkedId() == 12:
                self.info12 = self.l2[2]
            elif self.bg12.checkedId() == 13:
                self.info12 = self.l2[3]
            elif self.bg12.checkedId() == 14:
                self.info12 = self.l2[4]
            else:
                self.info12 = ''
            self.issue_Error_hint()
        elif sender == self.bg13:
            if self.bg13.checkedId() == 20:
                self.info13 = self.l3[0]
            elif self.bg13.checkedId() == 21:
                self.info13 = self.l3[1]
            elif self.bg13.checkedId() == 22:
                self.info13 = self.l3[2]
            elif self.bg13.checkedId() == 23:
                self.info13 = self.l3[3]
            else:
                self.info13 = ''
            self.issue_Error_hint()
        elif sender == self.bg14:
            if self.bg14.checkedId() == 30:
                self.info14 = self.l4[0]
            elif self.bg14.checkedId() == 31:
                self.info14 = self.l4[1]
            elif self.bg14.checkedId() == 32:
                self.info14 = self.l4[2]
            elif self.bg14.checkedId() == 33:
                self.info14 = self.l4[3]
            elif self.bg14.checkedId() == 34:
                self.info14 = self.l4[4]
            else:
                self.info14 = ''
            self.issue_Error_hint()

    def initSignal(self):
        # 初始化信号槽
        self.province_box.currentIndexChanged.connect\
                                (self.city_model.setFilter)
        self.city_box.currentIndexChanged.connect\
                                (self.county_model.setFilter)
        self.province_box2.currentIndexChanged.connect\
                                (self.city_model2.setFilter)
        self.city_box2.currentIndexChanged.connect\
                                (self.county_model2.setFilter)

    def initModel(self):
        # 初始化模型
        self.province_model = SortFilterProxyModel(self)
        self.city_model = SortFilterProxyModel(self)
        self.county_model = SortFilterProxyModel(self)
        # 设置模型
        self.province_box.setModel(self.province_model)
        self.city_box.setModel(self.city_model)
        self.county_box.setModel(self.county_model)

        # 初始化模型
        self.province_model2 = SortFilterProxyModel(self)
        self.city_model2 = SortFilterProxyModel(self)
        self.county_model2 = SortFilterProxyModel(self)
        # 设置模型
        self.province_box2.setModel(self.province_model2)
        self.city_box2.setModel(self.city_model2)
        self.county_box2.setModel(self.county_model2)

    def initData(self):
        # 初始化数据
        datas = open("UI/data.json", "rb").read()
        encoding = chardet.detect(datas) or {}
        datas = datas.decode(encoding.get("encoding", "utf-8"))
        datas = json.loads(datas)
        # 开始解析数据
        for data in datas:
            item_code = data.get("item_code")  # 编码
            item_name = data.get("item_name")  # 名字
            item = QStandardItem(item_name)
            item.setData(item_code, Qt.ToolTipRole)
            if item_code.endswith("0000"):  # 4个0结尾的是市级以上的
                self.province_model.appendRow(item)
            elif item_code.endswith("00"):  # 2个0结尾的是市
                self.city_model.appendRow(item)
            else:  # 市以下
                self.county_model.appendRow(item)

        # 开始解析数据
        for data in datas:
            item_code = data.get("item_code")  # 编码
            item_name = data.get("item_name")  # 名字
            item = QStandardItem(item_name)
            item.setData(item_code, Qt.ToolTipRole)
            if item_code.endswith("0000"):  # 4个0结尾的是市级以上的
                self.province_model2.appendRow(item)
            elif item_code.endswith("00"):  # 2个0结尾的是市
                self.city_model2.appendRow(item)
            else:  # 市以下
                self.county_model2.appendRow(item)

    def handle_size(self, left, top):
        screen = self.frameGeometry()  # 窗口显示位置
        wall = QDesktopWidget().availableGeometry().center()
        screen.moveCenter(wall)
        if left < 0:
            left = 0
        if top < 0:
            top = 0
        if left > screen.left() * 2:
            left = screen.left() * 2
        if top > screen.top() * 2:
            top = screen.top() * 2
        self.move(left, top)
        QApplication.processEvents()

    # 把隐藏的窗口显示出来
    def handle_click(self):
        if not self.isVisible():
            self.show()

    # 对ESC进行的重载  按ESC也有退出的功能
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()
            self.close_signal.emit()

    # 重写无边框拖动方法
    def mouseMoveEvent(self, e: QMouseEvent):
        try:
            self._endPos = e.pos() - self._startPos
            self.move(self.pos() + self._endPos)
        except TypeError:
            pass

    def mousePressEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._isTracking = True
            self._startPos = QPoint(e.x(), e.y())

    def mouseReleaseEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None
Exemplo n.º 23
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.resize(550, 320)
        self.setWindowTitle('关注微信公众号:学点编程吧--标签:纯文本(QLabel)')

        self.lb1 = QLabel('学点编程吧,我爱你~!', self)
        self.lb1.setGeometry(0, 0, 550, 50)

        self.lb2 = QLabel('我内容很少哦...', self)
        self.lb2.setGeometry(0, 100, 120, 70)

        self.lb3 = QLabel('我内容很少哦...', self)
        self.lb3.setGeometry(0, 190, 120, 70)
        self.lb3.setWordWrap(True)  # 实现自动换行,默认是不能自动换行的

        self.bt1 = QPushButton('输入内容1', self)
        self.bt1.move(0, 150)

        self.bt2 = QPushButton('输入内容2', self)
        self.bt2.move(0, 280)

        self.ra1 = QRadioButton('左边', self)
        self.ra2 = QRadioButton('中间', self)
        self.ra3 = QRadioButton('右边', self)

        self.ra1.move(10, 60)
        self.ra2.move(70, 60)
        self.ra3.move(130, 60)

        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.ra1, 1)
        self.bg1.addButton(self.ra2, 2)
        self.bg1.addButton(self.ra3, 3)

        self.show()

        self.bg1.buttonClicked.connect(self.rbclicked)
        self.bt1.clicked.connect(self.showDialog)
        self.bt2.clicked.connect(self.showDialog)

    def rbclicked(self):
        if self.bg1.checkedId() == 1:
            self.lb1.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        elif self.bg1.checkedId() == 2:
            self.lb1.setAlignment(Qt.AlignCenter)
        elif self.bg1.checkedId() == 3:
            self.lb1.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

    def showDialog(self):
        sender = self.sender()
        if sender == self.bt1:
            text, ok = QInputDialog.getText(self, '内容1', '请输入内容1:')
            if ok:
                self.lb2.setText(text)
        elif sender == self.bt2:
            text, ok = QInputDialog.getText(self, '内容2', '请输入内容2:')
            if ok:
                self.lb3.setText(str(text))
Exemplo n.º 24
0
class FileDialogWizardDialog(QDialog, Ui_FileDialogWizardDialog):
    """
    Class implementing the color dialog wizard dialog.
    
    It displays a dialog for entering the parameters
    for the QFileDialog code generator.
    """
    def __init__(self, pyqtVariant, parent=None):
        """
        Constructor
        
        @param pyqtVariant variant of PyQt (integer; 0, 4 or 5)
        @param parent parent widget (QWidget)
        """
        super(FileDialogWizardDialog, self).__init__(parent)
        self.setupUi(self)

        self.eStartWithCompleter = E5FileCompleter(self.eStartWith)
        self.eWorkDirCompleter = E5DirCompleter(self.eWorkDir)

        self.__pyqtVariant = pyqtVariant

        self.__typeButtonsGroup = QButtonGroup(self)
        self.__typeButtonsGroup.setExclusive(True)
        self.__typeButtonsGroup.addButton(self.rOpenFile, 1)
        self.__typeButtonsGroup.addButton(self.rOpenFiles, 2)
        self.__typeButtonsGroup.addButton(self.rSaveFile, 3)
        self.__typeButtonsGroup.addButton(self.rfOpenFile, 11)
        self.__typeButtonsGroup.addButton(self.rfOpenFiles, 12)
        self.__typeButtonsGroup.addButton(self.rfSaveFile, 13)
        self.__typeButtonsGroup.addButton(self.rDirectory, 20)
        self.__typeButtonsGroup.buttonClicked[int].connect(
            self.__toggleInitialFilterAndResult)
        self.__toggleInitialFilterAndResult(1)

        self.pyqtComboBox.addItems(["PyQt4", "PyQt5"])
        if self.__pyqtVariant == 5:
            self.pyqtComboBox.setCurrentIndex(1)
        else:
            self.pyqtComboBox.setCurrentIndex(0)

        self.rSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rfSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rDirectory.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cStartWith.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cWorkDir.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cFilters.toggled[bool].connect(self.__toggleGroupsAndTest)

        self.bTest = self.buttonBox.addButton(self.tr("Test"),
                                              QDialogButtonBox.ActionRole)

        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())

    def __adjustOptions(self, options):
        """
        Private method to adjust the file dialog options.
        
        @param options file dialog options (QFileDialog.Options)
        @return modified options (QFileDialog.Options)
        """
        if Globals.isLinuxPlatform():
            options |= QFileDialog.DontUseNativeDialog
        return options

    @pyqtSlot(str)
    def on_pyqtComboBox_currentIndexChanged(self, txt):
        """
        Private slot to setup the dialog for the selected PyQt variant.
        
        @param txt text of the selected combo box entry (string)
        """
        self.rfOpenFile.setEnabled(txt == "PyQt5")
        self.rfOpenFiles.setEnabled(txt == "PyQt5")
        self.rfSaveFile.setEnabled(txt == "PyQt5")

        if txt == "PyQt5":
            if self.rfOpenFile.isChecked():
                self.rOpenFile.setChecked(True)
            elif self.rfOpenFiles.isChecked():
                self.rOpenFiles.setChecked(True)
            elif self.rfSaveFile.isChecked():
                self.rSaveFile.setChecked(True)

        self.__pyqtVariant = 5 if txt == "PyQt5" else 4

        self.__toggleInitialFilterAndResult(
            self.__typeButtonsGroup.checkedId())

    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.bTest:
            self.on_bTest_clicked()

    @pyqtSlot()
    def on_bTest_clicked(self):
        """
        Private method to test the selected options.
        """
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rOpenFile.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getOpenFileName(None, self.eCaption.text(),
                                            self.eStartWith.text(),
                                            self.eFilters.text(), options)
            else:
                QFileDialog.getOpenFileNameAndFilter(
                    None, self.eCaption.text(), self.eStartWith.text(),
                    self.eFilters.text(), self.eInitialFilter.text(), options)
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rOpenFiles.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getOpenFileNames(None, self.eCaption.text(),
                                             self.eStartWith.text(),
                                             self.eFilters.text(), options)
            else:
                QFileDialog.getOpenFileNamesAndFilter(
                    None, self.eCaption.text(), self.eStartWith.text(),
                    self.eFilters.text(), self.eInitialFilter.text(), options)
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rSaveFile.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getSaveFileName(None, self.eCaption.text(),
                                            self.eStartWith.text(),
                                            self.eFilters.text(), options)
            else:
                QFileDialog.getSaveFileNameAndFilter(
                    None, self.eCaption.text(), self.eStartWith.text(),
                    self.eFilters.text(), self.eInitialFilter.text(), options)
        elif self.rDirectory.isChecked():
            options = QFileDialog.Options()
            if not self.cSymlinks.isChecked():
                options |= QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            if self.cDirOnly.isChecked():
                options |= QFileDialog.Options(QFileDialog.ShowDirsOnly)
            else:
                options |= QFileDialog.Options(QFileDialog.Option(0))
            options = self.__adjustOptions(options)
            QFileDialog.getExistingDirectory(None, self.eCaption.text(),
                                             self.eWorkDir.text(), options)

    def __toggleConfirmCheckBox(self):
        """
        Private slot to enable/disable the confirmation check box.
        """
        self.cConfirmOverwrite.setEnabled(self.rSaveFile.isChecked()
                                          or self.rfSaveFile.isChecked())

    def __toggleGroupsAndTest(self):
        """
        Private slot to enable/disable certain groups and the test button.
        """
        if self.rDirectory.isChecked():
            self.filePropertiesGroup.setEnabled(False)
            self.dirPropertiesGroup.setEnabled(True)
            self.bTest.setDisabled(self.cWorkDir.isChecked())
        else:
            self.filePropertiesGroup.setEnabled(True)
            self.dirPropertiesGroup.setEnabled(False)
            self.bTest.setDisabled(self.cStartWith.isChecked()
                                   or self.cFilters.isChecked())

    def __toggleInitialFilterAndResult(self, id):
        """
        Private slot to enable/disable the initial filter elements and the
        results entries.
        
        @param id id of the clicked button (integer)
        """
        if (self.__pyqtVariant == 4 and id in [11, 12, 13]) or \
                (self.__pyqtVariant == 5 and id in [1, 2, 3]):
            enable = True
        else:
            enable = False
        self.lInitialFilter.setEnabled(enable)
        self.eInitialFilter.setEnabled(enable)
        self.cInitialFilter.setEnabled(enable)

        self.lFilterVariable.setEnabled(enable)
        self.eFilterVariable.setEnabled(enable)

    def getCode(self, indLevel, indString):
        """
        Public method to get the source code for Qt4 and Qt5.
        
        @param indLevel indentation level (int)
        @param indString string used for indentation (space or tab) (string)
        @return generated code (string)
        """
        # calculate our indentation level and the indentation string
        il = indLevel + 1
        istring = il * indString
        estring = os.linesep + indLevel * indString

        # now generate the code
        if self.parentSelf.isChecked():
            parent = "self"
        elif self.parentNone.isChecked():
            parent = "None"
        elif self.parentOther.isChecked():
            parent = self.parentEdit.text()
            if parent == "":
                parent = "None"

        # prepare the result variables
        nameVariable = self.eNameVariable.text()
        if not nameVariable:
            if self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFile, self.rfOpenFile, self.rSaveFile,
                    self.rfSaveFile
            ]:
                nameVariable = "fileName"
            elif self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFiles, self.rfOpenFiles
            ]:
                nameVariable = "fileNames"
            elif self.__typeButtonsGroup.checkedButton() == self.rDirectory:
                nameVariable = "dirName"
            else:
                nameVariable = "res"
        filterVariable = self.eFilterVariable.text()
        if not filterVariable:
            if (self.__pyqtVariant == 4 and
                self.__typeButtonsGroup.checkedButton() in [
                    self.rfOpenFile, self.rfOpenFiles, self.rfSaveFile]) or \
                    (self.__pyqtVariant == 5 and
                        self.__typeButtonsGroup.checkedButton() in [
                            self.rOpenFile, self.rOpenFiles, self.rSaveFile]):
                filterVariable = ", selectedFilter"
            else:
                filterVariable = ""

        code = '{0}{1} = QFileDialog.'.format(nameVariable, filterVariable)
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if self.rOpenFile.isChecked():
                code += 'getOpenFileName({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if self.eFilters.text() == "":
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFile.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if not self.cSymlinks.isChecked():
                code += \
                    ',{0}{1}QFileDialog.Options(' \
                    'QFileDialog.DontResolveSymlinks)' \
                    .format(os.linesep, istring)
            code += '){0}'.format(estring)
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if self.rOpenFiles.isChecked():
                code += 'getOpenFileNames({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNamesAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFiles.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if not self.cSymlinks.isChecked():
                code += \
                    ',{0}{1}QFileDialog.Options(' \
                    'QFileDialog.DontResolveSymlinks)' \
                    .format(os.linesep, istring)
            code += '){0}'.format(estring)
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if self.rSaveFile.isChecked():
                code += 'getSaveFileName({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getSaveFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfSaveFile.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if (not self.cSymlinks.isChecked()) or \
               (not self.cConfirmOverwrite.isChecked()):
                code += ',{0}{1}QFileDialog.Options('.format(
                    os.linesep, istring)
                if not self.cSymlinks.isChecked():
                    code += 'QFileDialog.DontResolveSymlinks'
                if (not self.cSymlinks.isChecked()) and \
                   (not self.cConfirmOverwrite.isChecked()):
                    code += ' | '
                if not self.cConfirmOverwrite.isChecked():
                    code += 'QFileDialog.DontConfirmOverwrite'
                code += ')'
            code += '){0}'.format(estring)
        elif self.rDirectory.isChecked():
            code += 'getExistingDirectory({0}{1}'.format(os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if not self.eWorkDir.text():
                code += '""'
            else:
                if self.cWorkDir.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eWorkDir.text())
            code += ',{0}{1}QFileDialog.Options('.format(os.linesep, istring)
            if not self.cSymlinks.isChecked():
                code += 'QFileDialog.DontResolveSymlinks | '
            if self.cDirOnly.isChecked():
                code += 'QFileDialog.ShowDirsOnly'
            else:
                code += 'QFileDialog.Option(0)'
            code += ')){0}'.format(estring)

        return code
Exemplo n.º 25
0
class PochaPlayerInputWidget(QFrame):

    winnerSet = QtCore.pyqtSignal(str)
    newExpected = QtCore.pyqtSignal()
    handsClicked = QtCore.pyqtSignal(str, str)

    def __init__(self, player, engine, colour=None, parent=None):
        super(PochaPlayerInputWidget, self).__init__(parent)
        self.player = player
        self.engine = engine
        self.winner = False
        self.pcolour = colour
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.setSpacing(0)

        self.label = QLabel(self)
        self.label.setText(self.player)
        self.mainLayout.addWidget(self.label)
        self.label.setAutoFillBackground(False)
        self.setFrameShape(QFrame.Panel)
        self.setFrameShadow(QFrame.Raised)
        self.label.setScaledContents(True)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setWordWrap(False)
        css = ("QLabel {{ font-size: 24px; font-weight: bold; "
               "color:rgb({},{},{});}}")
        self.label.setStyleSheet(css.format(self.pcolour.red(),
                                            self.pcolour.green(),
                                            self.pcolour.blue()))

        self.expectedGroupBox = QFrame(self)
        self.mainLayout.addWidget(self.expectedGroupBox)
        self.ebLayout = QHBoxLayout(self.expectedGroupBox)
        self.ebLayout.setSpacing(0)
        self.ebLayout.setContentsMargins(2, 2, 2, 2)
        self.expectedGroup = QButtonGroup(self)
        self.expectedGroup.buttonReleased.connect(self.expectedClickedAction)
        self.expectedButtons = []

        self.wonGroupBox = QFrame(self)
        self.mainLayout.addWidget(self.wonGroupBox)
        self.wbLayout = QHBoxLayout(self.wonGroupBox)
        self.wbLayout.setSpacing(0)
        self.wbLayout.setContentsMargins(2, 2, 2, 2)
        self.wonGroup = QButtonGroup(self)
        self.wonGroup.buttonReleased.connect(self.wonClickedAction)
        self.wonButtons = []
        for i in range(-1, 9):
            button = PochaHandsButton(str(i), self)
            self.expectedGroup.addButton(button, i)
            self.expectedButtons.append(button)
            button.toggled.connect(self.enableWonGroup)
            if i < 0:
                button.hide()
            else:
                self.ebLayout.addWidget(button)

            button = PochaHandsButton(str(i), self)
            self.wonGroup.addButton(button, i)
            self.wonButtons.append(button)
            if i < 0:
                button.hide()
            else:
                self.wbLayout.addWidget(button)

        self.reset()

    def reset(self):
        self.expectedButtons[0].setChecked(True)
        self.wonButtons[0].setChecked(True)
        self.refreshButtons()
        self.disableWonRow()

    def refreshButtons(self, forbidden=-1):
        hands = self.engine.getHands()
        for eb, wb in zip(self.expectedButtons, self.wonButtons):
            eb.setDisabled(int(eb.text()) > hands)
            if int(eb.text()) == forbidden:
                eb.setDisabled(True)
            wb.setDisabled(int(wb.text()) > hands)

    def disableWonRow(self, disable=True):
        if self.getExpectedHands() < 0:
            self.wonGroupBox.setDisabled(True)
        else:
            self.wonGroupBox.setDisabled(disable)

    def enableWonGroup(self, button):
        self.newExpected.emit()

    def isWinner(self): return False

    def getPlayer(self): return self.player

    def getScore(self):
        expected = self.expectedGroup.checkedId()
        won = self.wonGroup.checkedId()
        if expected < 0 or won < 0:
            return 0
        if expected == won:
            return 10 + 3 * won
        return -3 * abs(expected - won)

    def getWonHands(self): return self.wonGroup.checkedId()

    def getExpectedHands(self): return self.expectedGroup.checkedId()

    def setExpectedHands(self, number):
        if number < 0:
            self.expectedButtons[0].toggle()
            return True
        button = self.expectedGroup.button(number)
        if button.isEnabled():
            button.toggle()
            return True
        return False

    def setWonHands(self, number):
        if number < 0:
            self.wonButtons[0].toggle()
            return True
        button = self.wonGroup.button(number)
        if button.isEnabled():
            button.toggle()
            return True
        return False

    def expectedClickedAction(self, _):
        self.handsClicked.emit('expected', self.player)

    def wonClickedAction(self, _):
        self.handsClicked.emit('won', self.player)

    def setColour(self, colour):
        self.pcolour = colour
        css = ("QLabel {{ font-size: 24px; font-weight: bold; "
               "color:rgb({},{},{});}}")
        self.label.setStyleSheet(css.format(self.pcolour.red(),
                                            self.pcolour.green(),
                                            self.pcolour.blue()))
Exemplo n.º 26
0
class FileDialogWizardDialog(QDialog, Ui_FileDialogWizardDialog):
    """
    Class implementing the color dialog wizard dialog.
    
    It displays a dialog for entering the parameters
    for the QFileDialog code generator.
    """
    def __init__(self, pyqtVariant, parent=None):
        """
        Constructor
        
        @param pyqtVariant variant of PyQt (integer; 0, 4 or 5)
        @param parent parent widget (QWidget)
        """
        super(FileDialogWizardDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.eStartWithCompleter = E5FileCompleter(self.eStartWith)
        self.eWorkDirCompleter = E5DirCompleter(self.eWorkDir)
        
        self.__pyqtVariant = pyqtVariant
        
        self.__typeButtonsGroup = QButtonGroup(self)
        self.__typeButtonsGroup.setExclusive(True)
        self.__typeButtonsGroup.addButton(self.rOpenFile, 1)
        self.__typeButtonsGroup.addButton(self.rOpenFiles, 2)
        self.__typeButtonsGroup.addButton(self.rSaveFile, 3)
        self.__typeButtonsGroup.addButton(self.rfOpenFile, 11)
        self.__typeButtonsGroup.addButton(self.rfOpenFiles, 12)
        self.__typeButtonsGroup.addButton(self.rfSaveFile, 13)
        self.__typeButtonsGroup.addButton(self.rDirectory, 20)
        self.__typeButtonsGroup.buttonClicked[int].connect(
            self.__toggleInitialFilterAndResult)
        self.__toggleInitialFilterAndResult(1)
        
        self.pyqtComboBox.addItems(["PyQt4", "PyQt5"])
        if self.__pyqtVariant == 5:
            self.pyqtComboBox.setCurrentIndex(1)
        else:
            self.pyqtComboBox.setCurrentIndex(0)
        
        self.rSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rfSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rDirectory.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cStartWith.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cWorkDir.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cFilters.toggled[bool].connect(self.__toggleGroupsAndTest)
        
        self.bTest = self.buttonBox.addButton(
            self.tr("Test"), QDialogButtonBox.ActionRole)
        
        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())
    
    def __adjustOptions(self, options):
        """
        Private method to adjust the file dialog options.
        
        @param options file dialog options (QFileDialog.Options)
        @return modified options (QFileDialog.Options)
        """
        if Globals.isLinuxPlatform():
            options |= QFileDialog.DontUseNativeDialog
        return options
    
    @pyqtSlot(str)
    def on_pyqtComboBox_currentIndexChanged(self, txt):
        """
        Private slot to setup the dialog for the selected PyQt variant.
        
        @param txt text of the selected combo box entry (string)
        """
        self.rfOpenFile.setEnabled(txt == "PyQt5")
        self.rfOpenFiles.setEnabled(txt == "PyQt5")
        self.rfSaveFile.setEnabled(txt == "PyQt5")
        
        if txt == "PyQt5":
            if self.rfOpenFile.isChecked():
                self.rOpenFile.setChecked(True)
            elif self.rfOpenFiles.isChecked():
                self.rOpenFiles.setChecked(True)
            elif self.rfSaveFile.isChecked():
                self.rSaveFile.setChecked(True)
        
        self.__pyqtVariant = 5 if txt == "PyQt5" else 4
        
        self.__toggleInitialFilterAndResult(
            self.__typeButtonsGroup.checkedId())
    
    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.bTest:
            self.on_bTest_clicked()
    
    @pyqtSlot()
    def on_bTest_clicked(self):
        """
        Private method to test the selected options.
        """
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rOpenFile.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getOpenFileName(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    options)
            else:
                QFileDialog.getOpenFileNameAndFilter(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    self.eInitialFilter.text(),
                    options)
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rOpenFiles.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getOpenFileNames(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    options)
            else:
                QFileDialog.getOpenFileNamesAndFilter(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    self.eInitialFilter.text(),
                    options)
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rSaveFile.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getSaveFileName(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    options)
            else:
                QFileDialog.getSaveFileNameAndFilter(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    self.eInitialFilter.text(),
                    options)
        elif self.rDirectory.isChecked():
            options = QFileDialog.Options()
            if not self.cSymlinks.isChecked():
                options |= QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            if self.cDirOnly.isChecked():
                options |= QFileDialog.Options(QFileDialog.ShowDirsOnly)
            else:
                options |= QFileDialog.Options(QFileDialog.Option(0))
            options = self.__adjustOptions(options)
            QFileDialog.getExistingDirectory(
                None,
                self.eCaption.text(),
                self.eWorkDir.text(),
                options)
    
    def __toggleConfirmCheckBox(self):
        """
        Private slot to enable/disable the confirmation check box.
        """
        self.cConfirmOverwrite.setEnabled(
            self.rSaveFile.isChecked() or self.rfSaveFile.isChecked())
    
    def __toggleGroupsAndTest(self):
        """
        Private slot to enable/disable certain groups and the test button.
        """
        if self.rDirectory.isChecked():
            self.filePropertiesGroup.setEnabled(False)
            self.dirPropertiesGroup.setEnabled(True)
            self.bTest.setDisabled(self.cWorkDir.isChecked())
        else:
            self.filePropertiesGroup.setEnabled(True)
            self.dirPropertiesGroup.setEnabled(False)
            self.bTest.setDisabled(
                self.cStartWith.isChecked() or self.cFilters.isChecked())
    
    def __toggleInitialFilterAndResult(self, id):
        """
        Private slot to enable/disable the initial filter elements and the
        results entries.
        
        @param id id of the clicked button (integer)
        """
        if (self.__pyqtVariant == 4 and id in [11, 12, 13]) or \
                (self.__pyqtVariant == 5 and id in [1, 2, 3]):
            enable = True
        else:
            enable = False
        self.lInitialFilter.setEnabled(enable)
        self.eInitialFilter.setEnabled(enable)
        self.cInitialFilter.setEnabled(enable)
        
        self.lFilterVariable.setEnabled(enable)
        self.eFilterVariable.setEnabled(enable)
    
    def getCode(self, indLevel, indString):
        """
        Public method to get the source code for Qt4 and Qt5.
        
        @param indLevel indentation level (int)
        @param indString string used for indentation (space or tab) (string)
        @return generated code (string)
        """
        # calculate our indentation level and the indentation string
        il = indLevel + 1
        istring = il * indString
        estring = os.linesep + indLevel * indString
        
        # now generate the code
        if self.parentSelf.isChecked():
            parent = "self"
        elif self.parentNone.isChecked():
            parent = "None"
        elif self.parentOther.isChecked():
            parent = self.parentEdit.text()
            if parent == "":
                parent = "None"
        
        # prepare the result variables
        nameVariable = self.eNameVariable.text()
        if not nameVariable:
            if self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFile, self.rfOpenFile,
                    self.rSaveFile, self.rfSaveFile]:
                nameVariable = "fileName"
            elif self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFiles, self.rfOpenFiles]:
                nameVariable = "fileNames"
            elif self.__typeButtonsGroup.checkedButton() == self.rDirectory:
                nameVariable = "dirName"
            else:
                nameVariable = "res"
        filterVariable = self.eFilterVariable.text()
        if not filterVariable:
            if (self.__pyqtVariant == 4 and
                self.__typeButtonsGroup.checkedButton() in [
                    self.rfOpenFile, self.rfOpenFiles, self.rfSaveFile]) or \
                    (self.__pyqtVariant == 5 and
                        self.__typeButtonsGroup.checkedButton() in [
                            self.rOpenFile, self.rOpenFiles, self.rSaveFile]):
                filterVariable = ", selectedFilter"
            else:
                filterVariable = ""
        
        code = '{0}{1} = QFileDialog.'.format(nameVariable, filterVariable)
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if self.rOpenFile.isChecked():
                code += 'getOpenFileName({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if self.eFilters.text() == "":
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFile.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if not self.cSymlinks.isChecked():
                code += \
                    ',{0}{1}QFileDialog.Options(' \
                    'QFileDialog.DontResolveSymlinks)' \
                    .format(os.linesep, istring)
            code += '){0}'.format(estring)
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if self.rOpenFiles.isChecked():
                code += 'getOpenFileNames({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNamesAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFiles.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if not self.cSymlinks.isChecked():
                code += \
                    ',{0}{1}QFileDialog.Options(' \
                    'QFileDialog.DontResolveSymlinks)' \
                    .format(os.linesep, istring)
            code += '){0}'.format(estring)
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if self.rSaveFile.isChecked():
                code += 'getSaveFileName({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getSaveFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfSaveFile.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if (not self.cSymlinks.isChecked()) or \
               (not self.cConfirmOverwrite.isChecked()):
                code += ',{0}{1}QFileDialog.Options('.format(
                    os.linesep, istring)
                if not self.cSymlinks.isChecked():
                    code += 'QFileDialog.DontResolveSymlinks'
                if (not self.cSymlinks.isChecked()) and \
                   (not self.cConfirmOverwrite.isChecked()):
                    code += ' | '
                if not self.cConfirmOverwrite.isChecked():
                    code += 'QFileDialog.DontConfirmOverwrite'
                code += ')'
            code += '){0}'.format(estring)
        elif self.rDirectory.isChecked():
            code += 'getExistingDirectory({0}{1}'.format(os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eWorkDir.text():
                code += '""'
            else:
                if self.cWorkDir.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eWorkDir.text())
            code += ',{0}{1}QFileDialog.Options('.format(os.linesep, istring)
            if not self.cSymlinks.isChecked():
                code += 'QFileDialog.DontResolveSymlinks | '
            if self.cDirOnly.isChecked():
                code += 'QFileDialog.ShowDirsOnly'
            else:
                code += 'QFileDialog.Option(0)'
            code += ')){0}'.format(estring)
            
        return code
Exemplo n.º 27
0
class MainWindow(QMainWindow):
    InsertTextButton = 10
    items = {-2: "source", -3: "channel", -4: "sink"}

    def __init__(self):
        import _diagramscene_rc

        super(MainWindow, self).__init__()

        self.config_manipulations = FlumeConfig(self)
        properties_generator.dump_props()

        self.create_actions()
        self.create_menus()
        self.create_tool_box()
        self.clicked_button_id = 0

        self.scene = DiagramScene(self.item_menu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))

        self.scene.itemInserted.connect(self.item_inserted)
        self.scene.textInserted.connect(self.text_inserted)
        self.scene.itemSelected.connect(self.item_selected)

        self.create_tool_bars()
        # self.scene.enable_grid()

        layout = QHBoxLayout()
        layout.addWidget(self.tool_box)
        self.view = QGraphicsView(self.scene)
        self.view.centerOn(0, 0)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("The Flume Illustrator")

    # noinspection PyAttributeOutsideInit,PyArgumentList
    def create_actions(self):

        self.to_front_action = QAction(QIcon(':/images/bringtofront.png'),
                                       "Bring to &Front", self, shortcut="Ctrl+F",
                                       statusTip="Bring item to front", triggered=self.bring_to_front)
        self.send_back_action = QAction(QIcon(':/images/sendtoback.png'),
                                        "Send to &Back", self, shortcut="Ctrl+B",
                                        statusTip="Send item to back", triggered=self.send_to_back)
        self.bold_action = QAction(QIcon(':/images/bold.png'),
                                   "Bold", self, checkable=True, shortcut="Ctrl+B",
                                   triggered=self.handle_font_change)
        self.italic_action = QAction(QIcon(':/images/italic.png'),
                                     "Italic", self, checkable=True, shortcut="Ctrl+I",
                                     triggered=self.handle_font_change)
        self.underline_action = QAction(QIcon(':/images/underline.png'),
                                        "Underline", self, checkable=True, shortcut="Ctrl+U",
                                        triggered=self.handle_font_change)

        self.delete_action = QAction(QIcon(':/images/delete.png'),
                                     "Delete", self, shortcut="Delete", statusTip='Delete item from diagram',
                                     triggered=self.delete_item)
        self.exit_action = QAction("Exit", self, shortcut="Ctrl+X",
                                   statusTip="Quit program", triggered=self.close)
        self.about_action = QAction("About", self, shortcut="Ctrl+B",
                                    triggered=self.about)
        self.load_config_action = QAction("Load", self, shortcut="Ctrl+O",
                                          statusTip="Load config file", triggered=self.config_manipulations.load_config)

        self.enable_grid_action = QAction("Enable grid", self, checkable=True, triggered=self.enable_grid)

    # noinspection PyAttributeOutsideInit
    def create_menus(self):
        self.file_menu = self.menuBar().addMenu("File")
        self.file_menu.addAction(self.load_config_action)
        self.file_menu.addAction(self.exit_action)

        self.item_menu = self.menuBar().addMenu("Item")
        self.item_menu.addAction(self.delete_action)
        self.item_menu.addSeparator()
        self.item_menu.addAction(self.to_front_action)
        self.item_menu.addAction(self.send_back_action)

        self.about_menu = self.menuBar().addMenu("Help")
        self.about_menu.addAction(self.about_action)

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_box(self):
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(False)
        self.button_group.buttonClicked[int].connect(self.button_group_clicked)

        layout = QGridLayout()
        layout.addWidget(self.create_cell_widget("Source", "source"), 0, 0)
        layout.addWidget(self.create_cell_widget("Channel", "channel"), 0, 1)
        layout.addWidget(self.create_cell_widget("Sink", "sink"), 1, 0)

        text_button = QToolButton()
        text_button.setCheckable(True)
        self.button_group.addButton(text_button, self.InsertTextButton)
        text_button.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        text_button.setIconSize(QSize(50, 50))

        text_layout = QGridLayout()
        text_layout.addWidget(text_button, 0, 0, Qt.AlignHCenter)
        text_layout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        text_widget = QWidget()
        text_widget.setLayout(text_layout)
        layout.addWidget(text_widget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        item_widget = QWidget()
        item_widget.setLayout(layout)

        self.tool_box = QToolBox()
        self.tool_box.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.tool_box.setMinimumWidth(item_widget.sizeHint().width())
        self.tool_box.addItem(item_widget, "Basic Flume Items")

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_bars(self):

        self.edit_tool_bar = self.addToolBar("Edit")
        self.edit_tool_bar.addAction(self.delete_action)
        self.edit_tool_bar.addAction(self.to_front_action)
        self.edit_tool_bar.addAction(self.send_back_action)

        self.edit_tool_bar.addAction(self.enable_grid_action)

        self.font_combo = QFontComboBox()
        self.font_combo.currentFontChanged.connect(self.current_font_changed)

        self.font_size_combo = QComboBox()
        self.font_size_combo.setEditable(True)
        for i in range(8, 30, 2):
            self.font_size_combo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.font_size_combo.setValidator(validator)
        self.font_size_combo.currentIndexChanged.connect(self.font_size_changed)

        self.font_color_tool_button = QToolButton()
        self.font_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.font_color_tool_button.setMenu(
            self.create_color_menu(self.text_color_changed, Qt.black))
        self.text_action = self.font_color_tool_button.menu().defaultAction()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               Qt.black))
        self.font_color_tool_button.setAutoFillBackground(True)
        self.font_color_tool_button.clicked.connect(self.text_button_triggered)

        self.fill_color_tool_button = QToolButton()
        self.fill_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.fill_color_tool_button.setMenu(
            self.create_color_menu(self.item_color_changed, Qt.white))
        self.fillAction = self.fill_color_tool_button.menu().defaultAction()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               Qt.white))
        self.fill_color_tool_button.clicked.connect(self.fill_button_triggered)

        self.line_color_tool_button = QToolButton()
        self.line_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.line_color_tool_button.setMenu(
            self.create_color_menu(self.line_color_changed, Qt.black))
        self.lineAction = self.line_color_tool_button.menu().defaultAction()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               Qt.black))
        self.line_color_tool_button.clicked.connect(self.line_button_triggered)

        self.text_tool_bar = self.addToolBar("Font")
        self.text_tool_bar.addWidget(self.font_combo)
        self.text_tool_bar.addWidget(self.font_size_combo)
        self.text_tool_bar.addAction(self.bold_action)
        self.text_tool_bar.addAction(self.italic_action)
        self.text_tool_bar.addAction(self.underline_action)

        self.color_tool_bar = self.addToolBar("Color")
        self.color_tool_bar.addWidget(self.font_color_tool_button)
        self.color_tool_bar.addWidget(self.fill_color_tool_button)
        self.color_tool_bar.addWidget(self.line_color_tool_button)

        self.loading_tool_bar = self.addToolBar("Load")
        self.loading_tool_bar.addAction(self.load_config_action)

        pointer_button = QToolButton()
        pointer_button.setCheckable(True)
        pointer_button.setChecked(True)
        pointer_button.setIcon(QIcon(":/images/pointer.png"))
        line_pointer_button = QToolButton()
        line_pointer_button.setCheckable(True)
        line_pointer_button.setIcon(QIcon(":/images/linepointer.png"))

        self.pointer_type_group = QButtonGroup()
        self.pointer_type_group.addButton(pointer_button, DiagramScene.MoveItem)
        self.pointer_type_group.addButton(line_pointer_button, DiagramScene.InsertLine)
        self.pointer_type_group.buttonClicked[int].connect(self.pointer_group_clicked)

        self.scene_scale_combo = QComboBox()
        self.scene_scale_combo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.scene_scale_combo.setCurrentIndex(2)
        self.scene_scale_combo.currentIndexChanged[str].connect(self.scene_scale_changed)

        self.pointer_tool_bar = self.addToolBar("Pointer type")
        self.pointer_tool_bar.addWidget(pointer_button)
        self.pointer_tool_bar.addWidget(line_pointer_button)
        self.pointer_tool_bar.addWidget(self.scene_scale_combo)

    def button_group_clicked(self, button_id):
        buttons = self.button_group.buttons()
        self.clicked_button_id = button_id
        for button in buttons:
            if self.button_group.button(button_id) != button:
                button.setChecked(False)
        if button_id == self.InsertTextButton:
            self.scene.set_mode(DiagramScene.InsertText)
        else:
            self.scene.set_item_type(self.items[button_id])
            self.scene.set_mode(DiagramScene.InsertItem)

    def delete_item(self):
        for item in self.scene.selectedItems():
            if isinstance(item, FlumeDiagramItem):
                item.remove_arrows()
            self.scene.removeItem(item)

    # noinspection PyTypeChecker,PyCallByClass
    def about(self):

        # noinspection PyArgumentList
        QMessageBox.about(self, "About Flume Illustrator", "The Flume illustrator shows config-file details")

    def pointer_group_clicked(self):
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def bring_to_front(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() >= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() + 0.1
        selected_item.setZValue(z_value)

    def send_to_back(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() <= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() - 0.1
        selected_item.setZValue(z_value)

    def scene_scale_changed(self, scale):
        new_scale = float(scale[:scale.index("%")]) / 100
        old_transform = self.view.transform()
        self.view.resetTransform()
        self.view.translate(old_transform.dx(), old_transform.dy())
        self.view.scale(new_scale, new_scale)

    def item_inserted(self, diagram_type):
        self.pointer_type_group.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.set_mode(self.scene.DefaultMode)
        self.button_group.button(self.clicked_button_id).setChecked(False)

    def text_inserted(self, item):
        self.button_group.button(self.InsertTextButton).setChecked(False)
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def current_font_changed(self, font):
        self.handle_font_change()

    def font_size_changed(self, font=None):
        self.handle_font_change()

    def text_color_changed(self):
        self.text_action = self.sender()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               QColor(self.text_action.data())))
        self.text_button_triggered()

    def item_color_changed(self):
        self.fillAction = self.sender()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               QColor(self.fillAction.data())))
        self.fill_button_triggered()

    def line_color_changed(self):
        self.lineAction = self.sender()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               QColor(self.lineAction.data())))
        self.line_button_triggered()

    def text_button_triggered(self):
        self.scene.set_text_color(QColor(self.text_action.data()))

    def fill_button_triggered(self):
        self.scene.set_item_color(QColor(self.fillAction.data()))

    def line_button_triggered(self):
        self.scene.set_line_color(QColor(self.lineAction.data()))

    def handle_font_change(self):
        font = self.font_combo.currentFont()
        font.setPointSize(int(self.font_size_combo.currentText()))
        if self.bold_action.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italic_action.isChecked())
        font.setUnderline(self.underline_action.isChecked())

        self.scene.setFont(font)

    def item_selected(self, item):
        font = item.font()
        self.font_combo.setCurrentFont(font)
        self.font_size_combo.setEditText(str(font.pointSize()))
        self.bold_action.setChecked(font.weight() == QFont.Bold)
        self.italic_action.setChecked(font.italic())
        self.underline_action.setChecked(font.underline())

    def create_cell_widget(self, text, diagram_type):
        item = FlumeObject(diagram_type, "")
        icon = QIcon(item.pictogram.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.button_group.addButton(button)  # , diagram_type

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignHCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    # noinspection PyArgumentList
    def create_color_menu(self, slot, default_color):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        color_menu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.create_color_icon(color), name, self,
                             triggered=slot)
            action.setData(QColor(color))
            color_menu.addAction(action)
            if color == default_color:
                color_menu.setDefaultAction(action)
        return color_menu

    @staticmethod
    def create_color_tool_button_icon(image_file, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(image_file)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    @staticmethod
    def create_color_icon(color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)

    def enable_grid(self):
        if self.enable_grid_action.isChecked():
            color = Qt.black
        else:
            color = Qt.white
        for i in range(50):
            for j in range(50):
                self.scene.addEllipse(i * 100, j * 100, 2, 2, QPen(color))
Exemplo n.º 28
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # word count
        gb = QGroupBox()
        hbox1 = QHBoxLayout()
        gb.setLayout(hbox1)
        vbox.addWidget(gb)
        gb.setTitle(_("Select your seed length:"))
        bg_numwords = QButtonGroup()
        word_counts = (12, 18, 24)
        for i, count in enumerate(word_counts):
            rb = QRadioButton(gb)
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, i)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))
        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)
        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and not model == 'T':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=word_counts[bg_numwords.checkedId()],
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
Exemplo n.º 29
0
class NewUserForm(QWidget):

    def __init__(self, parent=None):
        super(NewUserForm, self).__init__(parent)
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()

    def createWidgets(self):
        self.title = QLabel("Welcome!")
        titleFont = QFont()
        titleFont.setPointSize(36)
        titleFont.setItalic(True)
        self.title.setFont(titleFont)

        self.subtitle = QLabel("Before we begin the experiment, please fill the following details. Those details will be kept completely confidential and used for the sole purpose of the experiment.")
        self.subtitle.setWordWrap(True)

        self.idLabel = QLabel("&Identification number")
        self.idLineEdit = QLineEdit()
        # TODO add validation
        regexp = QRegExp('^\d{8,9}$')
        validator = QRegExpValidator(regexp)
        self.idLineEdit.setValidator(validator)
        self.idLabel.setBuddy(self.idLineEdit)

        self.ageLabel = QLabel("&Age:")
        self.ageSpinBox = QSpinBox()
        self.ageSpinBox.setRange(16, 80)
        self.ageSpinBox.setValue(20)
        self.ageLabel.setBuddy(self.ageSpinBox)

        self.genderLabel = QLabel("&Gender:")
        self.maleRadioButton = QRadioButton("Male")
        self.femaleRadioButton = QRadioButton("Female")
        self.genderButtonGroup = QButtonGroup()
        self.genderButtonGroup.addButton(self.maleRadioButton, 1)
        self.genderButtonGroup.addButton(self.femaleRadioButton, 2)
        self.genderLayout = QHBoxLayout()
        self.genderLayout.addWidget(self.maleRadioButton)
        self.genderLayout.addWidget(self.femaleRadioButton)
        self.genderLabel.setBuddy(self.maleRadioButton)

        self.fieldLabel = QLabel("Primary &field of studies:")
        field_list = ["--- Please select ---",
                      "Industrial Engineering",
                      "Electrical Engineering",
                      "Electrical Engineering & Computer Science",
                      "Electrical Engineering & Physics",
                      "Mechanical Engineering",
                      "Biomedical Engineering",
                      "Environmental Engineering"]
        self.fieldComboBox = QComboBox()
        self.fieldComboBox.addItems(field_list)
        self.fieldLabel.setBuddy(self.fieldComboBox)

        # self.next_button = QPushButton("Next >")
        # self.buttonBox = QDialogButtonBox(self.next_button)

    def layoutWidgets(self):
        formLayout = QGridLayout()
        formLayout.setSpacing(20)
        formLayout.setColumnStretch(0, 5)
        formLayout.setColumnStretch(1, 2)
        formLayout.setColumnStretch(2, 2)
        formLayout.setColumnStretch(4, 5)
        formLayout.setRowStretch(0, 1)
        
        formLayout.addWidget(self.title, 1, 1, 1, 2)
        formLayout.setRowMinimumHeight(2, 50)
        formLayout.addWidget(self.subtitle, 3, 1, 1, 2)
        formLayout.addWidget(self.idLabel, 4, 1)
        formLayout.addWidget(self.idLineEdit, 4, 2)
        formLayout.addWidget(self.ageLabel, 5, 1)
        formLayout.addWidget(self.ageSpinBox, 5, 2)
        formLayout.addWidget(self.genderLabel, 6, 1)
        formLayout.addLayout(self.genderLayout, 6, 2)
        formLayout.addWidget(self.fieldLabel, 7, 1)
        formLayout.addWidget(self.fieldComboBox, 7, 2)
        formLayout.setRowMinimumHeight(8, 30)
        # formLayout.addWidget(self.next_button, 9, 2)
        formLayout.setRowStretch(10, 1)

        self.setLayout(formLayout)

    def createConnections(self):
        # self.next_button.clicked.connect(self.accepted)
        pass

    def accepted(self):
        pass

    def save_results(self):
        # get value of gender checkbox and convert
        # 1 --> m
        # 2 --> f
        g = self.genderButtonGroup.checkedId()
        # save variables to global module 'config'
        config.id = self.idLineEdit.text()
        config.age = self.ageSpinBox.value()
        config.male = 1 if g == 1 else 0 if g == 2 else 999
        config.field = self.fieldComboBox.currentText()

    def rejected(self):
        # in case of pressing "Cancel"
        self.closeEvent(self)

    def closeEvent(self, event):
        # in case of clicking on X
        reply = QMessageBox.question(self, 'Message',
                                     "Are you sure you want to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
Exemplo n.º 30
0
class ToyConfigWindow(QDialog):
    def __init__(self, parent=None):
        super(ToyConfigWindow, self).__init__(parent)
        self.db_settings = get_settings_from_db()
        self.port_list = get_coms()
        if len(self.port_list) < 1:
            QMessageBox.critical(self, "Error", "Can not find any port")
        self.set_config_ui()

    def set_config_ui(self):
        # Main window style
        if platform == "linux" or platform == "linux2":
            # linux
            self.setGeometry(350, 350, 450, 390)
        elif platform == "darwin":
            # OS X
            self.setGeometry(350, 350, 450, 330)
        elif platform == "win32":
            # Windows...
            self.setGeometry(350, 350, 450, 330)

        self.setObjectName("configWindowBox")
        self.setWindowTitle("Settings")
        self.setFixedSize(self.width(), self.height())
        self.setWindowIcon(
            QIcon(
                os.path.dirname(os.path.realpath(__file__)) +
                "/resource/icon-set.png"))
        self.setModal(True)

        # -----------------------------------------------------------------------------
        # Package group
        barCodeLabel = QLabel('Web site :')
        barCodeLabel.setFixedWidth(55)
        self.barCodeInput = QLineEdit()
        self.barCodeInput.setText(self.db_settings['website'])
        packageBarCodeHLayout = QHBoxLayout()
        packageBarCodeHLayout.addWidget(barCodeLabel)
        packageBarCodeHLayout.addWidget(self.barCodeInput)

        barIDLabel = QLabel('ID :')
        barIDLabel.setFixedWidth(55)
        self.barIDInput = QLineEdit()
        self.barIDInput.setText(self.db_settings['key_id'])
        self.barIDInput.setFixedWidth(100)
        barRepeatLabel = QLabel('Repeat :')
        barRepeatLabel.setFixedWidth(55)
        self.barRepeatPassRadio = QRadioButton('pass')
        self.barRepeatNgRadio = QRadioButton('NG')

        if self.db_settings['repeat'] == "pass":
            self.barRepeatPassRadio.setChecked(True)
        else:
            self.barRepeatNgRadio.setChecked(True)

        self.repeatCodeBtns = QButtonGroup()
        self.repeatCodeBtns.addButton(self.barRepeatPassRadio, 0)
        self.repeatCodeBtns.addButton(self.barRepeatNgRadio, 1)

        packageBarIDHLayout = QHBoxLayout()
        packageBarIDHLayout.addWidget(barIDLabel)
        packageBarIDHLayout.addWidget(self.barIDInput)
        packageBarIDHLayout.addStretch(100)
        packageBarIDHLayout.addWidget(barRepeatLabel)
        packageBarIDHLayout.addWidget(self.barRepeatPassRadio)
        packageBarIDHLayout.addWidget(self.barRepeatNgRadio)
        packageBarIDHLayout.addStretch(1)

        packageInnerVLayout = QVBoxLayout()
        packageInnerVLayout.addLayout(packageBarCodeHLayout)
        packageInnerVLayout.addLayout(packageBarIDHLayout)

        packageGroupBox = QGroupBox('Package')
        packageGroupBox.setLayout(packageInnerVLayout)

        packageLayout = QHBoxLayout()
        packageLayout.addWidget(packageGroupBox)

        # -----------------------------------------------------------------------------
        # MCU group
        mcuPortLabel = QLabel('Port :')
        self.mcuCombobox = QComboBox()
        self.mcuCombobox.setFixedWidth(85)
        self.mcuCombobox.addItems(self.port_list)
        self.mcuCombobox.setCurrentText(self.db_settings['mcu_port'])
        mcuPortHLayout = QHBoxLayout()
        mcuPortHLayout.addWidget(mcuPortLabel)
        mcuPortHLayout.addWidget(self.mcuCombobox)
        mcuPortHLayout.addStretch(1)

        self.motorRunButton = QPushButton('Motor Run')
        # self.motorRunButton.setFixedWidth(85)
        self.motorRunButton.clicked.connect(self.motorRun)
        self.motorStopButton = QPushButton('Motor Stop')
        # self.motorStopButton.setFixedWidth(85)
        self.motorStopButton.clicked.connect(self.motorStop)
        motorVLayout = QVBoxLayout()
        motorVLayout.addWidget(self.motorRunButton)
        motorVLayout.addWidget(self.motorStopButton)

        mcuVLayout = QVBoxLayout()
        mcuVLayout.addLayout(mcuPortHLayout)
        mcuVLayout.addLayout(motorVLayout)

        mcuGroupBox = QGroupBox('MCU')
        mcuGroupBox.setLayout(mcuVLayout)

        # -----------------------------------------------------------------------------
        # Scanner group
        scannerPortLabel = QLabel('Port :')
        self.readerButton = QPushButton('Read')
        self.readerButton.clicked.connect(self.testScanner)
        self.scannerCombobox = QComboBox()
        self.scannerCombobox.setFixedWidth(85)
        self.scannerCombobox.addItems(self.port_list)
        self.scannerCombobox.setCurrentText(self.db_settings['scanner_port'])
        scannerPortHLayout = QHBoxLayout()
        scannerPortHLayout.addWidget(scannerPortLabel)
        scannerPortHLayout.addWidget(self.scannerCombobox)
        scannerPortHLayout.addStretch(1)
        scannerPortHLayout.addWidget(self.readerButton)

        self.readerTextBox = QTextBrowser()
        # self.readerTextBox.setFixedHeight(0)
        readerHLayout = QHBoxLayout()
        readerHLayout.addWidget(self.readerTextBox)

        scannerVLayout = QVBoxLayout()
        scannerVLayout.addLayout(scannerPortHLayout)
        scannerVLayout.addLayout(readerHLayout)

        scannerGroupBox = QGroupBox('Scanner')
        scannerGroupBox.setLayout(scannerVLayout)

        comsLayout = QHBoxLayout()
        comsLayout.addWidget(mcuGroupBox)
        comsLayout.addWidget(scannerGroupBox)

        # -----------------------------------------------------------------------------
        # Duration group
        durationReadLabel = QLabel('How long for read a bar code(ms) :')
        durationReadLabel.setFixedWidth(280)
        self.durationReadSpinBox = QSpinBox()
        self.durationReadSpinBox.setMaximum(1000000)
        self.durationReadSpinBox.setValue(self.db_settings['duration_read'])
        durationReadHLayout = QHBoxLayout()
        durationReadHLayout.addWidget(durationReadLabel)
        durationReadHLayout.addWidget(self.durationReadSpinBox)

        durationWaitLabel = QLabel('How long for wait for next bar code(ms) :')
        durationWaitLabel.setFixedWidth(280)
        self.durationWaitSpinBox = QSpinBox()
        self.durationWaitSpinBox.setMaximum(1000000)
        self.durationWaitSpinBox.setValue(self.db_settings['duration_wait'])
        durationWaitHLayout = QHBoxLayout()
        durationWaitHLayout.addWidget(durationWaitLabel)
        durationWaitHLayout.addWidget(self.durationWaitSpinBox)

        durationInnerVLayout = QVBoxLayout()
        durationInnerVLayout.addLayout(durationReadHLayout)
        durationInnerVLayout.addLayout(durationWaitHLayout)

        durationGroupBox = QGroupBox('Duration')
        durationGroupBox.setLayout(durationInnerVLayout)

        durationLayout = QHBoxLayout()
        durationLayout.addWidget(durationGroupBox)

        # -----------------------------------------------------------------------------
        # Save button
        self.saveButton = QPushButton('Save')
        self.saveButton.setFixedWidth(80)
        self.saveButton.clicked.connect(self.saveSettings)

        saveSettingsHLayout = QHBoxLayout()
        saveSettingsHLayout.addWidget(self.saveButton)

        # Main window layout
        mainVLayout = QVBoxLayout()
        mainVLayout.addLayout(packageLayout)
        mainVLayout.addLayout(comsLayout)
        mainVLayout.addLayout(durationLayout)
        mainVLayout.addLayout(saveSettingsHLayout)

        # -----------------------------------------------------------------------------
        # exec
        self.style = '''
                    #configWindowBox{background-color:#f6f6f6}
                '''
        self.setStyleSheet(self.style)
        self.setLayout(mainVLayout)
        self.show()

    def saveSettings(self):
        cfg_website = self.barCodeInput.text()
        cfg_barcodeId = self.barIDInput.text()
        if self.repeatCodeBtns.checkedId() == 0:
            repeatHandel = 'pass'
        else:
            repeatHandel = 'NG'
        cfg_mcu_port = self.mcuCombobox.currentText()
        cfg_scanner_port = self.scannerCombobox.currentText()
        cfg_duration_read = self.durationReadSpinBox.text()
        cfg_duration_wait = self.durationWaitSpinBox.text()
        cfg_lasttime = get_current_time()

        if cfg_mcu_port == cfg_scanner_port:
            QMessageBox.critical(self, "Error",
                                 "MCU port can not be same as scanner port")
        else:
            if len(cfg_barcodeId) < 1:
                QMessageBox.critical(self, "Error", "ID can not be empty!")
            else:
                try:
                    my_sqlite_db = Database()
                    update_settings = """UPDATE settings SET website=?,key_id=?,repeat=?,mcu_port=?,scanner_port=?,duration_read=?,duration_wait=?,modify_time=? WHERE id = 1"""
                    my_sqlite_db.update(update_settings, [
                        cfg_website, cfg_barcodeId, repeatHandel, cfg_mcu_port,
                        cfg_scanner_port, cfg_duration_read, cfg_duration_wait,
                        cfg_lasttime
                    ])
                    print('save settings ok')
                    self.close()
                except Exception as e:
                    print(e)

    def testScanner(self):
        self.serial_name_scanner = self.scannerCombobox.currentText()
        self.readerButton.setDisabled(True)
        self.readerTextBox.setText('Scanner reading...')
        try:
            self.ser_scanner = serial.Serial(self.serial_name_scanner,
                                             15200,
                                             timeout=0)
            begin_bytes = []
            for i in "16540D".split():
                begin_bytes.append(binascii.a2b_hex(i))
            self.ser_scanner.writelines(begin_bytes)

            # wait 2s for reading
            time.sleep(0.8)
            read_string = ''
            for x in range(0, 100):
                this_byte = self.ser_scanner.read(1)
                if this_byte != '\r':
                    read_string += this_byte.decode('utf8')
                else:
                    print("finish")

            if len(read_string) < 1:
                self.readerTextBox.setText('Can not to read')
            else:
                self.readerTextBox.setText('OK: ' + read_string)
            stop_bytes = []
            for k in "16550D".split():
                stop_bytes.append(binascii.a2b_hex(k))
            self.ser_scanner.writelines(stop_bytes)
            self.ser_scanner.close()
            self.readerButton.setDisabled(False)
        except Exception as e:
            QMessageBox.critical(
                self, "Error",
                "Can not open port %s" % self.serial_name_scanner)
            self.readerTextBox.setText('Can not to read')
            self.readerButton.setDisabled(False)

    def motorRun(self):
        serial_name = self.mcuCombobox.currentText()
        ser = serial.Serial(serial_name, 9600, timeout=0)
        do_motor_run(ser)

    def motorStop(self):
        serial_name = self.mcuCombobox.currentText()
        ser = serial.Serial(serial_name, 9600, timeout=0)
        do_motor_stop(ser)
Exemplo n.º 31
0
    def request_trezor_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            # KeepKey recovery doesn't need a word count
            if method == TIM_NEW:
                vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")
                def set_enabled():
                    from electrum.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))
                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())
Exemplo n.º 32
0
class DataCheck(Content):

    def __init__(self, parent=None, button_func=None, params=None):
        super().__init__(parent, 'Data check', params)

        self.button_func = button_func

        path = os.path.abspath(os.path.dirname(__file__)) + '/static/'

        # nr = min(5, data.shape[0])
        nr = len(self.params.data5)

        if params.lang == 'jp':
            text = ('データの読み込み結果(先頭{n}行)を以下に示します.\n'
                    'データを正しく読み込めていることを確認してください.'.format(n=nr))
            self.set_paragraph(
                'データ読み込み結果の確認', text=text)
        else:
            text = ('First {n} rows of your data are shown below.\n'
                    'Confirm that the data was read correctly.'.format(n=nr))
            self.set_paragraph(
                'Check data', text=text)

        table = NonScrollTable(self.inner)

        table.setRowCount(nr)
        table.setColumnCount(len(self.params.columns))
        table.setHorizontalHeaderLabels(self.params.columns)

        for r in range(nr):
            for c in range(len(self.params.columns)):
                item = QTableWidgetItem(str(self.params.data5.iat[r, c]))
                item.setFlags(Qt.ItemIsEnabled)
                table.setItem(r, c, item)

        table.setNonScroll()

        self.vbox.addWidget(table)

        # Text for type checking and objective variable setting
        path1 = path + 'categorical'
        text = self.get_text(path1)
        if self.params.lang == 'en':
            self.set_paragraph(
                'Check type of variables and set objective variable',
                text=text)
        else:
            self.set_paragraph('変数タイプの確認と目的変数の設定', text=text)

        # htable = QTableWidget(self.inner)
        htable = NonScrollTable(self.inner)

        htable.setRowCount(len(self.params.columns))
        htable.setColumnCount(4)
        htable.setHorizontalHeaderLabels(
            ['columns', 'categorical', 'numerical', 'target'])

        self.lst_cat = []
        self.lst_num = []
        self.lst_obj = []
        self.obj_group = QButtonGroup(self.inner)
        for c in range(len(self.params.columns)):
            # col 1
            item = QTableWidgetItem(self.params.columns[c])
            item.setFlags(Qt.ItemIsEnabled)
            htable.setItem(c, 0, item)

            group = QButtonGroup(self.inner)

            # col 2
            htable.setCellWidget(
                c, 1,
                self.__make_cell(c, 'cat', self.params.col_types[c],
                                 self.params.col_types_def[c]))
            group.addButton(self.lst_cat[-1])

            # col 3
            htable.setCellWidget(
                c, 2,
                self.__make_cell(c, 'num', self.params.col_types[c],
                                 self.params.col_types_def[c]))
            group.addButton(self.lst_num[-1])

            # col 4
            htable.setCellWidget(
                c, 3,
                self.__make_cell(c, 'obj', self.params.col_types[c],
                                 self.params.col_types_def[c]))
            self.obj_group.addButton(self.lst_obj[-1])
            self.obj_group.setId(self.lst_obj[-1], c)

        htable.setNonScroll()

        self.vbox.addWidget(htable)

        if self.params.lang == 'jp':
            self.txt_cnf = ('<font color="red">目的変数を1つ選択し,'
                    'targetの列にチェックをいれてください。')
            if self.params.task.lower() == 'classification':
                self.txt_cnf += '<br>目的変数はカテゴリ変数である必要があります。</font>'
            else:
                self.txt_cnf += '<br>目的変数は量的変数である必要があります。</font>'
        else:
            self.txt_cnf = ('<font color="red">Select one variable as target variable,'
                            'then set the column of "target" of the variable checked.')
            if self.params.task.lower() == 'classification':
                self.txt_cnf += '<br>Target variable must be a categorical variable.</font>'
            else:
                self.txt_cnf += '<br>Target variable must be a numerical variable.</font>'
        self.lbl_cnf = QLabel(self.txt_cnf, self.inner)

        self.vbox.addWidget(self.lbl_cnf)

        self.vbox.addStretch(1)

        self.btn = QPushButton('Next', self.inner)
        self.btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
        if self.params.lang == 'en':
            self.btn.clicked.connect(lambda: self.button_func('Overfitting'))
        else:
            self.btn.clicked.connect(lambda: self.button_func('過学習'))
        if self.obj_group.checkedButton() is None:
            self.btn.setEnabled(False)
        else:
            self.btn.setEnabled(True)

        self.vbox.addWidget(self.btn)

    def __make_cell(self, c, name, col_type, col_type_def):
        cell = QWidget(self.inner)
        rbtn = QRadioButton('', cell)
        rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c)))
        hbl = QHBoxLayout(cell)
        hbl.addWidget(rbtn)
        hbl.setContentsMargins(0, 0, 0, 0)
        hbl.setAlignment(Qt.AlignCenter)
        cell.setLayout(hbl)
        if name == 'cat':
            if col_type == 'object':
                rbtn.setChecked(True)
            self.lst_cat.append(rbtn)
        elif name == 'num':
            if col_type != 'object':
                rbtn.setChecked(True)
            if col_type_def == 'object':
                rbtn.setEnabled(False)
            self.lst_num.append(rbtn)
        elif name == 'obj':
            if col_type == 'object' and self.params.task == 'Regression':
                rbtn.setEnabled(False)
            elif col_type != 'object' and self.params.task == 'Classification':
                rbtn.setEnabled(False)
            if self.params.columns[c] == self.params.objective:
                rbtn.setChecked(True)
            self.lst_obj.append(rbtn)

        return cell

    def rbtn_clicked(self, text):
        name, idx = text.split('_')
        idx = int(idx)
        if len(self.lst_obj) <= idx:
            return

        if self.lst_num[idx].isChecked():
            if self.params.task == 'Classification':
                self.obj_group.setExclusive(False)
                self.lst_obj[idx].setChecked(False)
                self.obj_group.setExclusive(True)
                self.lst_obj[idx].setEnabled(False)
            elif self.params.task == 'Regression':
                self.lst_obj[idx].setEnabled(True)

            self.params.col_types[idx] = self.params.col_types_def[idx]
        elif self.lst_cat[idx].isChecked():
            if self.params.task == 'Classification':
                self.lst_obj[idx].setEnabled(True)
            elif self.params.task == 'Regression':
                self.obj_group.setExclusive(False)
                self.lst_obj[idx].setChecked(False)
                self.obj_group.setExclusive(True)
                self.lst_obj[idx].setEnabled(False)

            self.params.col_types[idx] = 'object'

        if self.obj_group.checkedButton() is None:
            self.params.objective = None
            self.lbl_cnf.setText(self.txt_cnf)
            self.btn.setEnabled(False)
        else:
            self.params.objective =\
                self.params.columns[self.obj_group.checkedId()]
            self.lbl_cnf.setText('<br>')
            self.btn.setEnabled(True)

        self.params.col_types_changed = True
Exemplo n.º 33
0
    def request_trezor_init_settings(self, wizard, method, model):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        gb = QGroupBox()
        hbox1 = QHBoxLayout()
        gb.setLayout(hbox1)
        vbox.addWidget(gb)
        gb.setTitle(_("Select your seed length:"))
        bg_numwords = QButtonGroup()
        for i, count in enumerate([12, 18, 24]):
            rb = QRadioButton(gb)
            rb.setText(_("%d words") % count)
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, i)
            hbox1.addWidget(rb)
            rb.setChecked(True)
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)

        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        if method == TIM_RECOVER and not model == 'T':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
            hbox_rectype.addWidget(rb2)
        else:
            bg_rectype = None

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        item = bg_numwords.checkedId()
        pin = cb_pin.isChecked()
        recovery_type = bg_rectype.checkedId() if bg_rectype else None

        return (item, name.text(), pin, cb_phrase.isChecked(), recovery_type)
Exemplo n.º 34
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # word count
        gb = QGroupBox()
        hbox1 = QHBoxLayout()
        gb.setLayout(hbox1)
        vbox.addWidget(gb)
        gb.setTitle(_("Select your seed length:"))
        bg_numwords = QButtonGroup()
        word_counts = (12, 18, 24)
        for i, count in enumerate(word_counts):
            rb = QRadioButton(gb)
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, i)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))

        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)

        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and not model == 'T':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=word_counts[bg_numwords.checkedId()],
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
Exemplo n.º 35
0
class Ui_Dialog(QWidget):
    def setupUi(self, Dialog):
        """
        UI模块
        :param Dialog:主界面
        :return:
        """
        Dialog.setObjectName("Dialog")
        Dialog.resize(1116, 738)
        self.cwd = os.getcwd()
        self.tabWidget = QtWidgets.QTabWidget(Dialog)
        self.tabWidget.setGeometry(QtCore.QRect(-10, 0, 1121, 741))
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")

        self.tabWidget.setDocumentMode(True)
        self.setAcceptDrops(True)
        self.outers = QtWidgets.QPushButton(self.tab)
        self.outers.setGeometry(QtCore.QRect(60, 110, 100, 40))
        self.outers.setObjectName("outers")

        self.outer_y = QtWidgets.QRadioButton(self.tab)
        self.outer_y.setGeometry(QtCore.QRect(200, 100, 89, 16))
        self.outer_y.setObjectName("outer_y")

        self.outer_x = QtWidgets.QRadioButton(self.tab)
        self.outer_x.setGeometry(QtCore.QRect(200, 150, 89, 16))
        self.outer_x.setObjectName("outer_x")

        self.show_files = QtWidgets.QTextBrowser(self.tab)
        self.show_files.setGeometry(QtCore.QRect(360, 60, 271, 131))
        self.show_files.setObjectName("show_files")

        # self.pushButton_2 = QtWidgets.QPushButton(self.tab)
        # self.pushButton_2.setGeometry(QtCore.QRect(60, 290, 100, 40))
        # self.pushButton_2.setObjectName("pushButton_2")
        #
        # self.radioButton_3 = QtWidgets.QRadioButton(self.tab)
        # self.radioButton_3.setGeometry(QtCore.QRect(200, 270, 89, 16))
        # self.radioButton_3.setObjectName("radioButton_3")
        #
        # self.radioButton_4 = QtWidgets.QRadioButton(self.tab)
        # self.radioButton_4.setGeometry(QtCore.QRect(200, 330, 89, 16))
        # self.radioButton_4.setObjectName("radioButton_4")

        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, "")

        self.groups_up = QButtonGroup()

        self.groups_up.addButton(self.outer_y, 11)
        self.groups_up.addButton(self.outer_x, 21)

        self.texttime = QtWidgets.QLCDNumber(self.tab)
        self.texttime.setGeometry(QtCore.QRect(0, 0, 500, 30))
        self.texttime.setMouseTracking(False)
        self.texttime.setDigitCount(19)
        self.texttime.setMode(QLCDNumber.Dec)
        self.texttime.setSegmentStyle(QLCDNumber.Flat)
        self.texttime.setObjectName("texttime")

        self.pdf = QtWidgets.QPushButton(self.tab)
        self.pdf.setObjectName("btn_chooseMutiFile")
        self.pdf.setText("pdf文本提取")
        self.pdf.setGeometry(QtCore.QRect(700, 100, 200, 40))

        self.pdf_show = QtWidgets.QTextBrowser(self.tab)
        self.pdf_show.setGeometry(QtCore.QRect(650, 150, 300, 500))
        self.pdf_show.setObjectName("y_text")

        self.weather = QtWidgets.QTextBrowser(self.tab)
        self.weather.setGeometry(QtCore.QRect(50, 300, 600, 200))
        self.weather.setObjectName("weather")

        self.winIconPix = QPixmap(16, 16)
        self.setWindowIcon(QIcon('mg.ico'))

        self.retranslateUi(Dialog)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "TOOLS"))
        Dialog.setWindowIcon(QIcon('mg.ico'))
        self.outers.setText(_translate("Dialog", "全连接"))
        self.outer_y.setText(_translate("Dialog", "横向"))
        self.outer_x.setText(_translate("Dialog", "竖向"))

        # self.pushButton_2.setText(_translate("Dialog", "交集"))
        # self.radioButton_3.setText(_translate("Dialog", "横向"))
        # self.radioButton_4.setText(_translate("Dialog", "横向"))

        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),
                                  _translate("Tool", "主页"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),
                                  _translate("Dialog", "。。。"))
        self.outers.clicked.connect(self.Chose_file)
        self.outers.clicked.connect(
            lambda: Dialog.yunxing(direction, 'outer',
                                   self.show_files.toPlainText().split()))

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.showtime)

        self.timer.start()

        self.pdf.clicked.connect(self.run_pdf_parse)
        self.Function_outer()
        self.Css()
        self.run_spider()

    def Function_outer(self):
        """
        槽函数挂载函数
        :return:
        """

        # self.outers.clicked.connect(self.Chose_file)
        self.groups_up.buttonClicked.connect(self.Chose_types)

    def Css(self):
        self.tab.setStyleSheet("#tab{background-color:#012456;}")
        self.tab_2.setStyleSheet("#tab_2{background-color:#012456;}")
        self.tabWidget.setStyleSheet(
            "QTabBar{background-color:#333300;outline:solid 2px;}QTabBar::tab{border-bottom-color:#C2C7CB;min-width: "
            "150px;border-right:2px solid black;border-style: outset;min-height: 40px;"
            "color:white;background-color:#4169E1;}QTabBar::tab:selected{background-color: white;"
            "color:green;border-top-right-radius:10px;border-top-left-radius:10px;border:none}QTabBar::tab:first{margin-left:20px;}"
            "QTabBar::tab:hover:!selected{color:red;background-color:black;}")
        self.outers.setStyleSheet(
            'QPushButton{background-Color:#7FFF00;border-radius: 10px;border: 2px solid green;}QPushButton:hover{color:red;background-color:black;}'
        )
        self.outer_y.setStyleSheet("color:white")
        self.outer_x.setStyleSheet("color:white")
        self.show_files.setStyleSheet(
            "background:transparent;border-style:outset;color:#FF8C00;border-color:#FFF5EE;"
        )
        # self.pushButton_2.setStyleSheet(
        #     'QPushButton{background-Color:#7FFF00;border-radius: 10px;border: 2px solid green;}QPushButton:hover{color:red;background-color:black;}')
        self.pdf.setStyleSheet(
            'QPushButton{background-Color:#7FFF00;border-radius: 10px;border: 2px solid green;}QPushButton:hover{color:red;background-color:black;}'
        )
        self.pdf_show.setStyleSheet(
            "background:transparent;border-style:outset;color:#FF8C00;border-color:#FFF5EE;font-size:20px;"
        )

    def showtime(self):
        """
        显示时间模块
        :return: None
        """
        self.dateEdit = QDateTimeEdit(QDateTime.currentDateTime(), self)
        self.dateEdit.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
        test = self.dateEdit.text()
        # self.texttime.setText(test)
        self.texttime.display(test)
        self.texttime.setStyleSheet(
            'font: italic 1px \"宋体\";border-width:0;border-style:outset;color:#DC143C;font-size:1px;'
        )

    def Chose_file(self):
        """
        选择多个文件
        :return:
        """
        files, filetype = QFileDialog.getOpenFileNames(self, "选择文件", self.cwd,
                                                       "Excle (*.xlsx);;")
        if len(files) == 0:
            return
        for i in files:
            self.show_files.append(i)

        return

    def Chose_types(self):
        """
        选择合并类型函数
        :return:
        """
        sender = self.sender()
        global direction
        if sender == self.groups_up:
            if self.groups_up.checkedId() == 11:
                # print('chosE函数',sender)
                direction = 1

            elif self.groups_up.checkedId() == 21:

                direction = 0
        return

    def run_pdf_parse(self):
        """
        pdf转换模块(后期优化,放进子进程模块)
        :return: 同文件名word版本.eg:文件.pdf --- 文件.doc
        """
        self.pdf_show.clear()
        files, filetype = QFileDialog.getOpenFileNames(self, "选择文件", self.cwd,
                                                       "PDF Files (*.pdf);;")

        if len(files) == 0:
            return

        for file in files:
            texts = readPDF(file)
            self.pdf_show.append(texts)
        return

    def run_spider(self):
        result = spider_weath()
        # ip = get_host_ip()
        # QMessageBox.question(self, 'HI', '来自 %s %s %s的你,你好吖!'%(result[0], result[1], result[2]),
        #                      QMessageBox.Yes, QMessageBox.Yes)
        # self.weather.setHtml(
        #     " &nbsp;<font color='red' >📍&nbsp;</font>:%s %s %s <br /> <font color='#FF8C00' >&nbsp;➤&nbsp;</font>:%s <br /> &nbsp;"
        #     "<font color='#FF4500' >☎&nbsp;</font>:%s" % (
        #         result[0], result[1], result[2], result[3], 'uu'))

        self.weather.setFont(QFont("Mongolian Baiti", 10, QFont.Bold))
        self.weather.setStyleSheet(
            "background:transparent;border-width:0;border-style:outset;color:white"
        )
        # self.weather.setHtml("<font color='#FF8C00' >555</font>" + result[10] + "  " + result[11])
        self.weather.setFont(QFont("Mongolian Baiti", 10, QFont.Bold))
        self.weather.setStyleSheet(
            "background:transparent;border-width:0;border-style:outset;color:white"
        )
        # -----------------------------------------------------------------------------------------
        self.weather.setText("%s°" % result[4])  # 温度
        self.weather.setFont(QFont("Mongolian Baiti", 40, QFont.Bold))
        self.weather.setStyleSheet(
            "background:transparent;border-width:0;border-style:outset;color:	white"
        )

        # self.textBrowser_5.setText("")  # 温度
        # self.textBrowser_5.setFont(QFont("Mongolian Baiti", 15, QFont.Bold))
        # self.textBrowser_5.setStyleSheet("background:transparent;border-width:0;border-style:outset;color:	white")

        self.weather.setHtml(
            "<font color='#FF8C00' >%s %s</font><br/> <font color='green' >湿度%s%% </font><br/> %s %s%s级 %s <br/> <font color='green' >%s</font><br/>"
            % (result[0], result[1], result[5], result[7], result[8],
               result[6], result[9], result[-1]))  # 温度
        self.weather.setFont(QFont("Mongolian Baiti", 15, QFont.Bold))
        self.weather.setStyleSheet(
            "background:transparent;border-width:0;border-style:outset;color:	white"
        )
        return
Exemplo n.º 36
0
class FileDialogWizardDialog(QDialog, Ui_FileDialogWizardDialog):
    """
    Class implementing the color dialog wizard dialog.
    
    It displays a dialog for entering the parameters for the
    E5FileDialog or QFileDialog code generator.
    """
    def __init__(self, dialogVariant, parent=None):
        """
        Constructor
        
        @param dialogVariant variant of the file dialog to be generated
            (-1 = E5FileDialog, 0 = unknown, 4 = PyQt4, 5 = PyQt5)
        @type int
        @param parent parent widget
        @type QWidget
        """
        super(FileDialogWizardDialog, self).__init__(parent)
        self.setupUi(self)

        self.eStartWithCompleter = E5FileCompleter(self.eStartWith)
        self.eWorkDirCompleter = E5DirCompleter(self.eWorkDir)

        self.__dialogVariant = dialogVariant

        self.__typeButtonsGroup = QButtonGroup(self)
        self.__typeButtonsGroup.setExclusive(True)
        self.__typeButtonsGroup.addButton(self.rOpenFile, 1)
        self.__typeButtonsGroup.addButton(self.rOpenFiles, 2)
        self.__typeButtonsGroup.addButton(self.rSaveFile, 3)
        self.__typeButtonsGroup.addButton(self.rfOpenFile, 11)
        self.__typeButtonsGroup.addButton(self.rfOpenFiles, 12)
        self.__typeButtonsGroup.addButton(self.rfSaveFile, 13)
        self.__typeButtonsGroup.addButton(self.rOpenFileUrl, 21)
        self.__typeButtonsGroup.addButton(self.rOpenFileUrls, 22)
        self.__typeButtonsGroup.addButton(self.rSaveFileUrl, 23)
        self.__typeButtonsGroup.addButton(self.rDirectory, 30)
        self.__typeButtonsGroup.addButton(self.rDirectoryUrl, 31)
        self.__typeButtonsGroup.buttonClicked[int].connect(
            self.__toggleInitialFilterAndResult)
        self.__toggleInitialFilterAndResult(1)

        self.__dialogVariant = dialogVariant
        if self.__dialogVariant == -1:
            self.pyqtComboBox.addItems(["eric"])
            self.setWindowTitle(self.tr("E5FileDialog Wizard"))
            self.pyqtComboBox.setCurrentIndex(0)
            self.pyqtComboBox.setEnabled(False)
        else:
            self.pyqtComboBox.addItems(["PyQt5", "PyQt4"])
            self.setWindowTitle(self.tr("QFileDialog Wizard"))
            if self.__dialogVariant == 5:
                self.pyqtComboBox.setCurrentIndex(0)
            elif self.__dialogVariant == 4:
                self.pyqtComboBox.setCurrentIndex(1)
            else:
                self.pyqtComboBox.setCurrentIndex(0)

        self.rSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rfSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rSaveFileUrl.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rDirectory.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.rDirectoryUrl.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cStartWith.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cWorkDir.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cFilters.toggled[bool].connect(self.__toggleGroupsAndTest)

        self.bTest = self.buttonBox.addButton(self.tr("Test"),
                                              QDialogButtonBox.ActionRole)

        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())

    def __adjustOptions(self, options):
        """
        Private method to adjust the file dialog options.
        
        @param options file dialog options (QFileDialog.Options)
        @return modified options (QFileDialog.Options)
        """
        if Globals.isLinuxPlatform():
            options |= QFileDialog.DontUseNativeDialog
        return options

    @pyqtSlot(str)
    def on_pyqtComboBox_currentIndexChanged(self, txt):
        """
        Private slot to setup the dialog for the selected PyQt variant.
        
        @param txt text of the selected combo box entry (string)
        """
        self.rfOpenFile.setEnabled(txt in ("eric", "PyQt4"))
        self.rfOpenFiles.setEnabled(txt in ("eric", "PyQt4"))
        self.rfSaveFile.setEnabled(txt in ("eric", "PyQt4"))

        self.rOpenFileUrl.setEnabled(txt == "PyQt5")
        self.rOpenFileUrls.setEnabled(txt == "PyQt5")
        self.rSaveFileUrl.setEnabled(txt == "PyQt5")
        self.rDirectoryUrl.setEnabled(txt == "PyQt5")

        if txt == "PyQt5":
            if self.rfOpenFile.isChecked():
                self.rOpenFile.setChecked(True)
            elif self.rfOpenFiles.isChecked():
                self.rOpenFiles.setChecked(True)
            elif self.rfSaveFile.isChecked():
                self.rSaveFile.setChecked(True)
        else:
            if self.rOpenFileUrl.isChecked():
                self.rOpenFile.setChecked(True)
            if self.rOpenFileUrls.isChecked():
                self.rOpenFiles.setChecked(True)
            if self.rSaveFileUrl.isChecked():
                self.rSaveFile.setChecked(True)
            if self.rDirectoryUrl.isChecked():
                self.rDirectory.setChecked(True)

        if txt == "eric":
            self.__dialogVariant = -1
        elif txt == "PyQt5":
            self.__dialogVariant = 5
        elif txt == "PyQt4":
            self.__dialogVariant = 4
        else:
            # default is PyQt5
            self.__dialogVariant = 5

        self.__toggleInitialFilterAndResult(
            self.__typeButtonsGroup.checkedId())

    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.bTest:
            self.on_bTest_clicked()

    @pyqtSlot()
    def on_bTest_clicked(self):
        """
        Private method to test the selected options.
        """
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            QFileDialog.getOpenFileName(None, self.eCaption.text(),
                                        self.eStartWith.text(),
                                        self.eFilters.text(),
                                        self.eInitialFilter.text(), options)
        elif self.rOpenFileUrl.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            try:
                QFileDialog.getOpenFileUrl(None, self.eCaption.text(),
                                           QUrl(self.eStartWith.text()),
                                           self.eFilters.text(),
                                           self.eInitialFilter.text(), options,
                                           self.schemesEdit.text().split())
            except TypeError:
                # PyQt5 < 5.13.0 contains an error
                QFileDialog.getOpenFileUrl(None, self.eCaption.text(),
                                           self.eStartWith.text(),
                                           self.eFilters.text(),
                                           self.eInitialFilter.text(), options,
                                           self.schemesEdit.text().split())
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            QFileDialog.getOpenFileNames(None, self.eCaption.text(),
                                         self.eStartWith.text(),
                                         self.eFilters.text(),
                                         self.eInitialFilter.text(), options)
        elif self.rOpenFileUrls.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            try:
                QFileDialog.getOpenFileUrls(None, self.eCaption.text(),
                                            QUrl(self.eStartWith.text()),
                                            self.eFilters.text(),
                                            self.eInitialFilter.text(),
                                            options,
                                            self.schemesEdit.text().split())
            except TypeError:
                # PyQt5 < 5.13.0 contains an error
                QFileDialog.getOpenFileUrls(None, self.eCaption.text(),
                                            self.eStartWith.text(),
                                            self.eFilters.text(),
                                            self.eInitialFilter.text(),
                                            options,
                                            self.schemesEdit.text().split())
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            QFileDialog.getSaveFileName(None, self.eCaption.text(),
                                        self.eStartWith.text(),
                                        self.eFilters.text(),
                                        self.eInitialFilter.text(), options)
        elif self.rSaveFileUrl.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            try:
                QFileDialog.getSaveFileUrl(None, self.eCaption.text(),
                                           QUrl(self.eStartWith.text()),
                                           self.eFilters.text(),
                                           self.eInitialFilter.text(), options,
                                           self.schemesEdit.text().split())
            except TypeError:
                # PyQt5 < 5.13.0 contains an error
                QFileDialog.getSaveFileUrl(None, self.eCaption.text(),
                                           self.eStartWith.text(),
                                           self.eFilters.text(),
                                           self.eInitialFilter.text(), options,
                                           self.schemesEdit.text().split())
        elif self.rDirectory.isChecked():
            options = QFileDialog.Options()
            if not self.cSymlinks.isChecked():
                options |= QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            if self.cDirOnly.isChecked():
                options |= QFileDialog.Options(QFileDialog.ShowDirsOnly)
            else:
                options |= QFileDialog.Options(QFileDialog.Option(0))
            options = self.__adjustOptions(options)
            QFileDialog.getExistingDirectory(None, self.eCaption.text(),
                                             self.eWorkDir.text(), options)
        elif self.rDirectoryUrl.isChecked():
            options = QFileDialog.Options()
            if not self.cSymlinks.isChecked():
                options |= QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            if self.cDirOnly.isChecked():
                options |= QFileDialog.Options(QFileDialog.ShowDirsOnly)
            else:
                options |= QFileDialog.Options(QFileDialog.Option(0))
            options = self.__adjustOptions(options)
            try:
                QFileDialog.getExistingDirectoryUrl(
                    None, self.eCaption.text(), QUrl(self.eWorkDir.text()),
                    options,
                    self.schemesEdit.text().split())
            except TypeError:
                # PyQt5 < 5.13.0 contains an error
                QFileDialog.getExistingDirectoryUrl(
                    None, self.eCaption.text(), self.eWorkDir.text(), options,
                    self.schemesEdit.text().split())

    def __toggleConfirmCheckBox(self):
        """
        Private slot to enable/disable the confirmation check box.
        """
        self.cConfirmOverwrite.setEnabled(self.rSaveFile.isChecked()
                                          or self.rfSaveFile.isChecked()
                                          or self.rSaveFileUrl.isChecked())

    def __toggleGroupsAndTest(self):
        """
        Private slot to enable/disable certain groups and the test button.
        """
        if self.rDirectory.isChecked() or self.rDirectoryUrl.isChecked():
            self.filePropertiesGroup.setEnabled(False)
            self.dirPropertiesGroup.setEnabled(True)
            self.bTest.setDisabled(self.cWorkDir.isChecked())
        else:
            self.filePropertiesGroup.setEnabled(True)
            self.dirPropertiesGroup.setEnabled(False)
            self.bTest.setDisabled(self.cStartWith.isChecked()
                                   or self.cFilters.isChecked())

    def __toggleInitialFilterAndResult(self, checkedId):
        """
        Private slot to enable/disable the initial filter elements and the
        results entries.
        
        @param checkedId id of the clicked button (integer)
        """
        enable = (
            (self.__dialogVariant in (-1, 4) and checkedId in [11, 12, 13]) or
            (self.__dialogVariant == 5 and checkedId in [1, 2, 3, 21, 22, 23]))

        self.lInitialFilter.setEnabled(enable)
        self.eInitialFilter.setEnabled(enable)
        self.cInitialFilter.setEnabled(enable)

        self.lFilterVariable.setEnabled(enable)
        self.eFilterVariable.setEnabled(enable)

        self.urlPropertiesGroup.setEnabled(checkedId in (21, 22, 23, 31))

    def getCode(self, indLevel, indString):
        """
        Public method to get the source code for Qt4 and Qt5.
        
        @param indLevel indentation level (int)
        @param indString string used for indentation (space or tab) (string)
        @return generated code (string)
        """
        # calculate our indentation level and the indentation string
        il = indLevel + 1
        istring = il * indString
        estring = os.linesep + indLevel * indString

        # now generate the code
        if self.parentSelf.isChecked():
            parent = "self"
        elif self.parentNone.isChecked():
            parent = "None"
        elif self.parentOther.isChecked():
            parent = self.parentEdit.text()
            if parent == "":
                parent = "None"

        # prepare the result variables
        nameVariable = self.eNameVariable.text()
        if not nameVariable:
            if self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFile, self.rfOpenFile, self.rSaveFile,
                    self.rfSaveFile
            ]:
                nameVariable = "fileName"
            elif self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFiles, self.rfOpenFiles
            ]:
                nameVariable = "fileNames"
            elif self.__typeButtonsGroup.checkedButton() == self.rDirectory:
                nameVariable = "dirName"
            else:
                nameVariable = "res"
        filterVariable = self.eFilterVariable.text()
        if not filterVariable:
            if ((self.__dialogVariant in (-1, 4)
                 and self.__typeButtonsGroup.checkedButton()
                 in [self.rfOpenFile, self.rfOpenFiles, self.rfSaveFile])
                    or (self.__dialogVariant == 5
                        and self.__typeButtonsGroup.checkedButton()
                        in [self.rOpenFile, self.rOpenFiles, self.rSaveFile])):
                filterVariable = ", selectedFilter"
            else:
                filterVariable = ""
        else:
            filterVariable = ", " + filterVariable

        if self.__dialogVariant == -1:
            dialogType = "E5FileDialog"
        else:
            dialogType = "QFileDialog"

        code = '{0}{1} = {2}.'.format(nameVariable, filterVariable, dialogType)
        if (self.rOpenFile.isChecked() or self.rfOpenFile.isChecked()
                or self.rOpenFileUrl.isChecked()):
            if self.rOpenFile.isChecked():
                code += 'getOpenFileName({0}{1}'.format(os.linesep, istring)
            elif self.rOpenFileUrl.isChecked():
                code += 'getOpenFileUrl({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if self.rOpenFileUrl.isChecked():
                if not self.eStartWith.text():
                    code += 'QUrl(),{0}{1}'.format(os.linesep, istring)
                else:
                    if self.cStartWith.isChecked():
                        fmt = '{0},{1}{2}'
                    else:
                        fmt = 'QUrl("{0}"),{1}{2}'
                    code += fmt.format(self.eStartWith.text(), os.linesep,
                                       istring)
            else:
                if not self.eStartWith.text():
                    code += '"",{0}{1}'.format(os.linesep, istring)
                else:
                    if self.cStartWith.isChecked():
                        fmt = '{0},{1}{2}'
                    else:
                        fmt = '"{0}",{1}{2}'
                    code += fmt.format(self.eStartWith.text(), os.linesep,
                                       istring)
            if self.eFilters.text() == "":
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFile.isChecked() or self.__dialogVariant == 5:
                if self.eInitialFilter.text() == "":
                    initialFilter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    initialFilter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, initialFilter)
            if not self.cSymlinks.isChecked():
                code += ',{0}{1}{2}.Options({2}.DontResolveSymlinks)'.format(
                    os.linesep, istring, dialogType)
            if self.rOpenFileUrl.isChecked() and bool(self.schemesEdit.text()):
                code += ',{0}{1}{2}'.format(os.linesep, istring,
                                            self.__prepareSchemesList())
            code += '){0}'.format(estring)
        elif (self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked()
              or self.rOpenFileUrls.isChecked()):
            if self.rOpenFiles.isChecked():
                code += 'getOpenFileNames({0}{1}'.format(os.linesep, istring)
            elif self.rOpenFileUrls.isChecked():
                code += 'getOpenFileUrls({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNamesAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if self.rOpenFileUrls.isChecked():
                if not self.eStartWith.text():
                    code += 'QUrl(),{0}{1}'.format(os.linesep, istring)
                else:
                    if self.cStartWith.isChecked():
                        fmt = '{0},{1}{2}'
                    else:
                        fmt = 'QUrl("{0}"),{1}{2}'
                    code += fmt.format(self.eStartWith.text(), os.linesep,
                                       istring)
            else:
                if not self.eStartWith.text():
                    code += '"",{0}{1}'.format(os.linesep, istring)
                else:
                    if self.cStartWith.isChecked():
                        fmt = '{0},{1}{2}'
                    else:
                        fmt = '"{0}",{1}{2}'
                    code += fmt.format(self.eStartWith.text(), os.linesep,
                                       istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFiles.isChecked() or self.__dialogVariant == 5:
                if self.eInitialFilter.text() == "":
                    initialFilter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    initialFilter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, initialFilter)
            if not self.cSymlinks.isChecked():
                code += ',{0}{1}{2}.Options({2}.DontResolveSymlinks)'.format(
                    os.linesep, istring, dialogType)
            if (self.rOpenFileUrls.isChecked()
                    and bool(self.schemesEdit.text())):
                code += ',{0}{1}{2}'.format(os.linesep, istring,
                                            self.__prepareSchemesList())
            code += '){0}'.format(estring)
        elif (self.rSaveFile.isChecked() or self.rfSaveFile.isChecked()
              or self.rSaveFileUrl.isChecked()):
            if self.rSaveFile.isChecked():
                code += 'getSaveFileName({0}{1}'.format(os.linesep, istring)
            elif self.rSaveFileUrl.isChecked():
                code += 'getSaveFileUrl({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getSaveFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if self.rSaveFileUrl.isChecked():
                if not self.eStartWith.text():
                    code += 'QUrl(),{0}{1}'.format(os.linesep, istring)
                else:
                    if self.cStartWith.isChecked():
                        fmt = '{0},{1}{2}'
                    else:
                        fmt = 'QUrl("{0}"),{1}{2}'
                    code += fmt.format(self.eStartWith.text(), os.linesep,
                                       istring)
            else:
                if not self.eStartWith.text():
                    code += '"",{0}{1}'.format(os.linesep, istring)
                else:
                    if self.cStartWith.isChecked():
                        fmt = '{0},{1}{2}'
                    else:
                        fmt = '"{0}",{1}{2}'
                    code += fmt.format(self.eStartWith.text(), os.linesep,
                                       istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfSaveFile.isChecked() or self.__dialogVariant == 5:
                if self.eInitialFilter.text() == "":
                    initialFilter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    initialFilter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, initialFilter)
            if ((not self.cSymlinks.isChecked())
                    or (not self.cConfirmOverwrite.isChecked())):
                code += ',{0}{1}{2}.Options('.format(os.linesep, istring,
                                                     dialogType)
                if not self.cSymlinks.isChecked():
                    code += '{0}.DontResolveSymlinks'.format(dialogType)
                if ((not self.cSymlinks.isChecked())
                        and (not self.cConfirmOverwrite.isChecked())):
                    code += ' | '
                if not self.cConfirmOverwrite.isChecked():
                    code += '{0}.DontConfirmOverwrite'.format(dialogType)
                code += ')'
            if (self.rSaveFileUrl.isChecked()
                    and bool(self.schemesEdit.text())):
                code += ',{0}{1}{2}'.format(os.linesep, istring,
                                            self.__prepareSchemesList())

            code += '){0}'.format(estring)
        elif self.rDirectory.isChecked() or self.rDirectoryUrl.isChecked():
            if self.rDirectory.isChecked():
                code += 'getExistingDirectory({0}{1}'.format(
                    os.linesep, istring)
            else:
                code += 'getExistingDirectoryUrl({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(self.eCaption.text(),
                                                       os.linesep, istring)
            if self.rDirectoryUrl.isChecked():
                if not self.eWorkDir.text():
                    code += 'QUrl()'
                else:
                    if self.cWorkDir.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'QUrl("{0}")'
                    code += fmt.format(self.eWorkDir.text())
            else:
                if not self.eWorkDir.text():
                    code += '""'
                else:
                    if self.cWorkDir.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = '"{0}"'
                    code += fmt.format(self.eWorkDir.text())
            code += ',{0}{1}{2}.Options('.format(os.linesep, istring,
                                                 dialogType)
            if not self.cSymlinks.isChecked():
                code += '{0}.DontResolveSymlinks | '.format(dialogType)
            if self.cDirOnly.isChecked():
                code += '{0}.ShowDirsOnly'.format(dialogType)
            else:
                code += '{0}.Option(0)'.format(dialogType)
            code += ')'
            if self.rDirectoryUrl.isChecked():
                code += ',{0}{1}{2}'.format(os.linesep, istring,
                                            self.__prepareSchemesList())
            code += '){0}'.format(estring)

        return code

    def __prepareSchemesList(self):
        """
        Private method to prepare the list of supported schemes.
        
        @return string representation of the supported schemes
        @rtype str
        """
        return repr(self.schemesEdit.text().strip().split())
Exemplo n.º 37
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        
        self.save_location = None
        self.layout = QVBoxLayout()

        self.create_credential_boxes()
        self.create_subsession_box()
        self.create_plot_type_selection()
        self.create_mode_selection()
        self.create_spinbox_settings()
        self.create_title_box()
        self.create_run_button()
        self.create_progress_bar()

        # Window settings
        self.setLayout(self.layout)
        self.setFixedSize(800, 600)

    def create_credential_boxes(self):
        self.email = QLineEdit()
        self.password = QLineEdit()
        self.password.setEchoMode(QLineEdit.Password)

        user_pass = credentials.retrieve('iracing')
        self.email.setPlaceholderText("Email")
        self.password.setPlaceholderText("Password")
        if user_pass is not None:
            username, password = user_pass
            self.email.setText(username)
            self.password.setText(password)

        self.layout.addWidget(self.email)
        self.layout.addWidget(self.password)

    def create_subsession_box(self):
        self.subsession = QLineEdit()
        self.subsession.setPlaceholderText("Subsession ID (ie. 27983466)")
        self.subsession.setToolTip("Same as the split number when hovering on results icon. Also found in URL of results page.")
        self.layout.addWidget(self.subsession)

    def create_title_box(self):
        self.title = QLineEdit()
        self.title.setPlaceholderText("Enter plot title")
        self.layout.addWidget(self.title)


    def create_plot_type_selection(self):
        radio_buttons = [QRadioButton("Swarm Plot"), QRadioButton("Violin Plot")]
        radio_buttons[0].setChecked(True)  
        button_layout = QHBoxLayout()
        self.plot_type_group = QButtonGroup()

        for index, button in enumerate(radio_buttons):
            button_layout.addWidget(button)
            self.plot_type_group.addButton(button, index)

        self.layout.addLayout(button_layout)

    def create_mode_selection(self):
        radio_buttons = [QRadioButton("Save to file"), QRadioButton("Interactive")]
        button_layout = QHBoxLayout()
        self.mode_group = QButtonGroup()

        radio_buttons[0].setChecked(True)
        for index, button in enumerate(radio_buttons):
            button_layout.addWidget(button)
            self.mode_group.addButton(button, index)

        self.layout.addLayout(button_layout)

    def create_spinbox_settings(self):
        self.max_drivers = QSpinBox()
        self.max_drivers.setValue(10)
        self.outlier_delta = QSpinBox()
        self.outlier_delta.setValue(3)
        self.yaxis_delta = QSpinBox()
        self.yaxis_delta.setValue(0)

        info = ["Max Drivers", "Outlier Delta", "Y-Axis Delta"]
        options = [self.max_drivers, self.outlier_delta, self.yaxis_delta]
        los = [QHBoxLayout(), QHBoxLayout(), QHBoxLayout()]
        for i, opt, lo in zip(info, options, los):
            lo.addWidget(QLabel(i))
            lo.addWidget(opt)
            self.layout.addLayout(lo)
    
    def create_run_button(self):
        self.run_button = QPushButton('Run!')
        self.run_button.clicked.connect(self.run)
        self.layout.addWidget(self.run_button)
        self.layout.setAlignment(self.run_button, Qt.AlignHCenter)
    
    def create_progress_bar(self):
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.layout.addWidget(self.progress_bar)

    
    def query_save_location(self):
        chosen_filename = QFileDialog.getSaveFileName(self, 'Choose file location for pace graph', os.getcwd(), 'PNG (*.png)')[0]
        self.save_location = Path(chosen_filename)


    def warn(self, message):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText(message)
        msg.setWindowTitle("Error!")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()


    def run(self):
        if self.mode_group.checkedId() == 0:
            self.query_save_location()
            if str(self.save_location) == '.':
                self.warn("You must select save location if using 'Save to file' mode")
                return

        config = WorkerConfig(
            self.subsession.text(),
            self.email.text(),
            self.password.text(),
            self.max_drivers.value(),
            self.outlier_delta.value(),
            self.yaxis_delta.value() if self.yaxis_delta.value() != 0 else None,
            self.mode_group.checkedId() == 1,
            self.plot_type_group.checkedId() == 1,
            self.title.text(),
            self.save_location
        )

        self.worker = Worker(config)
        self.worker.finished.connect(self.worker_finished)
        self.worker.my_signal.connect(self.warn)
        self.worker.plot_ready.connect(self.show_plot)
        self.run_button.setEnabled(False)

        self.animation = QPropertyAnimation(self.progress_bar, b"value")
        self.animation.setDuration(4000)
        self.animation.setStartValue(0)
        self.animation.setEndValue(98)
        self.animation.setEasingCurve(QEasingCurve.OutExpo)
        self.animation.start()

        self.worker.start()


    def worker_finished(self):
        self.progress_bar.setValue(100)
        self.animation.stop()
        self.run_button.setEnabled(True)
        

    def show_plot(self, config, results):
        # matplotlib prefers to be on main thread, which is why we don't plot in the worker

        self.run_button.setEnabled(False)

        try:
            swarm = LapSwarm(results, config.max_drivers, config.outlier_delta)
        except EmptyResults:
            self.warn("No subsession results, please check subsession ID.")
            return
        
        ax = swarm.create_plot(config.title, config.violin, config.yaxis_delta)

        if config.interactive:
            interactive_plot(ax)
        else:
            file_path = str(config.save_location)
            export_plot(ax, file_path)

        self.run_button.setEnabled(True)
Exemplo n.º 38
0
class DMSUnitWgt(QWidget):
    unitTabDataWdg = None
    decorateTypeWgt: DMSDecorateTypeWgt = None
    decorateDataWgt: DMSDecorateDataWgt = None

    currentBuilding: DB_Building = None
    unitDict: dict = {}

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

        self.initUI()
        self.initTrigger()

    def initUI(self):
        self.ui = Ui_UnitWgt()
        self.ui.setupUi(self)
        self.ui.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.decorateTypeWgt = DMSDecorateTypeWgt(self)
        self.decorateDataWgt = DMSDecorateDataWgt(self)
        count = self.ui.verticalLayout.count()
        self.ui.verticalLayout.addWidget(self.decorateDataWgt)
        self.groupButton = QButtonGroup(self)

    def unitChanged(self):
        # self.decorateDataWgt.
        pass

    def initTrigger(self):
        self.ui.pBtnAddUnit.clicked.connect(self.addUnit)
        self.ui.pBtnDleleteUnit.clicked.connect(self.deleteUnit)
        self.groupButton.buttonClicked.connect(self.unitChanged)

    def setCurrentBuilding(self, building_id):
        if self.currentBuilding and self.currentBuilding.id == building_id:
            return
        self.currentBuilding = None
        building: DB_Building = dmsDatabase().getRecordById(
            DB_Building, building_id)
        if building is None:
            self.updateUiEnabled()
            return
        self.currentBuilding = building
        self.clearUnit()
        self.loadUnit()
        self.updateUiEnabled()

    def getCurrentUnit(self):
        pass

    def addUnit(self):
        unit = newUnit(self.currentBuilding)
        unit_tool_btn = self.createToolButton(unit)
        unit_tool_btn.setChecked(True)

    def deleteUnit(self):
        _id = self.groupButton.checkedId()
        _button = self.groupButton.checkedButton()

        self.groupButton.removeButton(_button)
        delete(_button)
        customDeleteRecord(DB_Building_Unit, _id)
        self.updateUiEnabled()

    def createToolButton(self, business_unit) -> QToolButton:
        if business_unit is None:
            return
        unit_tool_btn = QToolButton()
        unit_tool_btn.setText(business_unit.name)
        unit_tool_btn.setCheckable(True)
        count = self.ui.horizontalLayout.count()
        self.ui.horizontalLayout.insertWidget(count - 3, unit_tool_btn)
        self.unitDict[business_unit.id] = unit_tool_btn
        self.groupButton.addButton(unit_tool_btn, business_unit.id)

        return unit_tool_btn

    def loadUnit(self):
        if self.currentBuilding is None:
            return
        unit_list = dmsDatabase().getTableList(
            DB_Building_Unit, "building_id = " + str(self.currentBuilding.id))
        if len(unit_list) == 0:
            return
        first_item: QToolButton = None
        for item in unit_list:
            unit_tool_btn = self.createToolButton(item)
            if first_item is None:
                first_item = unit_tool_btn
        first_item.setChecked(True)

    def clearUnit(self):
        if len(self.unitDict) == 0:
            return
        tool_btn_list = self.unitDict.values()

        for var in self.groupButton.buttons():
            self.groupButton.removeButton(var)

        for item in tool_btn_list:
            self.ui.horizontalLayout.removeWidget(item)
            delete(item)
        self.unitDict.clear()

    def updateUnitDate(self, currentBuildingID, previousBuildingID=None):
        """
        槽函数
        :param currentBuildingID:
        :param previousBuildingID:
        :return:
        """
        pass
        # # Todo 待梳理嵌套关系
        # print(currentBuildingID, previousBuildingID)
        # dateTableWidget = self.unitTabWdg.currentWidget()
        # dateTableWidget = DMSDecorateDataWgt()
        # # decorateTaskList: List[DB_Decorate_Type] = dmsProject().getTableList(DB_Decorate_Type, filter_str=currentBuildingID).orderBy(
        # #     DB_Decorate_Type.order)
        # decorateTaskList: List[DB_Decorate_Type] = dmsDatabase().getTableList(DB_Decorate_Type)
        # tableHeaderList = [task.name for task in decorateTaskList]
        # dateTableWidget.setHorizontalHeaderLabels(tableHeaderList)

    def updateUiEnabled(self):
        enabled = False
        if len(self.unitDict) == 0:
            enabled = False
        else:
            enabled = True

        self.ui.pBtnDleleteUnit.setEnabled(enabled)
Exemplo n.º 39
0
class Example(QWidget):
    '''
    超多个密码结合
    '''
    def __init__(self):
        '''
        一些初始设置
        '''
        super().__init__()
        self.initUI()

    def initUI(self):
        '''
        界面初始设置
        '''
        self.resize(500, 300)
        self.setWindowTitle('关注微信公众号:学点编程吧--抽象按钮的学习3(QAbstractButton)')

        label1 = QLabel('密码输入区', self)
        label1.move(50, 50)

        label2 = QLabel('正确密码:321', self)
        label2.move(50, 200)

        label3 = QLabel('你输入的密码:', self)
        label3.move(50, 250)

        self.label4 = QLabel('   ', self)
        self.label4.move(150, 250)

        self.bt11 = QPushButton('1', self)
        self.bt12 = QPushButton('2', self)
        self.bt13 = QPushButton('3', self)
        self.bt21 = QPushButton('1', self)
        self.bt22 = QPushButton('2', self)
        self.bt23 = QPushButton('3', self)
        self.bt31 = QPushButton('1', self)
        self.bt32 = QPushButton('2', self)
        self.bt33 = QPushButton('3', self)

        self.bt11.setGeometry(150, 50, 40, 40)
        self.bt12.setGeometry(200, 50, 40, 40)
        self.bt13.setGeometry(250, 50, 40, 40)
        self.bt21.setGeometry(150, 100, 40, 40)
        self.bt22.setGeometry(200, 100, 40, 40)
        self.bt23.setGeometry(250, 100, 40, 40)
        self.bt31.setGeometry(150, 150, 40, 40)
        self.bt32.setGeometry(200, 150, 40, 40)
        self.bt33.setGeometry(250, 150, 40, 40)

        self.btg1 = QButtonGroup(self)  # 按钮组
        self.btg2 = QButtonGroup(self)
        self.btg3 = QButtonGroup(self)

        self.btg1.addButton(self.bt11, 1)  # 每个按钮组中每个按钮的id
        self.btg1.addButton(self.bt12, 2)
        self.btg1.addButton(self.bt13, 3)
        self.btg2.addButton(self.bt21, 1)
        self.btg2.addButton(self.bt22, 2)
        self.btg2.addButton(self.bt23, 3)
        self.btg3.addButton(self.bt31, 1)
        self.btg3.addButton(self.bt32, 2)
        self.btg3.addButton(self.bt33, 3)

        self.bt11.setCheckable(True)
        self.bt12.setCheckable(True)
        self.bt13.setCheckable(True)
        self.bt21.setCheckable(True)
        self.bt22.setCheckable(True)
        self.bt23.setCheckable(True)
        self.bt31.setCheckable(True)
        self.bt32.setCheckable(True)
        self.bt33.setCheckable(True)

        self.show()

        self.pwd1, self.pwd2, self.pwd3 = '', '', ''
        # 3个密码初始化

        self.btg1.buttonClicked.connect(self.setPassword)
        self.btg2.buttonClicked.connect(self.setPassword)
        self.btg3.buttonClicked.connect(self.setPassword)

    def setPassword(self, pressed):
        sender = self.sender()
        if sender == self.btg1:
            self.pwd1 = str(self.btg1.checkedId())
        elif sender == self.btg2:
            self.pwd2 = str(self.btg2.checkedId())
        elif sender == self.btg3:
            self.pwd3 = str(self.btg3.checkedId())
        # 使用pwd1、pwd2、pwd3分别记录每个被选中按钮的id

        self.label4.setText(self.pwd1 + self.pwd2 + self.pwd3)

        if self.pwd1 + self.pwd2 + self.pwd3 == '321':
            QMessageBox.information(self, '提示', '恭喜,密码正确,可以进入!')
Exemplo n.º 40
0
    def request_safe_t_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{:d} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")

                def set_enabled():
                    from vialectrum.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))

                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())
Exemplo n.º 41
0
class Dimili(QMainWindow):

    def baslat(self, anaPencere):
        anaPencere.resize(600, 400)
        anaPencere.setWindowTitle("Dimili-Türkçe Sözlük")
        anaPencere.setFixedSize(600,400)

        icon =QIcon()
        icon.addPixmap(QPixmap("Dictionary.png"),QIcon.Normal,QIcon.Off)
        anaPencere.setWindowIcon(icon)
        zemin=QWidget(anaPencere)
        zemin.setGeometry(QRect(0,30,600,390))
        zemin.setStyleSheet("background-color:rgb(167, 196, 233);")
        self.araKutu = QLineEdit(anaPencere)
        self.araKutu.setGeometry(QRect(10, 80, 200, 20))

        self.araKutu.textChanged.connect(self.benzerKelimeler)


        self.kelimeGir = QLabel("Kelimeler:",anaPencere)
        self.kelimeGir.setGeometry(QRect(10, 110, 141, 21))

        self.kelimeGor = QLabel("Kelime Ara",anaPencere)
        self.kelimeGor.setGeometry(QRect(10, 30, 91, 16))
        self.harfGrup=QButtonGroup(anaPencere)
        aharf=QPushButton("â",anaPencere)
        aharf.setGeometry(QRect(10,50,25,25))
        eharf=QPushButton("é",anaPencere)
        eharf.setGeometry(QRect(30,50,25,25))

        self.DilGrup=QButtonGroup(anaPencere)
        self.Dil1 = QPushButton("Zazaca-Türkçe",anaPencere)
        self.Dil1.setGeometry(QRect(230, 80, 91, 23))
        self.Dil1.setCheckable(True)
        self.Dil1.setAutoExclusive(True)
        self.Dil1.setChecked(True)
        self.Dil1.setStyleSheet("background-color: rgb(102, 255, 0);")

        self.Dil2 = QPushButton("Türkçe-Zazaca",anaPencere)
        self.Dil2.setGeometry(QRect(330, 80, 91, 23))
        self.Dil2.setCheckable(True)
        self.Dil2.setAutoExclusive(True)
        self.Dil2.setStyleSheet("background-color: rgb(255, 94, 105);")

        self.DilGrup.addButton(self.Dil1,1)
        self.DilGrup.addButton(self.Dil2,2)
        self.DilGrup.buttonClicked[int].connect(self.dilSecme)
        self.kelimeListesi=QListWidget(anaPencere)
        self.kelimeListesi.setGeometry(QRect(10, 130, 191, 231))

        self.kelimeListesi.itemClicked.connect(self.kelimeAcikla)
        self.kelimeAnlam = QLabel("Kelimenin Anlamı:",anaPencere)
        self.kelimeAnlam.setGeometry(QRect(230, 110, 131, 21))

        self.cumleList1 = QListWidget(anaPencere)
        self.cumleList1.setGeometry(QRect(230, 130, 351, 51))

        self.ornekCumle1 = QLabel("Örnek Zazaca Cümle:",anaPencere)
        self.ornekCumle1.setGeometry(QRect(230, 200, 101, 21))

        self.cumleList2 = QListWidget(anaPencere)
        self.cumleList2.setGeometry(QRect(230, 220, 351, 51))

        self.ornekCumle2 = QLabel("Örnek Türkçe Cümle:",anaPencere)
        self.ornekCumle2.setGeometry(QRect(230, 290, 111, 16))

        self.cumleList3 = QListWidget(anaPencere)
        self.cumleList3.setGeometry(QRect(230, 310, 351, 51))




        self.anaMenu = QMenuBar(anaPencere)
        self.anaMenu.setGeometry(QRect(0, 0, 600, 21))

        self.menuDosya = QMenu("Dosya",self.anaMenu)

        self.menuDuzenle = QMenu("Düzenle",self.anaMenu)

        self.menuYardim = QMenu("Yardım",self.anaMenu)

        anaPencere.setMenuBar(self.anaMenu)

        self.durum = QStatusBar(zemin)
        anaPencere.setStatusBar(self.durum)
        self.durum.setStyleSheet("background-color:white")
        self.durum.showMessage("Hazır")

        self.cikis= QAction(QIcon("Exit.ico"),"&Çıkış",anaPencere)
        self.cikis.setShortcut("Ctrl+X")

        self.cikis.triggered.connect(anaPencere.close)

        self.actionHakkinda = QAction("Hakkında",anaPencere)
        self.actionHakkinda.triggered.connect(self.hakkinda)
        self.actionSecenekler = QAction("Seçenekler",anaPencere)

        self.menuDosya.addAction(self.cikis)
        self.menuDuzenle.addAction(self.actionSecenekler)
        self.menuYardim.addAction(self.actionHakkinda)
        self.anaMenu.addAction(self.menuDosya.menuAction())
        self.anaMenu.addAction(self.menuDuzenle.menuAction())
        self.anaMenu.addAction(self.menuYardim.menuAction())

    def kelimeAcikla(self):
        if self.DilGrup.checkedId()==1:
            self.cumleList1.clear()
            self.cumleList2.clear()
            self.cumleList3.clear()
            itemtext= [str(x.text()) for x in self.kelimeListesi.selectedItems()]
            for it in itemtext:
                itemtext=it
            self.im.execute("select Tur from DimTur where Zazaca=?",[itemtext])
            turliste=[tur[0] for tur in self.im.fetchall()]
            for tura in turliste:
                turliste=tura
            self.im.execute("select Turkce from DimTur where Zazaca=?",[itemtext])
            turkAnlam=[tur[0] for tur in self.im.fetchall()]
            for tr in turkAnlam:
                self.cumleList1.addItem(itemtext+"("+turliste+")"+" : "+tr)
            self.im.execute("select OrnekZazacaCumle from DimTur where Zazaca=?",[itemtext])
            ornekZaza=[zaza[0] for zaza in self.im.fetchall()]
            for za in ornekZaza:
                ornekZaza=za
            self.cumleList2.addItem(ornekZaza)
            self.im.execute("select OrnekTurkceCumle from DimTur where Zazaca=?",[itemtext])
            ornekTurk=[turk[0] for turk in self.im.fetchall()]
            for orn in ornekTurk:
                ornekTurk=orn
            self.cumleList3.addItem(ornekTurk)
        if self.DilGrup.checkedId()==2:
            self.cumleList1.clear()
            self.cumleList2.clear()
            self.cumleList3.clear()
            itemtext= [str(x.text()) for x in self.kelimeListesi.selectedItems()]
            for it in itemtext:
                itemtext=it
            self.im.execute("select Tur from DimTur where Turkce=?",[itemtext])
            turliste=[tur[0] for tur in self.im.fetchall()]
            for tura in turliste:
                turliste=tura
            self.im.execute("select Zazaca from DimTur where Turkce=?",[itemtext])
            zazaAnlam=[tur[0] for tur in self.im.fetchall()]
            for tr in zazaAnlam:
                self.cumleList1.addItem(itemtext+"("+turliste+")"+" : "+tr)
            self.im.execute("select OrnekZazacaCumle from DimTur where Turkce=?",[itemtext])
            ornekTurk=[turk[0] for turk in self.im.fetchall()]
            for orn in ornekTurk:
                ornekTurk=orn
            self.cumleList2.addItem(ornekTurk)
            self.im.execute("select OrnekTurkceCumle from DimTur where Turkce=?",[itemtext])
            ornekZaza=[zaza[0] for zaza in self.im.fetchall()]
            for za in ornekZaza:
                ornekZaza=za
            self.cumleList3.addItem(ornekZaza)




    def benzerKelimeler(self):
        if self.DilGrup.checkedId()==1:
            self.VT=sqlite3.connect("DimiliVT.sqlite")
            self.im=self.VT.cursor()
            self.kelimeListesi.clear()
            kelime=self.araKutu.text()
            if kelime=="" or kelime==None:
                self.kelimeListesi.clear()
            else:
                self.im.execute("select Zazaca from DimTur where Zazaca like ? order by Zazaca ",[kelime+'%'])
                zazaListe=[za[0] for za in self.im.fetchall()]
                for i in zazaListe:
                 self.kelimeListesi.addItem(i)

        if self.DilGrup.checkedId()==2:
            self.VT=sqlite3.connect("DimiliVT.sqlite")
            self.im=self.VT.cursor()
            kelime=self.araKutu.text()
            self.kelimeListesi.clear()
            if kelime=="" or kelime==None:
                self.kelimeListesi.clear()
            else:
                self.im.execute("select Turkce from DimTur where Turkce like ? ",[kelime+'%'])
                turkListe=[tu[0] for tu in self.im.fetchall()]
                for i in turkListe:
                  self.kelimeListesi.addItem(i)

    def dilSecme(self,ind):
        if ind==1:
            self.araKutu.setText("")
            self.kelimeListesi.clear()
            self.cumleList1.clear()
            self.cumleList2.clear()
            self.cumleList3.clear()
            self.Dil1.setStyleSheet("background:#66FF00")
            self.Dil2.setStyleSheet("background-color:#E41841")
        if ind==2:
            self.araKutu.setText("")
            self.kelimeListesi.clear()
            self.cumleList1.clear()
            self.cumleList2.clear()
            self.cumleList3.clear()
            self.Dil2.setStyleSheet("background:#66FF00")
            self.Dil1.setStyleSheet("background-color:#E41841")
    def hakkinda(self):
        QMessageBox.about(self, "Program Hakkında",
                "Bu program <b>bla bla</b> tarafından programlanmıştır. 2015")