Пример #1
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QtGui.QTextCharFormat()
        keywordFormat.setForeground(QtCore.Qt.blue)
        keywordFormat.setFontWeight(QtGui.QFont.Bold)

        keywordPatterns = ["\\b{}\\b".format(k) for k in keyword.kwlist]

        self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat)
                                  for pattern in keywordPatterns]

        classFormat = QtGui.QTextCharFormat()
        classFormat.setFontWeight(QtGui.QFont.Bold)
        self.highlightingRules.append(
            (QtCore.QRegExp("\\bQ[A-Za-z]+\\b"), classFormat))

        singleLineCommentFormat = QtGui.QTextCharFormat()
        singleLineCommentFormat.setForeground(QtCore.Qt.gray)
        self.highlightingRules.append(
            (QtCore.QRegExp("#[^\n]*"), singleLineCommentFormat))

        quotationFormat = QtGui.QTextCharFormat()
        quotationFormat.setForeground(QtCore.Qt.darkGreen)
        self.highlightingRules.append(
            (QtCore.QRegExp("\".*\""), quotationFormat))
        self.highlightingRules.append(
            (QtCore.QRegExp("'.*'"), quotationFormat))
Пример #2
0
 def __init__(self, parent, color_scheme=None):
     """
     :param parent: parent document (QTextDocument)
     :param color_scheme: color scheme to use.
     """
     QtGui.QSyntaxHighlighter.__init__(self, parent)
     Mode.__init__(self)
     if not color_scheme:
         color_scheme = ColorScheme('qt')
     self._color_scheme = color_scheme
     self._spaces_ptrn = QtCore.QRegExp(r'[ \t]+')
     #: Fold detector. Set it to a valid FoldDetector to get code folding
     #: to work. Default is None
     self.fold_detector = None
     self.WHITESPACES = QtCore.QRegExp(r'\s+')
Пример #3
0
    def __init__(self, title, info, action, default_value=None):
        """A customised `QInputDialog`.
        """

        vtapp = vitables.utils.getVTApp()
        # Makes the dialog and gives it a layout
        super(InputNodeName, self).__init__(vtapp.gui)
        self.setupUi(self)

        # Set dialog caption and label with general info
        self.setWindowTitle(title)
        self.generalInfo.setText(info)

        # The Create/Rename button
        self.edit_button = self.buttonsBox.addButton(
            action, QtWidgets.QDialogButtonBox.AcceptRole)

        # Setup a validator for checking the entered node name
        validator = QtGui.QRegExpValidator(self)
        pattern = QtCore.QRegExp("[a-zA-Z_]+[0-9a-zA-Z_ ]*")
        validator.setRegExp(pattern)
        self.valueLE.setValidator(validator)

        if default_value:
            self.valueLE.setText(default_value)

        # Make sure that buttons are in the proper activation state
        self.valueLE.textChanged.emit(self.valueLE.text())
    def checkLineEditPattern(self):
        parameters_ok = True
        freqFilter_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(
                "[0-9]{1,3}([ ][0-9]{1,3}[ ][0-9]{1,3}[ ][0-9]{1,3})?"))

        lineEditList = [
            self.lineEdit_maxTimeRange, self.lineEdit_initTimeRange,
            self.lineEdit_initDataScale, self.lineEdit_channelMin,
            self.lineEdit_channelMax, self.lineEdit_samplingRate,
            self.lineEdit_refreshRate
        ]

        for lineEdit in lineEditList:
            if lineEdit.text() == "":
                parameters_ok = False

        freqFilter_validation = freqFilter_validator.validate(
            self.lineEdit_freqFilter.text(), 0)
        if freqFilter_validation[0] != 2:
            parameters_ok = False

        if parameters_ok is False:
            QtWidgets.QMessageBox.critical(
                None, 'Error', 'Some parameters were not correctly specified.',
                QtWidgets.QMessageBox.Cancel)

        return parameters_ok
    def setup_time_zero_row(self):
        self.time_zero_label = QtWidgets.QLabel(self)
        self.time_zero_label.setText("Time Zero : ")

        self.time_zero_edit = QtWidgets.QLineEdit(self)
        timezero_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(valid_float_regex), self.time_zero_edit)
        self.time_zero_edit.setValidator(timezero_validator)
        self.time_zero_edit.setText("")

        self.time_zero_unit_label = QtWidgets.QLabel(self)
        self.time_zero_unit_label.setText(u"\u03BCs (From data file ")

        self.time_zero_checkbox = QtWidgets.QCheckBox(self)
        self.time_zero_checkbox.setChecked(True)

        self.time_zero_label_2 = QtWidgets.QLabel(self)
        self.time_zero_label_2.setText(" )")

        self.time_zero_layout = QtWidgets.QHBoxLayout()
        self.time_zero_layout.addSpacing(10)
        self.time_zero_layout.addWidget(self.time_zero_unit_label)
        self.time_zero_layout.addWidget(self.time_zero_checkbox)
        self.time_zero_layout.addWidget(self.time_zero_label_2)
        self.time_zero_layout.addStretch(0)

        self.layout.addWidget(self.time_zero_label, 1, 0)
        self.layout.addWidget(self.time_zero_edit, 1, 1)
        self.layout.addItem(self.time_zero_layout, 1, 2)
    def setup_last_good_data_row(self):

        self.last_good_data_label = QtWidgets.QLabel(self)
        self.last_good_data_label.setText("Last Good Data : ")

        self.last_good_data_edit = QtWidgets.QLineEdit(self)

        last_good_data_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(valid_float_regex), self.first_good_data_edit)
        self.last_good_data_edit.setValidator(last_good_data_validator)
        self.last_good_data_edit.setText("")

        self.last_good_data_unit_label = QtWidgets.QLabel(self)
        self.last_good_data_unit_label.setText(u" \u03BCs (From data file ")

        self.last_good_data_checkbox = QtWidgets.QCheckBox(self)
        self.last_good_data_checkbox.setChecked(True)

        self.last_good_data_label_2 = QtWidgets.QLabel(self)
        self.last_good_data_label_2.setText(" )")

        self.last_good_data_layout = QtWidgets.QHBoxLayout()
        self.last_good_data_layout.addSpacing(10)
        self.last_good_data_layout.addWidget(self.last_good_data_unit_label)
        self.last_good_data_layout.addWidget(self.last_good_data_checkbox)
        self.last_good_data_layout.addWidget(self.last_good_data_label_2)
        self.last_good_data_layout.addStretch(0)

        self.layout.addWidget(self.last_good_data_label, 3, 0)
        self.layout.addWidget(self.last_good_data_edit, 3, 1)
        self.layout.addItem(self.last_good_data_layout, 3, 2)
Пример #7
0
 def highlightBlock(self, text):
     for pattern, format in self.highlightingRules:
         expression = QtCore.QRegExp(pattern)
         index = expression.indexIn(text)
         while index >= 0:
             length = expression.matchedLength()
             self.setFormat(index, length, format)
             index = expression.indexIn(text, index + length)
     self.setCurrentBlockState(0)
Пример #8
0
    def __init__(self, parent=None):
        hint = N_('Commit summary')
        HintedLineEdit.__init__(self, hint, parent=parent)
        self.menu_actions = []

        comment_char = prefs.comment_char()
        re_comment_char = re.escape(comment_char)
        regex = QtCore.QRegExp(r'^\s*[^%s \t].*' % re_comment_char)
        self._validator = QtGui.QRegExpValidator(regex, self)
        self.setValidator(self._validator)
    def setup_rebin_row(self):
        self.rebin_label = QtWidgets.QLabel(self)
        self.rebin_label.setText("Rebin : ")

        self.rebin_selector = QtWidgets.QComboBox(self)
        self.rebin_selector.addItems(["None", "Fixed", "Variable"])

        self.rebin_steps_label = QtWidgets.QLabel(self)
        self.rebin_steps_label.setText("Steps : ")

        self.rebin_steps_edit = QtWidgets.QLineEdit(self)
        int_validator = QtGui.QDoubleValidator()
        self.rebin_steps_edit.setValidator(int_validator)
        self.rebin_steps_edit.setToolTip(
            'Value to scale current bin width by.')

        self.rebin_variable_label = QtWidgets.QLabel(self)
        self.rebin_variable_label.setText("Bin Boundaries : ")
        self.rebin_variable_edit = QtWidgets.QLineEdit(self)
        self.rebin_variable_edit.setToolTip(
            'A comma separated list of first bin boundary, width, last bin boundary.\n'
            'Optionally this can be followed by a comma and more widths and last boundary pairs.\n'
            'Optionally this can also be a single number, which is the bin width.\n'
            'Negative width values indicate logarithmic binning.\n\n'
            'For example:\n'
            '2,-0.035,10: from 2 rebin in Logarithmic bins of 0.035 up to 10;\n'
            '0,100,10000,200,20000: from 0 rebin in steps of 100 to 10,000 then steps of 200 to 20,000'
        )
        variable_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp('^(\s*-?\d+(\.\d+)?)(\s*,\s*-?\d+(\.\d+)?)*$'))
        self.rebin_variable_edit.setValidator(variable_validator)

        self.rebin_layout = QtWidgets.QHBoxLayout()
        self.rebin_layout.addSpacing(10)

        self.rebin_layout.addWidget(self.rebin_label)
        self.rebin_layout.addWidget(self.rebin_selector)

        self.rebin_layout.addWidget(self.rebin_steps_label)
        self.rebin_layout.addWidget(self.rebin_steps_edit)
        self.rebin_layout.addWidget(self.rebin_variable_label)
        self.rebin_layout.addWidget(self.rebin_variable_edit)
        self.rebin_layout.addStretch(0)
        self.rebin_layout.addSpacing(10)

        self.rebin_steps_label.hide()
        self.rebin_steps_edit.hide()
        self.rebin_variable_label.hide()
        self.rebin_variable_edit.hide()
Пример #10
0
    def __init__(self, parent):
        QtWidgets.QDialog.__init__(self, parent)

        self.vtk_widget = parent

        ui = self.ui = get_ui('new_project_popup.ui', self)

        self.setWindowTitle('Create a new project')

        ui.toolbutton_browse.clicked.connect(self.browse)
        ui.toolbutton_browse.setIcon(get_icon('folder.svg'))

        ui.lineedit_project_name.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp(re_valid_run_name_qt)))
        ui.combobox_location.editTextChanged.connect(self.check_location)
Пример #11
0
    def __init__(self, name, pattern, info):
        """A customised `QInputDialog`.
        """

        vtapp = vitables.utils.getVTApp()
        # Makes the dialog and gives it a layout
        super(RenameDlg, self).__init__(vtapp.gui)
        self.setupUi(self)

        # Sets dialog caption
        self.setWindowTitle(info[0])
        self.generalInfo.setText(info[1])

        self.troubled_name = name
        self.cpattern = re.compile(pattern)

        # The result returned by this dialog will be contained in the
        # action dictionary. Its values can be:
        # If Overwrite --> True, troubled_name
        # If Rename --> False, new_name
        # If Cancel --> False, ''
        self.action = {'overwrite': False, 'new_name': ''}

        # The dialog buttons: Rename, Overwrite and Cancel
        self.overwrite_button = self.buttonsBox.addButton(
            translate('RenameDlg', 'Overwrite', 'A button label'),
            QtWidgets.QDialogButtonBox.AcceptRole)
        self.rename_button = self.buttonsBox.addButton(
            translate('RenameDlg', 'Rename', 'A button label'),
            QtWidgets.QDialogButtonBox.AcceptRole)
        self.rename_button.setDefault(1)
        self.cancel_button = self.buttonsBox.button(
            QtWidgets.QDialogButtonBox.Cancel)

        # Setup a validator for checking the entered node name
        validator = QtGui.QRegExpValidator(self)
        qt_pattern = QtCore.QRegExp(pattern)
        validator.setRegExp(qt_pattern)
        self.valueLE.setValidator(validator)
        self.valueLE.setText(self.troubled_name)

        self.valueLE.selectAll()

        # Make sure that buttons are in the proper activation state
        self.valueLE.textChanged.emit(self.valueLE.text())
 def setValuePatterns(self):
     self.lineEdit_maxTimeRange.setValidator(
         QtGui.QIntValidator(0, 2147483647))
     self.lineEdit_initTimeRange.setValidator(
         QtGui.QIntValidator(0, 2147483647))
     self.lineEdit_initDataScale.setValidator(
         QtGui.QIntValidator(0, 2147483647))
     self.lineEdit_channelMin.setValidator(
         QtGui.QIntValidator(1, 2147483647))
     self.lineEdit_channelMax.setValidator(
         QtGui.QIntValidator(1, 2147483647))
     self.lineEdit_samplingRate.setValidator(
         QtGui.QIntValidator(0, 2147483647))
     self.lineEdit_refreshRate.setValidator(
         QtGui.QIntValidator(0, 2147483647))
     self.lineEdit_freqFilter.setValidator(
         QtGui.QRegExpValidator(
             QtCore.QRegExp(
                 "[0-9]{1,3}([ ][0-9]{1,3}[ ][0-9]{1,3}[ ][0-9]{1,3})?")))
    def setup_double_pulse_row(self):
        self.double_pulse_data_edit = QtWidgets.QLineEdit(self)

        double_pulse_data_validator = QtGui.QRegExpValidator(
            QtCore.QRegExp(valid_float_regex),
            self.double_pulse_data_edit)
        self.double_pulse_data_edit.setValidator(double_pulse_data_validator)
        self.double_pulse_data_edit.setText("0.33")

        self.double_pulse_data_unit_label = QtWidgets.QLabel(self)
        self.double_pulse_data_unit_label.setText(u" \u03BCs")

        self.double_pulse_data_combobox = QtWidgets.QComboBox(self)
        self.double_pulse_data_combobox.addItem('Single Pulse')
        self.double_pulse_data_combobox.addItem('Double Pulse')

        self.double_pulse_data_layout = QtWidgets.QHBoxLayout()
        self.double_pulse_data_layout.addSpacing(10)
        self.double_pulse_data_layout.addWidget(self.double_pulse_data_unit_label)
        self.double_pulse_data_layout.addStretch(0)

        self.layout.addWidget(self.double_pulse_data_combobox, 4, 0)
        self.layout.addWidget(self.double_pulse_data_edit, 4, 1)
        self.layout.addItem(self.double_pulse_data_layout, 4, 2)
Пример #14
0
    def OnSwitchPageButtonClick(self):

        # Input page number
        szText = self.switchPageLineEdit.text()
        if szText != "":
            # Pattern of a number
            regExp = QtCore.QRegExp(u"-?[0-9]*")
            # Validate a number
            if not regExp.exactMatch(szText):
                QtWidgets.QMessageBox.information(self, u"Info",
                                                  u"input number")
                return
        else:
            QtWidgets.QMessageBox.information(self, u"info",
                                              u"input page number")
            return
        # Get page number
        pageIndex = int(szText)
        # Validate existence of page
        if pageIndex > self.totalPageCount or pageIndex < 1:
            QMessageBox.information(self, u"info", u"page error")
            self.switchPageLineEdit.setText("")
            return
        self.OnSwitchPage(pageIndex)
Пример #15
0
    def __init__(self,
                 text="Enter object label",
                 parent=None,
                 labels=None,
                 sub_labels=None,
                 sort_labels=True,
                 show_text_field=True,
                 completion="startswith",
                 fit_to_content=None,
                 flags=None,
                 app=None):
        if fit_to_content is None:
            fit_to_content = {"row": False, "column": True}
        self._fit_to_content = fit_to_content
        super(LabelDialog, self).__init__(parent)

        # disable default button. Use default close button will have bug
        # that sub window setting will be reset and can not modify again.
        # QtCore.Qt.Dialog setting will be reseted.
        self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False)
        self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False)

        self.edit = LabelQLineEdit()
        self.edit.setPlaceholderText(text)
        self.edit.setValidator(labelme.utils.labelValidator())
        self.edit.editingFinished.connect(self.postProcess)
        if flags:
            self.edit.textChanged.connect(self.updateFlags)

        self.edit_group_id = QtWidgets.QLineEdit()
        self.edit_group_id.setPlaceholderText("Group ID")
        self.edit_group_id.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp(r"\d*"), None))

        layout = QtWidgets.QVBoxLayout()
        if show_text_field:
            layout_edit = QtWidgets.QHBoxLayout()
            layout_edit.addWidget(self.edit, 6)
            layout_edit.addWidget(self.edit_group_id, 2)
            layout.addLayout(layout_edit)

        ### cc region threshold
        self.cc_threshold_ui = []
        ## slider
        defaultValue = 6
        self.sl = QSlider(Qt.Horizontal)
        self.sl.setMinimum(0)
        self.sl.setMaximum(100)
        self.sl.setValue(defaultValue)
        self.sl.valueChanged.connect(self.sl_valuechange)
        ## label show slider value
        self.slLabel = QLabel("")
        self.slLabel.setText(str(defaultValue))
        self.slLabel.setAlignment(Qt.AlignCenter)
        ## tie slider and label together
        slider_set = QtWidgets.QHBoxLayout()
        slider_set.addWidget(self.sl, 6)
        slider_set.addWidget(self.slLabel, 2)
        ## add to total layout
        self.cc_threshold_ui.append(self.sl)
        self.cc_threshold_ui.append(self.slLabel)
        layout.addLayout(slider_set)

        ### text box attribute
        self.text_box_ui = []
        text_box_set = QtWidgets.QVBoxLayout()
        ## column of text
        tmpHor = QtWidgets.QHBoxLayout()
        self.text_cols = QtWidgets.QLineEdit("4")
        self.text_cols.setPlaceholderText("")
        self.text_cols.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp(r"\d*"), None))
        # label
        self.text_cols_label = QLabel("Columns of Text")
        self.text_cols_label.setAlignment(Qt.AlignLeft)
        tmpHor.addWidget(self.text_cols_label, 5)
        tmpHor.addWidget(self.text_cols, 5)
        # add to ui group
        self.text_box_ui.append(self.text_cols_label)
        self.text_box_ui.append(self.text_cols)
        text_box_set.addLayout(tmpHor)

        ## rows of text
        tmpHor = QtWidgets.QHBoxLayout()
        self.text_rows = QtWidgets.QLineEdit("4")
        self.text_rows.setPlaceholderText("")
        self.text_rows.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp(r"\d*"), None))
        # label
        self.text_rows_label = QLabel("Rows of Text")
        self.text_rows_label.setAlignment(Qt.AlignLeft)
        tmpHor.addWidget(self.text_rows_label, 5)
        tmpHor.addWidget(self.text_rows, 5)
        # add to ui group
        self.text_box_ui.append(self.text_rows_label)
        self.text_box_ui.append(self.text_rows)
        text_box_set.addLayout(tmpHor)

        ## generate button
        self.generateBoxbb = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Apply
            | QtWidgets.QDialogButtonBox.Reset, QtCore.Qt.Horizontal, self)
        self.generateBoxbb.button(self.generateBoxbb.Apply).clicked.connect(
            self.setTextBoxAttribute)
        self.generateBoxbb.button(self.generateBoxbb.Reset).clicked.connect(
            self.resetTextBoxAttribute)
        # add to ui group
        self.text_box_ui.append(self.generateBoxbb)
        text_box_set.addWidget(self.generateBoxbb,
                               alignment=QtCore.Qt.AlignRight)
        ## add to total layout
        layout.addLayout(text_box_set)

        # buttons
        self.buttonBox = bb = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal,
            self,
        )
        bb.button(bb.Ok).setIcon(labelme.utils.newIcon("done"))
        bb.button(bb.Cancel).setIcon(labelme.utils.newIcon("undo"))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        layout.addWidget(bb)
        # label_list
        self.labelList = QtWidgets.QListWidget()
        if self._fit_to_content["row"]:
            self.labelList.setHorizontalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff)
        if self._fit_to_content["column"]:
            self.labelList.setVerticalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff)
        self._sort_labels = sort_labels
        if labels:
            self.labelList.addItems(labels)
        if self._sort_labels:
            self.labelList.sortItems()
        else:
            self.labelList.setDragDropMode(
                QtWidgets.QAbstractItemView.InternalMove)
        self.labelList.currentItemChanged.connect(self.labelSelected)
        self.labelList.itemDoubleClicked.connect(self.labelDoubleClicked)
        self.edit.setListWidget(self.labelList)
        layout.addWidget(self.labelList)
        # sub label list
        self.sub_labelList = QtWidgets.QListWidget()
        if self._fit_to_content["row"]:
            self.sub_labelList.setHorizontalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff)
        if self._fit_to_content["column"]:
            self.sub_labelList.setVerticalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff)
        if labels:
            self.sub_labelList.addItems(sub_labels)
        self.sub_labelList.setDragDropMode(
            QtWidgets.QAbstractItemView.InternalMove)
        self.sub_labelList.currentItemChanged.connect(self.labelSelected)
        # make sure main label has content
        self.sub_labelList.itemDoubleClicked.connect(self.labelDoubleClicked)
        self.edit.setListWidget(self.sub_labelList)
        layout.addWidget(self.sub_labelList)
        # label_flags
        if flags is None:
            flags = {}
        self._flags = flags
        self.flagsLayout = QtWidgets.QVBoxLayout()
        self.resetFlags()
        layout.addItem(self.flagsLayout)
        self.edit.textChanged.connect(self.updateFlags)
        self.setLayout(layout)
        # completion
        completer = QtWidgets.QCompleter()
        if not QT5 and completion != "startswith":
            logger.warn("completion other than 'startswith' is only "
                        "supported with Qt5. Using 'startswith'")
            completion = "startswith"
        if completion == "startswith":
            completer.setCompletionMode(QtWidgets.QCompleter.InlineCompletion)
            # Default settings.
            # completer.setFilterMode(QtCore.Qt.MatchStartsWith)
        elif completion == "contains":
            completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
            completer.setFilterMode(QtCore.Qt.MatchContains)
        else:
            raise ValueError("Unsupported completion: {}".format(completion))
        completer.setModel(self.labelList.model())
        self.completer = completer
        self.edit.setCompleter(completer)

        # sub completion
        completer = QtWidgets.QCompleter()
        if not QT5 and completion != "startswith":
            logger.warn("completion other than 'startswith' is only "
                        "supported with Qt5. Using 'startswith'")
            completion = "startswith"
        if completion == "startswith":
            completer.setCompletionMode(QtWidgets.QCompleter.InlineCompletion)
            # Default settings.
            # completer.setFilterMode(QtCore.Qt.MatchStartsWith)
        elif completion == "contains":
            completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
            completer.setFilterMode(QtCore.Qt.MatchContains)
        else:
            raise ValueError("Unsupported completion: {}".format(completion))
        completer.setModel(self.sub_labelList.model())
        self.sub_completer = completer

        # mine
        # self.inEdit = False
        self.app = app
        self.sub_window = SubWindow(self)
Пример #16
0
    def setup_interface(self, show_checks=False):
        self.setObjectName("GroupingWidget")
        self.resize(500, 100)

        self.grouppair_label = QtWidgets.QLabel(self)
        self.grouppair_label.setObjectName("groupPairLabel")
        self.grouppair_label.setText("Group / ")

        self.pair_label = QtWidgets.QLabel(self)
        self.pair_label.setObjectName("pairLabel")
        font = QtGui.QFont()
        font.setBold(True)
        self.pair_label.setFont(font)
        self.pair_label.setText("Pair : ")

        self.grouppair_selector = QtWidgets.QComboBox(self)
        self.grouppair_selector.setObjectName("groupPairSelector")
        self.grouppair_selector.addItems(["fwd", "bwd"])

        self.alpha_label_2 = QtWidgets.QLabel(self)
        self.alpha_label_2.setObjectName("AlphaLabel")
        self.alpha_label_2.setText("Alpha : ")

        self.alpha_edit = QtWidgets.QLineEdit(self)
        self.alpha_edit.setObjectName("alphaEdit")
        self.alpha_edit.setText("1.0")
        self.alpha_edit.setEnabled(False)

        reg_ex = QtCore.QRegExp(valid_alpha_regex)
        alpha_validator = QtGui.QRegExpValidator(reg_ex, self.alpha_edit)
        self.alpha_edit.setValidator(alpha_validator)

        self.horizontal_layout = QtWidgets.QHBoxLayout()
        self.horizontal_layout.setObjectName("horizontalLayout3")
        self.horizontal_layout.addWidget(self.grouppair_label)
        self.horizontal_layout.addWidget(self.pair_label)
        self.horizontal_layout.addWidget(self.grouppair_selector)
        self.horizontal_layout.addStretch(0)
        self.horizontal_layout.addWidget(self.alpha_label_2)
        self.horizontal_layout.addWidget(self.alpha_edit)

        self.period_label = QtWidgets.QLabel(self)
        self.period_label.setObjectName("periodLabel")
        self.period_label.setText(
            "Data collected in n periods. Plot/analysis period(s) : ")

        self.summed_period_edit = QtWidgets.QLineEdit(self)
        self.summed_period_edit.setText("1")
        reg_ex = QtCore.QRegExp(run_string_regex)
        period_validator = QtGui.QRegExpValidator(reg_ex,
                                                  self.summed_period_edit)
        self.summed_period_edit.setValidator(period_validator)

        self.minus_label = QtWidgets.QLabel(self)
        self.minus_label.setObjectName("minusLabel")
        self.minus_label.setText("-")

        self.subtracted_period_edit = QtWidgets.QLineEdit(self)
        self.subtracted_period_edit.setText("")
        period_validator = QtGui.QRegExpValidator(reg_ex,
                                                  self.subtracted_period_edit)
        self.subtracted_period_edit.setValidator(period_validator)

        self.horizontal_layout_2 = QtWidgets.QHBoxLayout()
        self.horizontal_layout_2.setObjectName("horizontalLayout2")
        self.horizontal_layout_2.addWidget(self.period_label)
        self.horizontal_layout_2.addStretch(0)
        self.horizontal_layout_2.addWidget(self.summed_period_edit)
        self.horizontal_layout_2.addSpacing(10)
        self.horizontal_layout_2.addWidget(self.minus_label)
        self.horizontal_layout_2.addSpacing(10)
        self.horizontal_layout_2.addWidget(self.subtracted_period_edit)

        self.group = QtWidgets.QGroupBox("Groups and Pairs")
        self.group.setFlat(False)
        self.setStyleSheet(
            "QGroupBox {border: 1px solid grey;border-radius: 10px;margin-top: 1ex; margin-right: 0ex}"
            "QGroupBox:title {"
            'subcontrol-origin: margin;'
            "padding: 0 3px;"
            'subcontrol-position: top center;'
            'padding-top: 0px;'
            'padding-bottom: 0px;'
            "padding-right: 10px;"
            ' color: grey; }')

        self.vertical_layout = QtWidgets.QVBoxLayout(self)
        self.vertical_layout.setObjectName("verticalLayout")
        self.vertical_layout.addItem(self.horizontal_layout)
        self.vertical_layout.addItem(self.horizontal_layout_2)
        if show_checks:
            self.all_groups_label = QtWidgets.QLabel(self)
            self.all_groups_label.setText("Apply to all groups : ")
            self.all_groups_checkbox = QtWidgets.QCheckBox(self)
            self.all_pairs_label = QtWidgets.QLabel(self)
            self.all_pairs_label.setText(
                "Apply to all pairs (alpha will not be applied)  : ")
            self.all_pairs_checkbox = QtWidgets.QCheckBox(self)

            self.horizontal_layout_3 = QtWidgets.QHBoxLayout()
            self.horizontal_layout_3.setObjectName("horizontalLayout2")
            self.horizontal_layout_3.addWidget(self.all_groups_label)
            self.horizontal_layout_3.addWidget(self.all_groups_checkbox)

            self.horizontal_layout_4 = QtWidgets.QHBoxLayout()
            self.horizontal_layout_4.addWidget(self.all_pairs_label)
            self.horizontal_layout_4.addWidget(self.all_pairs_checkbox)
            self.vertical_layout.addItem(self.horizontal_layout_3)
            self.vertical_layout.addItem(self.horizontal_layout_4)

        self.group.setLayout(self.vertical_layout)

        self.widget_layout = QtWidgets.QVBoxLayout(self)
        self.widget_layout.addWidget(self.group)
        self.setLayout(self.widget_layout)
Пример #17
0
    def __init__(
        self,
        parent=None,
    ):
        super(MetaDialog, self).__init__(parent)
        self.parent = parent
        self.setWindowTitle('Meta information')
        regex_rules = 'a-zA-Z0-9.,_ -#(){}'
        regex = QtCore.QRegExp('^[' + regex_rules + ']+$')
        self.street1 = QtWidgets.QLabel('street1')
        self.street2 = QtWidgets.QLabel('street2')
        self.city = QtWidgets.QLabel('City')
        self.state = QtWidgets.QLabel('State')
        self.country = QtWidgets.QLabel('Country')
        self.date_created = QtWidgets.QLabel('Date Created')
        self.lat_long = QtWidgets.QLabel('lat/long')
        self.cust_display_name = QtWidgets.QLabel('Customer display name')
        self.bnr_display_name = QtWidgets.QLabel('Bossanova internal name')
        self.uuid = QtWidgets.QLabel('UUID')
        self.calc_lat_long = QtWidgets.QPushButton('Calc')

        self.street1_edit = QtWidgets.QLineEdit()
        self.street2_edit = QtWidgets.QLineEdit()
        self.city_edit = QtWidgets.QLineEdit()
        self.state_edit = QtWidgets.QLineEdit()
        self.country_edit = QtWidgets.QLineEdit()
        self.lat_long_edit = QtWidgets.QLineEdit()
        self.date_created_edit = QtWidgets.QLineEdit()
        self.date_created_edit.setText(
            datetime.datetime.now().strftime('%Y-%m-%d'))
        self.date_created_edit.setReadOnly(True)
        self.cust_display_name_edit = QtWidgets.QLineEdit()
        self.bnr_display_name_edit = QtWidgets.QLineEdit()
        self.uuid_edit = QtWidgets.QLineEdit()
        self.uuid_edit.setText(getUUID())
        self.uuid_edit.setReadOnly(True)
        self.calc_lat_long.clicked.connect(self._calculate_lat_long)
        self.widgets = [
            self.street1_edit, self.street2_edit, self.city_edit,
            self.state_edit, self.country_edit, self.bnr_display_name_edit,
            self.cust_display_name_edit
        ]
        self._set_widget_tooltip_property(self.widgets, regex_rules)
        self._set_widget_edit_property(self.widgets, self.postProcess)
        self._set_widget_validators(self.widgets, regex)

        grid = QtWidgets.QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(self.street1, 0, 0)
        grid.addWidget(self.street1_edit, 0, 1)
        grid.addWidget(self.street2, 1, 0)
        grid.addWidget(self.street2_edit, 1, 1)
        grid.addWidget(self.city, 2, 0)
        grid.addWidget(self.city_edit, 2, 1)
        grid.addWidget(self.state, 3, 0)
        grid.addWidget(self.state_edit, 3, 1)
        grid.addWidget(self.country, 5, 0)
        grid.addWidget(self.country_edit, 5, 1)
        grid.addWidget(self.date_created, 6, 0)
        grid.addWidget(self.date_created_edit, 6, 1)
        grid.addWidget(self.lat_long, 7, 0)
        grid.addWidget(self.lat_long_edit, 7, 1)
        grid.addWidget(self.calc_lat_long, 7, 2)
        grid.addWidget(self.cust_display_name, 8, 0)
        grid.addWidget(self.cust_display_name_edit, 8, 1)
        grid.addWidget(self.bnr_display_name, 9, 0)
        grid.addWidget(self.bnr_display_name_edit, 9, 1)
        grid.addWidget(self.uuid, 10, 0)
        grid.addWidget(self.uuid_edit, 10, 1)
        # buttons
        self.buttonBox = bb = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal,
            self,
        )
        bb.button(bb.Ok).setIcon(newIcon('done'))
        bb.button(bb.Cancel).setIcon(newIcon('undo'))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        grid.addWidget(bb, 11, 0)
        self.setLayout(grid)
Пример #18
0
 def set_run_edit_regex(self):
     # The regular expression string here is "^[0-9]*([0-9]+[,-]{0,1})*[0-9]+$"
     regex = QtCore.QRegExp(run_utils.run_string_regex)
     validator = QtGui.QRegExpValidator(regex)
     self.run_edit.setValidator(validator)
Пример #19
0
    def __init__(self, parent=None):
        super(SLMdialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("LLSpy :: SLM Pattern Generator")
        self.autofill = False
        self.mode = "square"
        self.dithered = False
        self.writeThreadpool = QtCore.QThreadPool()

        # TODO: figure out why windows sucks at multithreading
        if sys.platform.startswith("win"):
            self.writeThreadpool.setMaxThreadCount(1)

        self.PatternPresetsCombo.addItems(self.PRESETS)

        self.fudgeSpin.valueChanged.connect(self.updateSpacing)
        self.wavelengthSpin.valueChanged.connect(self.updateSpacing)
        self.innerNASpin.valueChanged.connect(self.updateSpacing)
        self.autoSpacingCheckBox.toggled.connect(self.toggleAutoSpace)

        # self.slmBinaryLabel.setStyleSheet("background-color: rgb(111, 174, 255);")
        self.slmBinaryLabel = QtWidgets.QLabel(self)
        self.slmBinaryLabel.setBackgroundRole(QtGui.QPalette.Base)
        self.slmBinaryLabel.setSizePolicy(
            QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored
        )
        # self.slmBinaryLabel.setGeometry(QtCore.QRect(0, 0, 476, 150))
        self.slmBinaryLabel.setFixedWidth(476)
        self.slmBinaryLabel.setFixedHeight(150)
        # self.slmBinaryLabel.setScaledContents(True)

        self.sampleIntensityLabel = QtWidgets.QLabel(self)
        self.sampleIntensityLabel.setBackgroundRole(QtGui.QPalette.Base)
        self.sampleIntensityLabel.setSizePolicy(
            QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored
        )
        # self.sampleIntensityLabel.setGeometry(QtCore.QRect(0, 0, 476, 150))
        self.sampleIntensityLabel.setFixedWidth(476)
        self.sampleIntensityLabel.setFixedHeight(150)

        self.maskIntensityLabel = QtWidgets.QLabel(self)
        self.maskIntensityLabel.setBackgroundRole(QtGui.QPalette.Base)
        self.maskIntensityLabel.setSizePolicy(
            QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored
        )

        self.upperRightScroll.setBackgroundRole(QtGui.QPalette.Dark)
        self.lowerLeftScroll.setBackgroundRole(QtGui.QPalette.Dark)
        self.lowerRightScroll.setBackgroundRole(QtGui.QPalette.Dark)
        self.upperRightScroll.setWidget(self.maskIntensityLabel)
        self.lowerLeftScroll.setWidget(self.slmBinaryLabel)
        self.lowerRightScroll.setWidget(self.sampleIntensityLabel)

        font = QtGui.QFont()
        # font.setFamily("Helvetica")
        font.setBold(True)
        font.setWeight(60)

        self.lowerLeftTitle = QtWidgets.QLabel(self.lowerLeftScroll)
        self.lowerLeftTitle.setGeometry(QtCore.QRect(5, 5, 170, 16))
        self.lowerLeftTitle.setFont(font)
        self.lowerLeftTitle.setStyleSheet("color:#777;")
        self.lowerLeftTitle.setObjectName("lowerLeftTitle")
        self.lowerLeftTitle.setText("binary SLM mask")

        self.lowerRightTitle = QtWidgets.QLabel(self.lowerRightScroll)
        self.lowerRightTitle.setGeometry(QtCore.QRect(5, 5, 170, 16))
        self.lowerRightTitle.setFont(font)
        self.lowerRightTitle.setStyleSheet("color:#777;")
        self.lowerRightTitle.setObjectName("lowerRightTitle")
        self.lowerRightTitle.setText("Intensity At Sample")

        self.upperRightTitle = QtWidgets.QLabel(self.upperRightScroll)
        self.upperRightTitle.setGeometry(QtCore.QRect(5, 5, 170, 16))
        self.upperRightTitle.setFont(font)
        self.upperRightTitle.setStyleSheet("color:#777;")
        self.upperRightTitle.setObjectName("upperRightTitle")
        self.upperRightTitle.setText("Intensity After Mask")

        self.ditherButton = QtWidgets.QPushButton(self.lowerRightScroll)
        self.ditherButton.setCheckable(True)
        w = self.lowerRightScroll.width()
        self.ditherButton.setGeometry(QtCore.QRect(w - 64, 4, 60, 25))
        self.ditherButton.setStyleSheet("color:#000;")
        self.ditherButton.setText("Dither")
        self.ditherButton.setFlat(True)
        self.ditherButton.setAutoFillBackground(True)
        self.ditherButton.clicked.connect(self.setDitherState)

        self.previewPatternButton.clicked.connect(self.previewPattern)
        self.writeFileButton.clicked.connect(self.writeFile)
        self.batchProcessButton.clicked.connect(self.batchProcess)
        self.chooseBatchOutputDir.clicked.connect(self.setBatchOutput)

        self.PatternPresetsCombo.currentTextChanged.connect(self.updatePreset)
        self.SLMmodelCombo.currentTextChanged.connect(self.setSLM)
        self.SLMmodelCombo.clear()
        self.SLMmodelCombo.addItems(list(SLMs.keys()))
        self.setSLM("SXGA-3DM")
        self.PatternPresetsCombo.setCurrentText("Square Lattice, Fill Chip")

        lutnames = sorted([lut.title() for lut in QLuts.keys()])
        self.maskLUTCombo.addItems(lutnames)
        self.maskLUTCombo.setCurrentText("Inferno")
        self.maskLUTCombo.currentTextChanged.connect(self.plotMaskIntensity)
        self.sampleLUTCombo.addItems(lutnames)
        self.sampleLUTCombo.setCurrentText("Viridis")
        self.sampleLUTCombo.currentTextChanged.connect(self.plotSampleIntensity)

        rangeRX = QtCore.QRegExp(r"[\d.-]+:?([\d.-]+)?:?([\d.-]+)?")
        rangeValidator = QtGui.QRegExpValidator(rangeRX)
        self.batch_tilt.setValidator(rangeValidator)
        self.batch_xShift.setValidator(rangeValidator)
        self.batch_yShift.setValidator(rangeValidator)

        numCommaRX = QtCore.QRegExp(r"[\d,.]+")
        numCommaValidator = QtGui.QRegExpValidator(numCommaRX)
        self.batch_outerNA.setValidator(numCommaValidator)
        self.batch_innerNA.setValidator(numCommaValidator)
        numCommaRX = QtCore.QRegExp(r"[\d,]+")
        self.batch_wave.setValidator(QtGui.QRegExpValidator(numCommaRX))
Пример #20
0
    def __init__(self,
                 text="Enter object label",
                 parent=None,
                 labels=None,
                 sort_labels=True,
                 show_text_field=True,
                 completion='startswith',
                 fit_to_content=None):
        if fit_to_content is None:
            fit_to_content = {'row': False, 'column': True}
        self._fit_to_content = fit_to_content

        super(LabelTextDialog, self).__init__(parent)
        self.edit = LabelQLineEdit()
        self.edit.setPlaceholderText(text)
        self.edit.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp(r'^[^ \t].+'), None))

        self.edit.editingFinished.connect(self.post_process)
        layout = QtWidgets.QVBoxLayout()
        if show_text_field:
            layout.addWidget(self.edit)
        # buttons
        self.buttonBox = bb = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal,
            self,
        )
        bb.button(bb.Ok).setIcon(new_icon('done'))
        bb.button(bb.Cancel).setIcon(new_icon('undo'))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        layout.addWidget(bb)
        # label_list
        self.labelList = QtWidgets.QListWidget()
        if self._fit_to_content['row']:
            self.labelList.setHorizontalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff)
        if self._fit_to_content['column']:
            self.labelList.setVerticalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff)
        self._sort_labels = sort_labels
        if labels:
            self.labelList.addItems(labels)
        if self._sort_labels:
            self.labelList.sortItems()
        else:
            self.labelList.setDragDropMode(
                QtWidgets.QAbstractItemView.InternalMove)
        self.labelList.currentItemChanged.connect(self.label_selected)
        self.edit.set_list_widget(self.labelList)
        layout.addWidget(self.labelList)
        self.setLayout(layout)
        # completion
        completer = QtWidgets.QCompleter()
        if not QT5 and completion != 'startswith':
            logger.warn("completion other than 'startswith' is only "
                        "supported with Qt5. Using 'startswith'")
            completion = 'startswith'
        if completion == 'startswith':
            completer.setCompletionMode(QtWidgets.QCompleter.InlineCompletion)
            # Default settings.
            # completer.setFilterMode(QtCore.Qt.MatchStartsWith)
        elif completion == 'contains':
            completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
            completer.setFilterMode(QtCore.Qt.MatchContains)
        else:
            raise ValueError('Unsupported completion: {}'.format(completion))
        completer.setModel(self.labelList.model())
        self.edit.setCompleter(completer)
    def filterRegExpChanged(self):
        syntax = QtCore.QRegExp.PatternSyntax(QtCore.QRegExp.FixedString)

        regExp = QtCore.QRegExp(self.ui.search_input.text(),
                                    QtCore.Qt.CaseInsensitive, syntax)
        self.proxyModel.setFilterRegExp(regExp)
Пример #22
0
    def setup_interface_layout(self):
        self.setObjectName("GroupingTabView")
        self.resize(1000, 1000)

        self.setup_description_layout()

        self.load_grouping_button = QtWidgets.QPushButton(self)
        self.load_grouping_button.setText("Load")
        self.load_grouping_button.setToolTip(
            "Load a previously saved grouping (in XML format)")

        self.save_grouping_button = QtWidgets.QPushButton(self)
        self.save_grouping_button.setText("Save")
        self.save_grouping_button.setToolTip(
            "Save the current state of the group/pair table to XML format")

        self.clear_grouping_button = QtWidgets.QPushButton(self)
        self.clear_grouping_button.setText("Clear")
        self.clear_grouping_button.setToolTip(
            "Clear the grouping/pairing tables")

        self.default_grouping_button = QtWidgets.QPushButton(self)
        self.default_grouping_button.setText("Default")
        self.default_grouping_button.setToolTip(
            "Restore the default grouping for the currently selected instrument."
        )

        self.horizontal_layout = QtWidgets.QHBoxLayout()
        self.horizontal_layout.setObjectName("horizontalLayout")
        self.horizontal_layout.addWidget(self.load_grouping_button)
        self.horizontal_layout.addWidget(self.save_grouping_button)
        self.horizontal_layout.addWidget(self.clear_grouping_button)
        self.horizontal_layout.addWidget(self.default_grouping_button)

        self.horizontal_layout_base = QtWidgets.QHBoxLayout()

        self.vertical_layout = QtWidgets.QVBoxLayout(self)
        self.vertical_layout.setObjectName("verticalLayout")
        self.vertical_layout.addItem(self.horizontal_layout)
        self.vertical_layout.addItem(self.horizontal_layout_description)
        self.vertical_layout.addWidget(self._grouping_table)
        self.vertical_layout.addWidget(self._pairing_table)
        self.vertical_layout.addItem(self.horizontal_layout_base)

        # PERIOD DATA
        self.period_label = QtWidgets.QLabel(self)
        self.period_label.setObjectName("periodLabel")
        self.period_label.setText(
            "Data collected in n periods. Plot/analysis period(s) : ")

        self.summed_period_edit = QtWidgets.QLineEdit(self)
        self.summed_period_edit.setText("1")
        reg_ex = QtCore.QRegExp(run_string_regex)
        period_validator = QtGui.QRegExpValidator(reg_ex,
                                                  self.summed_period_edit)
        self.summed_period_edit.setValidator(period_validator)

        self.minus_label = QtWidgets.QLabel(self)
        self.minus_label.setObjectName("minusLabel")
        self.minus_label.setText("-")

        self.subtracted_period_edit = QtWidgets.QLineEdit(self)
        self.subtracted_period_edit.setText("")
        period_validator = QtGui.QRegExpValidator(reg_ex,
                                                  self.subtracted_period_edit)
        self.subtracted_period_edit.setValidator(period_validator)

        self.horizontal_layout_1 = QtWidgets.QHBoxLayout()
        self.horizontal_layout_1.setObjectName("horizontalLayout2")
        self.horizontal_layout_1.addWidget(self.period_label)
        self.horizontal_layout_1.addStretch(0)
        self.horizontal_layout_1.addWidget(self.summed_period_edit)
        self.horizontal_layout_1.addSpacing(10)
        self.horizontal_layout_1.addWidget(self.minus_label)
        self.horizontal_layout_1.addSpacing(10)
        self.horizontal_layout_1.addWidget(self.subtracted_period_edit)
        self.vertical_layout.addItem(self.horizontal_layout_1)

        self.setLayout(self.vertical_layout)
Пример #23
0
 def set_regex(self, regex):
     re = QtCore.QRegExp(regex)
     self.setRegExp(re)
    def __init__(self, edit=False, data=None, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        # 保存并连接标记
        self.saveAndConnectFlag = False
        # 窗口大小
        self.setFixedSize(400, 300)
        # 判断新增或者编辑
        if edit:
            self.setWindowTitle(text.EDIT)
        else:
            self.setWindowTitle(text.ADD)

        # 表格布局,用来布局QLabel和QLineEdit
        tableGridLayout = QtWidgets.QGridLayout()

        # 用户ID
        rowNum = 0
        tableGridLayout.addWidget(QtWidgets.QLabel(text.USER_ID), rowNum, 0)
        if edit:
            self.userIDLineEdit = QtWidgets.QLineEdit(
                data['userID'] if 'userID' in data.keys() else None)
            self.userIDLineEdit.setDisabled(True)
        else:
            self.userIDLineEdit = QtWidgets.QLineEdit()
        self.userIDValidator = QtGui.QRegExpValidator(
            QtCore.QRegExp('^[a-zA-Z0-9]{4,16}$'))
        self.userIDLineEdit.setValidator(self.userIDValidator)
        tableGridLayout.addWidget(self.userIDLineEdit, rowNum, 1)

        # 密码
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.PASSWORD), rowNum, 0)
        if edit:
            self.passwordLineEdit = QtWidgets.QLineEdit(
                data['password'] if 'password' in data.keys() else None)
        else:
            self.passwordLineEdit = QtWidgets.QLineEdit()
        self.passwordValidator = QtGui.QRegExpValidator(
            QtCore.QRegExp('^.{4,20}$'))
        self.passwordLineEdit.setValidator(self.passwordValidator)
        self.passwordLineEdit.setEchoMode(QtWidgets.QLineEdit.Password)
        tableGridLayout.addWidget(self.passwordLineEdit, rowNum, 1)

        # 授权码
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.AUTH_CODE), rowNum, 0)
        if edit:
            self.authCodeLineEdit = QtWidgets.QLineEdit(
                data['authCode' if 'authCode' in data.keys() else None])
        else:
            self.authCodeLineEdit = QtWidgets.QLineEdit()
        tableGridLayout.addWidget(self.authCodeLineEdit, rowNum, 1)

        # 用户产品信息
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.USER_PRODUCT_INFO),
                                  rowNum, 0)
        if edit:
            self.userProductInfoLineEdit = QtWidgets.QLineEdit(
                data['userProductInfo'] if 'userProductInfo' in
                data.keys() else None)
        else:
            self.userProductInfoLineEdit = QtWidgets.QLineEdit()
        tableGridLayout.addWidget(self.userProductInfoLineEdit, rowNum, 1)

        # 经纪商ID
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.BROKER_ID), rowNum, 0)
        if edit:
            self.brokerIDLineEdit = QtWidgets.QLineEdit(
                data['brokerID'] if 'brokerID' in data.keys() else None)
            self.brokerIDLineEdit.setDisabled(True)
        else:
            self.brokerIDLineEdit = QtWidgets.QLineEdit()
        self.brokerIDValidator = QtGui.QRegExpValidator(
            QtCore.QRegExp('^[a-zA-Z0-9]{4,16}$'))
        self.brokerIDLineEdit.setValidator(self.brokerIDValidator)
        tableGridLayout.addWidget(self.brokerIDLineEdit, rowNum, 1)

        # 网关模块
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.GATEWAY_MODULE),
                                  rowNum, 0)
        self.gatewayModuleComboBox = QtWidgets.QComboBox()
        if edit:
            self.gatewayModuleComboBox.addItem(
                data['gatewayModule'] if 'gatewayModule' in
                data.keys() else None)
            self.gatewayModuleComboBox.setDisabled(True)
        else:
            self.gatewayModuleList = dynamicGatewayList
            self.gatewayModuleComboBox.addItems(self.gatewayModuleList)
        tableGridLayout.addWidget(self.gatewayModuleComboBox, rowNum, 1)

        # 网关显示名称
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.GATEWAY_DISPLAY_NAME),
                                  rowNum, 0)
        if edit:
            self.gatewayDisplayNameLineEdit = QtWidgets.QLineEdit(
                data['gatewayDisplayName'] if 'gatewayDisplayName' in
                data.keys() else None)
        else:
            self.gatewayDisplayNameLineEdit = QtWidgets.QLineEdit()

        self.gatewayDisplayNameValidator = QtGui.QRegExpValidator(
            QtCore.QRegExp('^.{4,16}$'))
        self.gatewayDisplayNameLineEdit.setValidator(
            self.gatewayDisplayNameValidator)
        tableGridLayout.addWidget(self.gatewayDisplayNameLineEdit, rowNum, 1)

        # 交易地址
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.TD_ADDRESS), rowNum, 0)
        if edit:
            self.tdAddressLineEdit = QtWidgets.QLineEdit(
                data['tdAddress'] if 'tdAddress' in data.keys() else None)
        else:
            self.tdAddressLineEdit = QtWidgets.QLineEdit('tcp://')
        # 验证TCP地址,未考虑端口超过65535的情况
        self.tdAddressValidator = QtGui.QRegExpValidator(
            QtCore.QRegExp(
                '^(tcp:\/\/)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:\d{2,5})$'
            ))
        self.tdAddressLineEdit.setValidator(self.tdAddressValidator)
        tableGridLayout.addWidget(self.tdAddressLineEdit, rowNum, 1)

        # 行情地址
        rowNum += 1
        tableGridLayout.addWidget(QtWidgets.QLabel(text.MD_ADDRESS), rowNum, 0)
        if edit:
            self.mdAddressLineEdit = QtWidgets.QLineEdit(
                data['mdAddress'] if 'mdAddress' in data.keys() else None)
        else:
            self.mdAddressLineEdit = QtWidgets.QLineEdit('tcp://')
        # 验证TCP地址,未考虑端口超过65535的情况
        self.mdAddressValidator = QtGui.QRegExpValidator(
            QtCore.QRegExp(
                '^(tcp:\/\/)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:\d{2,5})$'
            ))
        self.mdAddressLineEdit.setValidator(self.mdAddressValidator)
        tableGridLayout.addWidget(self.mdAddressLineEdit, rowNum, 1)

        # 创建按钮
        saveButton = QtWidgets.QPushButton(text.SAVE)
        saveAndConnectButton = QtWidgets.QPushButton(text.SAVE_AND_CONNECT)
        cancelButton = QtWidgets.QPushButton(text.CANCEL)

        # 按钮布局
        buttonGridLayout = QtWidgets.QGridLayout()
        buttonGridLayout.addWidget(saveButton, 0, 1)
        buttonGridLayout.addWidget(saveAndConnectButton, 0, 2)
        buttonGridLayout.addWidget(cancelButton, 0, 3)

        # 绑定事件
        saveButton.clicked.connect(self.save)  # 确定
        cancelButton.clicked.connect(self.reject)  # 取消
        saveAndConnectButton.clicked.connect(self.saveAndConnect)

        # 整合布局
        layout = QtWidgets.QGridLayout(self)
        layout.addLayout(tableGridLayout, 0, 0)
        layout.addLayout(buttonGridLayout, 1, 0)
        self.setLayout(layout)
Пример #25
0
def labelValidator():
    return QtGui.QRegExpValidator(QtCore.QRegExp(r'^[^ \t].+'), None)
Пример #26
0
    def __init__(self, info, ft_names, counter, initial_query, table):
        """
        Initialise the dialog.
        """
        #
        # Attributes used by slot updateOKState
        #
        self.used_names = ft_names
        self.col_names = info['col_names']
        self.condvars = info['condvars']
        self.source_table = table
        self.num_rows = info['nrows']

        #
        # Attributes used by slot composeQuery
        #
        # If the dialog is cancelled these initial values will be returned to
        # the caller. If the dialog is accepted then these values will be
        # updated (in the slotAccept method) and returned to the caller
        self.query_info = {}
        self.query_info['condition'] = ''
        self.query_info['rows_range'] = ()
        self.query_info['ft_name'] = ''
        self.query_info['indices_field_name'] = ''
        self.query_info['condvars'] = self.condvars
        self.query_info['src_filepath'] = info['src_filepath']
        self.query_info['src_path'] = info['src_path']

        #
        # Create the dialog and customise the content of some widgets
        #
        super(QueryDlg, self).__init__(QtWidgets.qApp.activeWindow())
        self.setupUi(self)

        self.setWindowTitle(
            translate('QueryDlg', 'New query on table: {0}',
                      'A dialog caption').format(info['name']))

        self.nameLE.setText('FilteredTable_{0}'.format(counter))

        self.indicesColumnLE.setEnabled(0)

        # Use the values of the last query done on this table (if any)
        if initial_query != '':
            self.queryLE.setText(initial_query)

        # Fill the combos
        operators = [
            '&', '|', '~', '<', '<=', '==', '!=', '>', '>=', '+', '-', '*',
            '/', '**', '%'
        ]
        self.operatorsComboBox.insertItems(0, operators)
        functions = [
            'where', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan',
            'arctan2', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh',
            'log', 'log10', 'log1p', 'exp', 'expm1', 'sqrt', 'real', 'imag',
            'complex'
        ]
        self.functionsComboBox.insertItems(0, functions)
        sorted_fields = [field for field in info['valid_fields']]
        sorted_fields.sort()
        self.columnsComboBox.insertItems(0, sorted_fields)
        self.rstartLE.setText('0')
        self.rstopLE.setText('{0}'.format(info['nrows']))

        whatsthis_button = self.buttonBox.button(
            QtWidgets.QDialogButtonBox.Help)
        whatsthis_button.setText("&What's this")

        #
        # Setup a validator for Range selectors section
        #
        validator = QtGui.QRegExpValidator(QtCore.QRegExp("\\d*"), self)
        self.rstartLE.setValidator(validator)
        self.rstopLE.setValidator(validator)
        self.rstep.setValidator(validator)

        #
        # Connect signals to slots
        #
        self.buttonBox.helpRequested.connect(
            QtWidgets.QWhatsThis.enterWhatsThisMode)
        # Ensure that if the condition line edit is initialised with an
        # initial condition then the OK button will be enabled
        self.nameLE.textChanged.emit(self.nameLE.text())
Пример #27
0
    def __init__(
        self,
        text="Enter object label",
        parent=None,
        labels=None,
        sort_labels=True,
        show_text_field=True,
        completion="startswith",
        fit_to_content=None,
        flags=None,
    ):
        if fit_to_content is None:
            fit_to_content = {"row": False, "column": True}
        self._fit_to_content = fit_to_content

        super(LabelDialog, self).__init__(parent)
        self.edit = LabelQLineEdit()
        self.edit.setPlaceholderText(text)
        self.edit.setValidator(labelpoints.utils.labelValidator())
        self.edit.editingFinished.connect(self.postProcess)
        if flags:
            self.edit.textChanged.connect(self.updateFlags)
        self.edit_group_id = QtWidgets.QLineEdit()
        self.edit_group_id.setPlaceholderText("Group ID")
        self.edit_group_id.setValidator(
            QtGui.QRegExpValidator(QtCore.QRegExp(r"\d*"), None)
        )
        layout = QtWidgets.QVBoxLayout()
        if show_text_field:
            layout_edit = QtWidgets.QHBoxLayout()
            layout_edit.addWidget(self.edit, 6)
            layout_edit.addWidget(self.edit_group_id, 2)
            layout.addLayout(layout_edit)
        # buttons
        self.buttonBox = bb = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal,
            self,
        )
        bb.button(bb.Ok).setIcon(labelpoints.utils.newIcon("done"))
        bb.button(bb.Cancel).setIcon(labelpoints.utils.newIcon("undo"))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        layout.addWidget(bb)
        # label_list
        self.labelList = QtWidgets.QListWidget()
        if self._fit_to_content["row"]:
            self.labelList.setHorizontalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff
            )
        if self._fit_to_content["column"]:
            self.labelList.setVerticalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOff
            )
        self._sort_labels = sort_labels
        if labels:
            self.labelList.addItems(labels)
        if self._sort_labels:
            self.labelList.sortItems()
        else:
            self.labelList.setDragDropMode(
                QtWidgets.QAbstractItemView.InternalMove
            )
        self.labelList.currentItemChanged.connect(self.labelSelected)
        self.labelList.itemDoubleClicked.connect(self.labelDoubleClicked)
        self.edit.setListWidget(self.labelList)
        layout.addWidget(self.labelList)
        # label_flags
        if flags is None:
            flags = {}
        self._flags = flags
        self.flagsLayout = QtWidgets.QVBoxLayout()
        self.resetFlags()
        layout.addItem(self.flagsLayout)
        self.edit.textChanged.connect(self.updateFlags)
        self.setLayout(layout)
        # completion
        completer = QtWidgets.QCompleter()
        if not QT5 and completion != "startswith":
            logger.warn(
                "completion other than 'startswith' is only "
                "supported with Qt5. Using 'startswith'"
            )
            completion = "startswith"
        if completion == "startswith":
            completer.setCompletionMode(QtWidgets.QCompleter.InlineCompletion)
            # Default settings.
            # completer.setFilterMode(QtCore.Qt.MatchStartsWith)
        elif completion == "contains":
            completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
            completer.setFilterMode(QtCore.Qt.MatchContains)
        else:
            raise ValueError("Unsupported completion: {}".format(completion))
        completer.setModel(self.labelList.model())
        self.edit.setCompleter(completer)
Пример #28
0
    def __init__(self, *args):
        super(main_GUI, self).__init__(*args)
        self.setWindowTitle("MOSAICpy :: Modular image processing tool")
        self.LLSItemThreads = []
        self.compressionThreads = []
        self.argQueue = [
        ]  # holds all argument lists that will be sent to threads
        self.aborted = False  # current abort status
        self.spimwins = []
        self._eta = 0

        # delete and reintroduce custom folderqueue.LLSDragDropTable and imp window
        self.listbox.setParent(None)
        self.listbox = folderqueue.LLSDragDropTable(self)
        self.listbox.status_update.connect(self.statusBar.showMessage)
        self.listbox.item_starting.connect(self.initProgress)
        self.listbox.step_finished.connect(self.incrementProgress)
        self.listbox.work_finished.connect(self.onProcessFinished)
        self.listbox.eta_update.connect(self.set_eta)
        self.processSplitter.insertWidget(0, self.listbox)
        self.impListWidget.setParent(None)
        self.impContainer = implist.ImpListContainer(parent=self)
        self.impListWidget = self.impContainer.list
        self.processSplitter.addWidget(self.impContainer)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateClock)
        self.actionAbort.triggered.connect(self.listbox.abort_workers)

        handler = qtlogger.NotificationHandler()
        handler.emitSignal.connect(self.log.append)
        logger.addHandler(handler)

        self.camcorDialog = camcalibgui.CamCalibDialog()
        self.genFlashParams.clicked.connect(self.camcorDialog.show)
        self.actionCamera_Calibration.triggered.connect(self.camcorDialog.show)

        # connect buttons
        self.processButton.clicked.connect(self.onProcess)
        # self.errorOptOutCheckBox.stateChanged.connect(self.toggleOptOut)

        # def toggleActiveGPU(val):
        #     gpunum = int(self.sender().objectName().strip('useGPU_'))
        #     app = QtCore.QCoreApplication.instance()
        #     if not hasattr(app, 'gpuset'):
        #         app.gpuset = set()
        #     if val:
        #         app.gpuset.add(gpunum)
        #         logger.debug("GPU {} added to gpuset.".format(gpunum))
        #     else:
        #         if gpunum in app.gpuset:
        #             app.gpuset.remove(gpunum)
        #             logger.debug("GPU {} removed from gpuset.".format(gpunum))
        #     logger.debug("GPUset now: {}".format(app.gpuset))

        # add GPU checkboxes and add
        # try:
        #     app = QtCore.QCoreApplication.instance()
        #     if not hasattr(app, 'gpuset'):
        #         app.gpuset = set()
        #     gpulist = mosaicpy.cudabinwrapper.gpulist()
        #     if len(gpulist):
        #         for i, gpu in enumerate(gpulist):
        #             box = QtWidgets.QCheckBox(self.tab_config)
        #             box.setChecked(True)
        #             box.setObjectName('useGPU_{}'.format(i))
        #             box.setText(gpu.strip('GeForce'))
        #             box.stateChanged.connect(toggleActiveGPU)
        #             app.gpuset.add(i)
        #             self.gpuGroupBoxLayout.addWidget(box)
        #     else:
        #         label = QtWidgets.QLabel(self.tab_config)
        #         label.setText('No CUDA-capabled GPUs detected')
        #         self.gpuGroupBoxLayout.addWidget(label)

        # except mosaicpy.cudabinwrapper.CUDAbinException as e:
        #     logger.warn(e)
        #     pass

        # connect actions

        # set validators for cRange and tRange fields
        ctrangeRX = QtCore.QRegExp(r"(\d[\d-]*,?)*")  # could be better
        ctrangeValidator = QtGui.QRegExpValidator(ctrangeRX)
        self.processCRangeLineEdit.setValidator(ctrangeValidator)
        self.processTRangeLineEdit.setValidator(ctrangeValidator)
        self.previewCRangeLineEdit.setValidator(ctrangeValidator)
        self.previewTRangeLineEdit.setValidator(ctrangeValidator)

        self.preview_threads = None
        self.previewAborted = False
        self.previewButton.clicked.connect(self.onPreview)
        if not preview._spimagine:
            self.prevBackendMatplotlibRadio.setChecked(True)
            self.prevBackendSpimagineRadio.setDisabled(True)
            self.prevBackendSpimagineRadio.setText("spimagine [unavailable]")

        self.disableSpimagineCheckBox.clicked.connect(
            lambda: QtWidgets.QMessageBox.information(
                self,
                "Restart Required",
                "Please quit and restart MOSAICpy for changes to take effect",
                QtWidgets.QMessageBox.Ok,
            ))

        # connect worker signals and slots

        self.RegCalib_channelRefModeCombo.clear()
        self.RegCalib_channelRefCombo.clear()

        # Restore settings from previous session and show ready status
        settings.guirestore(self, SETTINGS, SETTINGS)

        self.RegCalibPathLineEdit.setText("")
        self.RegFilePath.setText("")

        self.clock.display("00:00:00")
        self.statusBar.showMessage("Ready")

        self.show()
        self.raise_()