コード例 #1
0
ファイル: dlg_classes.py プロジェクト: nb1987/rvac
class AddScenarioDlg(QDialog):

	def __init__(self, root_node, parent=None):
		super(AddScenarioDlg, self).__init__(parent)
		self.setWindowTitle("Add Scenario")
		
		type_label = QLabel("&Scenario Type:")
		self.type_combobox = QComboBox()
		type_label.setBuddy(self.type_combobox)
		self.type_combobox.addItems(["External Fire", "Liquid Overfill", "Regulator Failure"])
		device_label = QLabel("&Associated Relief Device:")
		self.device_combobox = QComboBox()
		device_label.setBuddy(self.device_combobox)
		for area in root_node.children:
			for device in area.children:
				self.device_combobox.addItem(device.name, device)
		button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
			
		layout = QGridLayout()
		layout.addWidget(type_label, 0, 0)
		layout.addWidget(self.type_combobox, 0, 1)
		layout.addWidget(device_label, 1, 0)
		layout.addWidget(self.device_combobox, 1, 1)
		layout.addWidget(button_box, 2, 1)
		self.setLayout(layout)
		
		button_box.accepted.connect(self.accept)
		button_box.rejected.connect(self.reject)
		
	def returnVals(self):
		return (self.type_combobox.currentText(), self.device_combobox.itemData(self.device_combobox.currentIndex()))
コード例 #2
0
class FinishWrangleItemsDialog(QDialog):
    def __init__(self, parent=None):
        super(FinishWrangleItemsDialog, self).__init__(parent)

        layout = QFormLayout(self)

        self.status_selector = QComboBox()
        status_list = ["abort", "done", "publish", "cancel"]
        for status in status_list:
            self.status_selector.addItem(str(status))

        layout.addRow("Finished Status:", self.status_selector)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        layout.addWidget(self.buttons)

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

        self.setWindowTitle("Select Finished Status")
        self.resize(250, 100)

    # get current status from the dialog
    def status(self):
        return self.status_selector.currentText()

    # static method to create the dialog and return (date, time, accepted)
    @staticmethod
    def getStatus(parent=None):
        dialog = FinishWrangleItemsDialog(parent)
        result = dialog.exec_()
        status = dialog.status()
        return (status, result == QDialog.Accepted)
コード例 #3
0
ファイル: dlg_classes.py プロジェクト: nb1987/rvac
class CopyScenarioDlg(QDialog):

	def __init__(self, root_node, parent=None):
		super(CopyScenarioDlg, self).__init__(parent)
		self.setWindowTitle("Duplicate Scenario")
		
		device_label = QLabel("&Copy Scenario To:")
		self.device_combobox = QComboBox()
		device_label.setBuddy(self.device_combobox)
		for area in root_node.children:
			for device in area.children:
				self.device_combobox.addItem(device.name, device)
		button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
			
		layout = QGridLayout()
		layout.addWidget(device_label, 0, 0)
		layout.addWidget(self.device_combobox, 0, 1)
		layout.addWidget(button_box, 1, 1)
		self.setLayout(layout)
		
		button_box.accepted.connect(self.accept)
		button_box.rejected.connect(self.reject)
		
	def returnVals(self):
		return self.device_combobox.itemData(self.device_combobox.currentIndex())
コード例 #4
0
ファイル: FnShotStatusUI.py プロジェクト: antiero/dotHiero
 def createEditor(self, row, column, item, view):
   """
     Creates the ComboBox for setting the Status
   """
   cb = QComboBox()
   for key in gStatusTags.keys():
     cb.addItem(QIcon(gStatusTags[key]), key)
   return cb
コード例 #5
0
 def createEditor(self, row, column, item, view):
     """
   Creates the ComboBox for setting the Status
 """
     cb = QComboBox()
     for key in gStatusTags.keys():
         cb.addItem(QIcon(gStatusTags[key]), key)
     return cb
コード例 #6
0
class DelegateKeepsReferenceToEditor(QAbstractItemDelegate):
    def __init__(self, parent=None):
        QAbstractItemDelegate.__init__(self, parent)
        self.comboBox = QComboBox()
        self.comboBox.addItem(id_text)

    def createEditor(self, parent, option, index):
        self.comboBox.setParent(parent)
        return self.comboBox
コード例 #7
0
class DelegateKeepsReferenceToEditor(QAbstractItemDelegate):
    def __init__(self, parent=None):
        QAbstractItemDelegate.__init__(self, parent)
        self.comboBox = QComboBox()
        self.comboBox.addItem(id_text)

    def createEditor(self, parent, option, index):
        self.comboBox.setParent(parent)
        return self.comboBox
コード例 #8
0
ファイル: dlg_classes.py プロジェクト: nb1987/rvac
class AddDeviceDlg(QDialog):

	def __init__(self, root_node, parent=None):
		super(AddDeviceDlg, self).__init__(parent)
		self.setWindowTitle("Add Relief Device")

		id_label = QLabel("&Relief Device ID:")
		self.id_lineedit = QLineEdit()
		self.id_lineedit.setMaxLength(200)
		id_label.setBuddy(self.id_lineedit)
		area_label = QLabel("Associated Relief Device &Area:")
		self.area_combobox = QComboBox()
		for area in root_node.children:
			self.area_combobox.addItem(area.name, area)
		area_label.setBuddy(self.area_combobox)
		color_label = QLabel("&Text Color:")
		self.color_combobox = QComboBox()
		for key in sorted(COLORS.keys()):
			pixmap = QPixmap(26, 26)
			pixmap.fill(COLORS[key])
			self.color_combobox.addItem(QIcon(pixmap), key)
		color_label.setBuddy(self.color_combobox)
		button_box = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
			
		layout = QGridLayout()
		layout.addWidget(id_label, 0, 0)
		layout.addWidget(self.id_lineedit, 0, 1)
		layout.addWidget(area_label, 1, 0)
		layout.addWidget(self.area_combobox, 1, 1)
		layout.addWidget(color_label, 2, 0)
		layout.addWidget(self.color_combobox, 2, 1)
		layout.addWidget(button_box, 3, 1)
		self.setLayout(layout)
		
		button_box.accepted.connect(self.accept)
		button_box.rejected.connect(self.reject)
		
	def accept(self):
		if len(self.id_lineedit.text().strip()) == 0:
			QMessageBox.warning(self, "Error: Relief Device ID Blank", "The relief device must be given an ID.", QMessageBox.Ok)
			self.id_lineedit.setFocus()
			return
		selected_area = self.area_combobox.itemData(self.area_combobox.currentIndex())
		for device in selected_area.children:
			if device.name == self.id_lineedit.text():
				QMessageBox.warning(self, "Error: Relief Device ID Already Exists", 
				"Cannot add relief device because that relief device ID already exists. Please create a new relief device ID.", QMessageBox.Ok)
				self.id_lineedit.setFocus()
				self.id_lineedit.setSelection(0, self.id_lineedit.maxLength())
				return
		QDialog.accept(self)
		
	def returnVals(self):
		return (self.id_lineedit.text(), self.area_combobox.itemData(self.area_combobox.currentIndex()),
		COLORS[self.color_combobox.currentText()])
コード例 #9
0
class TransferTaskDialog(QDialog):
    def __init__(self, parent=None):
        super(TransferTaskDialog, self).__init__(parent)

        layout = QFormLayout(self)

        self.to_queue_selector = QComboBox()
        self.from_queue_selector = QComboBox()

        queue_list = cqmanage.cqQueueList()
        for queue in queue_list:
            self.to_queue_selector.addItem(str(queue))
            self.from_queue_selector.addItem(str(queue))

        self.number_to_transfer = QLineEdit("")

        layout.addRow("To Queue:", self.to_queue_selector)
        layout.addRow("From Queue:", self.from_queue_selector)
        layout.addRow("Amount:", self.number_to_transfer)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        layout.addWidget(self.buttons)

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

        self.setWindowTitle("Transfer Tasks")
        self.resize(225, 150)

    def toQueue(self):
        return self.to_queue_selector.currentText()

    def fromQueue(self):
        return self.from_queue_selector.currentText()

    def amount(self):
        amt = self.number_to_transfer.text()
        if amt == "":
            return 0
        return int(amt)

    # static method to create the dialog and return parameter
    @staticmethod
    def getTransfer(parent=None):
        dialog = TransferTaskDialog(parent)
        result = dialog.exec_()
        toqueue = dialog.toQueue()
        fromqueue = dialog.fromQueue()
        amt = dialog.amount()
        return (toqueue, fromqueue, amt, result == QDialog.Accepted)
    def _addComboBox(self, row, col, items, currentItem=None):
        comb = QComboBox()
        for it in items:
            comb.addItem(it)
        self.table.setCellWidget(row, col, comb)

        if currentItem is not None:
            if currentItem in items:
                comb.setCurrentIndex(items.index(currentItem))
            else:
                print('invalid item: {}'.format(currentItem))

        return comb
コード例 #11
0
    def _addComboBox(self, row, col, items, currentItem=None):
        comb = QComboBox()
        for it in items:
            comb.addItem(it)
        self.table.setCellWidget(row, col, comb)

        if (currentItem is not None) and (currentItem != ''):
            if currentItem in items:
                comb.setCurrentIndex(items.index(currentItem))
            else:
                print('invalid item: {}'.format(currentItem))

        return comb
コード例 #12
0
ファイル: FnPdfExporter.py プロジェクト: weijer/dotStudio
class ExportPdfOptionDialog(QDialog):
    """
    Displays options UI for the PDF
    """

    def __init__(self, parent=None):
        if not parent:
            parent = hiero.ui.mainWindow()
        super(ExportPdfOptionDialog, self).__init__(parent)

        layout = QFormLayout()
        self._fileNameField = FnFilenameField(False, isSaveFile=False, caption="Set PDF name", filter="*.pdf")
        self._fileNameField.setFilename(os.path.join(os.getenv("HOME"), "Desktop", "Sequence.pdf"))
        self._optionDropdown = QComboBox()
        self._buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self._buttonbox.button(QDialogButtonBox.Ok).setText("Export")
        self._buttonbox.accepted.connect(self.accept)
        self._buttonbox.rejected.connect(self.reject)

        self._pdfActionSettings = {"1 Shot per page": [1, 1], "4 Shots per page)": [2, 2], "9 Shots per page)": [3, 3]}

        for pdfMode in sorted(self._pdfActionSettings, reverse=True):
            self._optionDropdown.addItem(pdfMode)

        layout.addRow("Save to:", self._fileNameField)
        layout.addRow("PDF Layout:", self._optionDropdown)
        layout.addRow("", self._buttonbox)

        self.setLayout(layout)
        self.setWindowTitle("Export PDF Options")
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

    def numRows(self):
        """Returns the number of rows for the pdf"""
        optionText = self._optionDropdown.currentText()
        return self._pdfActionSettings[optionText][0]

    def numColumns(self):
        """Returns the number of columns for the pdf"""
        optionText = self._optionDropdown.currentText()
        return self._pdfActionSettings[optionText][1]

    def filePath(self):
        """Returns the filepath for the pdf"""
        filename = self._fileNameField.filename()
        if not filename.endswith(".pdf"):
            filename = filename + ".pdf"
        return filename
コード例 #13
0
    def createOptionsGroupBox(self):
        self.optionsGroupBox = QGroupBox("Options")

        buttonsOrientationLabel = QLabel("Orientation of buttons:")

        buttonsOrientationComboBox = QComboBox()
        buttonsOrientationComboBox.addItem("Horizontal", Qt.Horizontal)
        buttonsOrientationComboBox.addItem("Vertical", Qt.Vertical)
        buttonsOrientationComboBox.currentIndexChanged[int].connect(self.buttonsOrientationChanged)

        self.buttonsOrientationComboBox = buttonsOrientationComboBox

        optionsLayout = QGridLayout()
        optionsLayout.addWidget(buttonsOrientationLabel, 0, 0)
        optionsLayout.addWidget(self.buttonsOrientationComboBox, 0, 1)
        optionsLayout.setColumnStretch(2, 1)
        self.optionsGroupBox.setLayout(optionsLayout)
コード例 #14
0
ファイル: dynamiclayouts.py プロジェクト: AmerGit/Examples
    def createOptionsGroupBox(self):
        self.optionsGroupBox = QGroupBox("Options")

        buttonsOrientationLabel = QLabel("Orientation of buttons:")

        buttonsOrientationComboBox = QComboBox()
        buttonsOrientationComboBox.addItem("Horizontal", Qt.Horizontal)
        buttonsOrientationComboBox.addItem("Vertical", Qt.Vertical)
        buttonsOrientationComboBox.currentIndexChanged[int].connect(self.buttonsOrientationChanged)

        self.buttonsOrientationComboBox = buttonsOrientationComboBox

        optionsLayout = QGridLayout()
        optionsLayout.addWidget(buttonsOrientationLabel, 0, 0)
        optionsLayout.addWidget(self.buttonsOrientationComboBox, 0, 1)
        optionsLayout.setColumnStretch(2, 1)
        self.optionsGroupBox.setLayout(optionsLayout)
コード例 #15
0
ファイル: add_dc.py プロジェクト: asymworks/python-divelog
class IntroPage(QWizardPage):
    '''
    Introduction Wizard Page
    
    Contains the introduction text and a combo box to select either a pre-
    defined computer model or a custom computer type.
    '''
    def __init__(self, parent=None):
        super(IntroPage, self).__init__(parent)
        
        self._createLayout()
        
        self.registerField('type', self._cbxType)
        self.setTitle(self.tr('Add a Dive Computer'))
        self.setSubTitle(self.tr('Select the type of Dive Computer to add.  Make sure the computer is connected and ready to download before proceeding.'))

    def nextId(self):
        'Return the next Page Id'
        if self._cbxType.currentIndex() == len(ComputerTypes):
            return Pages.Custom
        else:
            return Pages.Browse
    
    def _createLayout(self):
        'Create the Wizard Page Layout'
        
        self._cbxType = QComboBox()
        self._lblType = QLabel(self.tr('Dive Computer &Type'))
        self._lblType.setBuddy(self._cbxType)
        
        for t in ComputerTypes:
            self._cbxType.addItem(t['name'])
        self._cbxType.addItem('Custom...')
        
        gbox = QGridLayout()
        gbox.addWidget(self._lblType, 0, 0)
        gbox.addWidget(self._cbxType, 0, 1)
        
        vbox = QVBoxLayout()
        vbox.addLayout(gbox)
        vbox.addStretch()
        
        self.setLayout(vbox)
コード例 #16
0
class LandmarkWidget(QWidget):

	landmarkTypeChanged = Signal(object)

	def __init__(self):
		super(LandmarkWidget, self).__init__()
		
		self.typeLabel = QLabel("Picker type:")
		self.typeCombo = QComboBox()
		self.typeCombo.addItem("Surface")
		self.typeCombo.addItem("Two step")
		self.typeCombo.currentIndexChanged.connect(self.comboboxChanged)

		self.surfaceWidget = SurfaceLandmarkWidget()
		self.twoStepWidget = TwoStepLandmarkWidget()
		self.surfaceWidget.setHidden(True)
		self.twoStepWidget.setHidden(True)

		layout = QGridLayout()
		layout.setAlignment(Qt.AlignTop)
		layout.addWidget(self.typeLabel, 0, 0)
		layout.addWidget(self.typeCombo, 0, 1)
		layout.addWidget(self.surfaceWidget, 1, 0, 1, 2)
		layout.addWidget(self.twoStepWidget, 2, 0, 1, 2)
		self.setLayout(layout)

		self.update()

	def update(self):
		idx = self.typeCombo.currentIndex()
		if idx == 0:
			self.surfaceWidget.setHidden(False)
			self.twoStepWidget.setHidden(True)
			self.landmarkType = SurfaceType
		elif idx == 1:
			self.surfaceWidget.setHidden(True)
			self.twoStepWidget.setHidden(False)
			self.landmarkType = TwoStepType

	@Slot(int)
	def comboboxChanged(self, index):
		self.update()
		self.landmarkTypeChanged.emit(self)
コード例 #17
0
class LandmarkWidget(QWidget):

    landmarkTypeChanged = Signal(object)

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

        self.typeLabel = QLabel("Picker type:")
        self.typeCombo = QComboBox()
        self.typeCombo.addItem("Surface")
        self.typeCombo.addItem("Two step")
        self.typeCombo.currentIndexChanged.connect(self.comboboxChanged)

        self.surfaceWidget = SurfaceLandmarkWidget()
        self.twoStepWidget = TwoStepLandmarkWidget()
        self.surfaceWidget.setHidden(True)
        self.twoStepWidget.setHidden(True)

        layout = QGridLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(self.typeLabel, 0, 0)
        layout.addWidget(self.typeCombo, 0, 1)
        layout.addWidget(self.surfaceWidget, 1, 0, 1, 2)
        layout.addWidget(self.twoStepWidget, 2, 0, 1, 2)
        self.setLayout(layout)

        self.update()

    def update(self):
        idx = self.typeCombo.currentIndex()
        if idx == 0:
            self.surfaceWidget.setHidden(False)
            self.twoStepWidget.setHidden(True)
            self.landmarkType = SurfaceType
        elif idx == 1:
            self.surfaceWidget.setHidden(True)
            self.twoStepWidget.setHidden(False)
            self.landmarkType = TwoStepType

    @Slot(int)
    def comboboxChanged(self, index):
        self.update()
        self.landmarkTypeChanged.emit(self)
コード例 #18
0
ファイル: myclusterui.py プロジェクト: zenotech/MyClusterUI
 def create_combobox(self, text, choices, option, default=NoDefault,
                     tip=None):
     """choices: couples (name, key)"""
     label = QLabel(text)
     combobox = QComboBox()
     if tip is not None:
         combobox.setToolTip(tip)
     # combobox.setEditable(True)
     for name, key in choices:
         combobox.addItem(name, key)  # to_qvariant(key))
     self.comboboxes[option] = combobox
     layout = QHBoxLayout()
     for subwidget in (label, combobox):
         layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
コード例 #19
0
    def __init__(self, *args, **kwargs):
        super(Widget_ConnectionType, self).__init__(*args, **kwargs)
        self.installEventFilter(self)
        mainLayout = QVBoxLayout(self)
        mainLayout.setSpacing(0)

        self.setStyleSheet("font-size:12px;")
        w_comboBox = QWidget()
        lay_comboBox = QHBoxLayout(w_comboBox)
        lay_comboBox.setContentsMargins(5, 5, 5, 5)
        lay_comboBox.setSpacing(0)
        label = QLabel("Connection Type : ")
        comboBox = QComboBox()
        comboBox.setStyleSheet("padding:2px; padding-left:5px")
        comboBox.addItem("Long Type")
        comboBox.addItem("Enum Type")
        lay_comboBox.addWidget(label)
        lay_comboBox.addWidget(comboBox)

        w_enumAttrName = QWidget()
        lay_enumAttrName = QHBoxLayout(w_enumAttrName)
        lay_enumAttrName.setContentsMargins(5, 5, 5, 5)
        lay_enumAttrName.setSpacing(0)
        label_enumName = QLabel("Enum Attribute Name :  ")
        lineEdit = QLineEdit()
        lineEdit.setStyleSheet("padding:2px")
        lay_enumAttrName.addWidget(label_enumName)
        lay_enumAttrName.addWidget(lineEdit)
        w_enumAttrName.setEnabled(False)

        mainLayout.addWidget(w_comboBox)
        mainLayout.addWidget(w_enumAttrName)

        self.comboBox = comboBox
        self.w_enumAttrName = w_enumAttrName
        self.lineEdit = lineEdit
        self.comboBox.currentIndexChanged.connect(self.cmd_attrTypeCondition)
        self.readData()

        lineEdit.textEdited.connect(self.writeData)
        comboBox.currentIndexChanged.connect(self.writeData)
        self.readData()
コード例 #20
0
    def __init__(self, *args, **kwargs):

        super(Widget_connectionElement, self).__init__(*args, **kwargs)
        self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable
                      | QtCore.Qt.ItemIsDragEnabled
                      | QtCore.Qt.ItemIsDropEnabled)

        lineEdit_attrName = QLineEdit()

        w_targetObject = QWidget(self.treeWidget())
        lay_targetObject = QHBoxLayout(w_targetObject)
        lay_targetObject.setContentsMargins(0, 0, 0, 0)
        lay_targetObject.setSpacing(0)
        lineEdit_targetObject = QLineEdit()
        button_targetObject = QPushButton("Load")
        lay_targetObject.addWidget(lineEdit_targetObject)
        lay_targetObject.addWidget(button_targetObject)

        comboBox_targetAttr = QComboBox(self.treeWidget())
        comboBox_targetAttr.addItem("rotateX")
        comboBox_targetAttr.addItem("rotateY")
        comboBox_targetAttr.addItem("rotateZ")
        comboBox_targetAttr.addItem("rotateX(+)")
        comboBox_targetAttr.addItem("rotateY(+)")
        comboBox_targetAttr.addItem("rotateZ(+)")
        comboBox_targetAttr.addItem("rotateX(-)")
        comboBox_targetAttr.addItem("rotateY(-)")
        comboBox_targetAttr.addItem("rotateZ(-)")
        self.comboBox = comboBox_targetAttr
        self.lineEdit_targetObject = lineEdit_targetObject
        self.lineEdit_attrName = lineEdit_attrName

        self.treeWidget().setItemWidget(self, 0, lineEdit_attrName)
        self.treeWidget().setItemWidget(self, 1, w_targetObject)
        self.treeWidget().setItemWidget(self, 2, comboBox_targetAttr)
        button_targetObject.clicked.connect(self.loadTargetObject)
        comboBox_targetAttr.currentIndexChanged.connect(
            self.treeWidget().parentWidget().writeData)
コード例 #21
0
ファイル: myclusterui.py プロジェクト: Python3pkg/MyClusterUI
 def create_combobox(self,
                     text,
                     choices,
                     option,
                     default=NoDefault,
                     tip=None):
     """choices: couples (name, key)"""
     label = QLabel(text)
     combobox = QComboBox()
     if tip is not None:
         combobox.setToolTip(tip)
     # combobox.setEditable(True)
     for name, key in choices:
         combobox.addItem(name, key)  # to_qvariant(key))
     self.comboboxes[option] = combobox
     layout = QHBoxLayout()
     for subwidget in (label, combobox):
         layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
コード例 #22
0
class QueueDialog(QDialog):
    def __init__(self, parent = None):
        super(QueueDialog, self).__init__(parent)

        layout = QFormLayout(self)
        
        self.queue_selector = QComboBox()
        queue_list = cqmanage.cqQueueList()
        for queue in queue_list:
            self.queue_selector.addItem(str(queue))

        layout.addRow("Queue:", self.queue_selector)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
            Qt.Horizontal, self)
        layout.addWidget(self.buttons)

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

        self.setWindowTitle("Select Queue")
        self.resize(200, 100)

    # get current queue name from the dialog
    def queueName(self):
        return self.queue_selector.currentText()

    # static method to create the dialog and return (date, time, accepted)
    @staticmethod
    def getQueue(parent = None):
        dialog = QueueDialog(parent)
        result = dialog.exec_()
        queueName = dialog.queueName()
        return (queueName, result == QDialog.Accepted)
コード例 #23
0
ファイル: waste.py プロジェクト: tinavas/FSERP
 def add_row_to_table(self, *args):
     """
     complex stuff of auto complete to be added to each combo box
     :return:
     """
     table = self.waste_table
     if args:
         if args[0] != 'new':
             table.clearContents()
             table.setRowCount(0)
             table.setRowCount(len(args))
             for i, j in enumerate(args):
                 code = QTableWidgetItem(j['code'])
                 table.setItem(i, 0, code)
                 item = QTableWidgetItem(j['item'])
                 table.setItem(i, 1, item)
                 category = QTableWidgetItem(j['category'])
                 table.setItem(i, 2, category)
                 quantity = QTableWidgetItem(str(j['quantity']))
                 table.setItem(i, 3, quantity)
                 reason = QTableWidgetItem(j['reason_for_discard'])
                 table.setItem(i, 4, reason)
         if args[0] == 'new':
             row = table.rowCount() + 1
             table.setRowCount(row)
             codeline = QLineEdit()
             codeline.editingFinished.connect(
                 lambda: self.get_details_of_code(row))
             table.setCellWidget(row - 1, 0, codeline)
             itemcombo = QComboBox()
             self.fill_item_list(itemcombo)
             itemcombo.currentIndexChanged.connect(
                 lambda: self.get_details_of_item(row))
             table.setCellWidget(row - 1, 1, itemcombo)
             category = QTableWidgetItem()
             table.setItem(row - 1, 2, category)
             quantity = QLineEdit()
             table.setCellWidget(row - 1, 3, quantity)
             combo = QComboBox()
             combo.addItem("Cancelled")
             combo.addItem("Mishandling")
             combo.addItem("Excess")
             table.setCellWidget(row - 1, 4, combo)
     table.setColumnWidth(0, (table.width() / 5))
     table.setColumnWidth(1, (table.width() / 5))
     table.setColumnWidth(2, (table.width() / 5))
     table.setColumnWidth(3, (table.width() / 5))
     table.horizontalHeader().setStretchLastSection(
         True
     )  # important to resize last section else blank space after last column
コード例 #24
0
class ExportPdfOptionDialog(QDialog):
    """
    Displays options UI for the PDF
    """

    def __init__(self, parent = None):
        if not parent:
            parent = hiero.ui.mainWindow()
        super(ExportPdfOptionDialog, self).__init__(parent)

        layout = QFormLayout()
        self._fileNameField  = FnFilenameField(False, isSaveFile=False, caption="Set PDF name", filter='*.pdf')
        self._fileNameField.setFilename(os.path.join(os.getenv('HOME'), "Desktop", "Sequence.pdf"))
        self._pdfLayoutDropdown  = QComboBox()
        self._pdfLayoutDropdown.setToolTip("Set the PDF page layout type.")
        self._thumbFrameTypeDropdown  = QComboBox()
        self._thumbFrameTypeDropdown.setToolTip("Set which frame to take the thumbnail from.")

        self._buttonbox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self._buttonbox.button(QDialogButtonBox.Ok).setText("Export")
        self._buttonbox.accepted.connect(self.accept)
        self._buttonbox.rejected.connect(self.reject)

        self._pdfLayouts = PDFExporter.PAGE_LAYOUTS_DICT

        self._thumbFrameTypes = PDFExporter.THUMB_FRAME_TYPES

        for pdfLayout in sorted(self._pdfLayouts, reverse=True):
            self._pdfLayoutDropdown.addItem(pdfLayout)

        for frameType in self._thumbFrameTypes:
            self._thumbFrameTypeDropdown.addItem(frameType)

        layout.addRow("Save to:", self._fileNameField)
        layout.addRow("PDF Layout:", self._pdfLayoutDropdown)
        layout.addRow("Thumbnail Frame:", self._thumbFrameTypeDropdown)        
        layout.addRow("", self._buttonbox)

        self.setLayout(layout)
        self.setWindowTitle("Export PDF Options")
        self.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )

    def _thumbnailFrameType(self):
        """Returns the currently selected thumbnail frame type"""
        return self._thumbFrameTypeDropdown.currentText()

    def _numRows(self):
        """Returns the number of rows for the pdf"""
        optionText = self._pdfLayoutDropdown.currentText()
        return self._pdfLayouts[optionText][0]

    def _numColumns(self):
        """Returns the number of columns for the pdf"""
        optionText = self._pdfLayoutDropdown.currentText()
        return self._pdfLayouts[optionText][1]

    def _filePath(self):
        """Returns the filepath for the pdf"""
        filename = self._fileNameField.filename()
        if not filename.endswith('.pdf'):
            filename = filename + ".pdf"
        return filename
コード例 #25
0
ファイル: beam.py プロジェクト: pymontecarlo/pymontecarlo-gui
class BeamWizardPage(_ExpandableOptionsWizardPage):
    def __init__(self, options, parent=None):
        _ExpandableOptionsWizardPage.__init__(self, options, parent)
        self.setTitle("Beam")

    def _initUI(self):
        # Variables
        self._widgets = {}

        # Widgets
        self._cb_beam = QComboBox()
        self._wdg_beam = QStackedWidget()

        # Layouts
        layout = _ExpandableOptionsWizardPage._initUI(self)
        layout.addRow("Type of beam", self._cb_beam)
        layout.addRow(self._wdg_beam)

        # Signals
        self._cb_beam.currentIndexChanged.connect(self._onBeamChanged)
        self._cb_beam.currentIndexChanged.connect(self.valueChanged)

        return layout

    def _onBeamChanged(self):
        newindex = self._cb_beam.currentIndex()
        oldwidget = self._wdg_beam.currentWidget()
        newwidget = self._wdg_beam.widget(newindex)
        if newwidget is None:
            return

        try:
            newwidget.setValue(oldwidget.value())
        except:
            newwidget.setValue(self.options().beam)

        self._wdg_beam.setCurrentIndex(newindex)

    def initializePage(self):
        _ExpandableOptionsWizardPage.initializePage(self)

        # Clear
        self._widgets.clear()
        for i in reversed(range(self._cb_beam.count())):
            self._cb_beam.removeItem(i)
            self._wdg_beam.removeWidget(self._wdg_beam.widget(i))

        # Populate combo box
        it = self._iter_widgets("pymontecarlo.ui.gui.options.beam", "BEAMS")
        for clasz, widget_class, programs in it:
            widget = widget_class()
            self._widgets[clasz] = widget

            program_text = ", ".join(map(attrgetter("name"), programs))
            text = "{0} ({1})".format(widget.accessibleName(), program_text)
            self._cb_beam.addItem(text)
            self._wdg_beam.addWidget(widget)

            widget.setParticlesEnabled(False)
            for program in programs:
                converter = program.converter_class
                for particle in converter.PARTICLES:
                    widget.setParticleEnabled(particle, True)

            widget.valueChanged.connect(self.valueChanged)

        # Select beam
        beam = self.options().beam

        widget = self._widgets.get(beam.__class__)
        if widget is None:
            widget = next(iter(self._widgets.values()))

        widget.setValue(beam)

        self._wdg_beam.setCurrentWidget(widget)
        self._cb_beam.setCurrentIndex(self._wdg_beam.currentIndex())

    def validatePage(self):
        if not self._wdg_beam.currentWidget().hasAcceptableInput():
            return False

        self.options().beam = self._wdg_beam.currentWidget().value()

        return True

    def expandCount(self):
        try:
            return len(expand(self._wdg_beam.currentWidget().value()))
        except:
            return 0
コード例 #26
0
class SpecgramPane(BasePane):
    def __init__(self, setting_dict):
        BasePane.__init__( self )
        specLayout = QFormLayout()

        analysisLayout = QFormLayout()

        self.winLenEdit = QLineEdit()
        analysisLayout.addRow(QLabel('Window length:'),self.winLenEdit)

        self.methodCombo = QComboBox()
        self.methodCombo.addItem("Fourier")
        analysisLayout.addRow(QLabel('Method:'),self.methodCombo)

        self.winTypeCombo = QComboBox()
        self.winTypeCombo.addItem("Square (rectangular)")
        self.winTypeCombo.addItem("Hamming (raised sine-squared)")
        self.winTypeCombo.addItem("Bartlett (triangular)")
        self.winTypeCombo.addItem("Welch (parabolic)")
        self.winTypeCombo.addItem("Hanning (sine-squared)")
        self.winTypeCombo.addItem("Gaussian")
        analysisLayout.addRow(QLabel('Window type:'),self.winTypeCombo)

        analysisWidget = QGroupBox('Analysis')
        analysisWidget.setLayout(analysisLayout)
        specLayout.addWidget(analysisWidget)


        resLayout = QFormLayout()
        self.freqStepsEdit = QLineEdit()
        resLayout.addRow(QLabel('Number of frequency steps:'),self.freqStepsEdit)

        self.timeStepsEdit = QLineEdit()
        resLayout.addRow(QLabel('Number of time steps:'),self.timeStepsEdit)


        resWidget = QGroupBox('Frequency and time resolution')
        resWidget.setLayout(resLayout)
        specLayout.addWidget(resWidget)


        viewLayout = QFormLayout()
        self.autoScaleCheck = QCheckBox()
        viewLayout.addRow(QLabel('Autoscale:'),self.autoScaleCheck)

        self.dynamicRangeEdit = QLineEdit()
        viewLayout.addRow(QLabel('Dynamic range (dB):'),self.dynamicRangeEdit)

        self.maxEdit = QLineEdit()
        viewLayout.addRow(QLabel('Maximum (dB/Hz):'),self.maxEdit)

        self.preEmphAlphaEdit = QLineEdit()
        viewLayout.addRow(QLabel('Pre-emphasis alpha:'),self.preEmphAlphaEdit)


        viewWidget = QGroupBox('View settings')
        viewWidget.setLayout(viewLayout)
        specLayout.addWidget(viewWidget)



        self.prev_state = setting_dict

    def get_current_state(self):
        setting_dict = {}
        return setting_dict
コード例 #27
0
ファイル: console.py プロジェクト: gsfarm/ones-console
class ConsoleWidget(QMainWindow):
    def __init__(self):
        super(ConsoleWidget, self).__init__()
        self.setWindowTitle('1c query')

        self._connection = None

        self._home = os.path.expanduser('~/%s' % QApplication.applicationName())
        if not os.path.isdir(self._home):
            os.mkdir(self._home)

        self.queryToolBar = self.addToolBar('Query')
        self.queryAction = self.queryToolBar.addAction('Run', self.executeQuery)
        self.queryAction.setDisabled(True)

        uri_history = list()
        path = os.path.join(self._home, 'uri_history.txt')
        if os.path.isfile(path):
            uri_history = open(path, 'r').read().split('\n')

        self.connectionToolBar = self.addToolBar('Connection')
        self.connectionUriCombo = QComboBox(self)
        self.connectionUriCombo.setEditable(True)
        if not uri_history:
            self.connectionUriCombo.addItem('File="";usr="";pwd="";')
            self.connectionUriCombo.addItem('Srvr="{host}";Ref="{ref}";Usr="******";Pwd="{password}";')
        else:
            self.connectionUriCombo.addItems(uri_history)
            self.connectionUriCombo.setCurrentIndex(len(uri_history) - 1)
        self.connectionUriCombo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
        self.connectionToolBar.addWidget(self.connectionUriCombo)

        self.onesVersionCombo = QComboBox(self)
        self.onesVersionCombo.addItems(['8.3', '8.2', '8.1', '8.0'])
        self.onesVersionCombo.setCurrentIndex(0)
        self.connectionToolBar.addWidget(self.onesVersionCombo)
        self.connectAction = self.connectionToolBar.addAction('Connect', self.connectOneS)
        self.disconnectAction = self.connectionToolBar.addAction('Disconnect', self.disconnectOneS)
        self.disconnectAction.setDisabled(True)

        self.logEdit = QPlainTextEdit(self)
        self.logDock = QDockWidget('Log', self)
        self.logDock.setWidget(self.logEdit)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.logDock, Qt.Horizontal)

        self.splitter = QSplitter(Qt.Vertical, self)
        self.setCentralWidget(self.splitter)

        self.sqlEdit = QTextEdit(self)
        self.sqlEdit.setLineWrapMode(QTextEdit.NoWrap)

        path = os.path.join(self._home, 'last-sql.txt')
        if os.path.isfile(path):
            sql = open(path, 'r').read()
            self.sqlEdit.setText(sql)

        self.model = QStandardItemModel(self)
        self.tableView = QTableView(self)
        self.tableView.setModel(self.model)

        self.splitter.addWidget(self.sqlEdit)
        self.splitter.addWidget(self.tableView)
        self.splitter.setStretchFactor(0, 3)
        self.splitter.setStretchFactor(1, 2)

    def query(self, sql):
        if not self._connection:
            self.logEdit.appendPlainText('No connection')
            return None

        try:
            query = self._connection.NewObject('Query', sql)
            result = query.Execute()
        except Exception as e:
            self.logEdit.appendPlainText(str(e))
            return None

        return result

    def refresh(self, result):
        self.model.clear()

        columns = list()
        result_columns = result.Columns
        for index in range(result_columns.Count()):
            name = result_columns.Get(index).Name
            columns.append(name)

        self.model.setColumnCount(len(columns))
        for section, name in enumerate(columns):
            self.model.setHeaderData(section, Qt.Horizontal, name)

        select = result.Choose()
        self.logEdit.appendPlainText('Selected %d records' % select.Count())
        while select.Next():
            items = list()
            for index in range(len(columns)):
                value = select.Get(index)

                item = QStandardItem('')
                if isinstance(value, bool):
                    item.setText(value and 'Yes' or 'No')

                elif isinstance(value, (int, str)):
                    item.setText(str(value))

                elif isinstance(value, datetime.datetime):
                    item.setText(value.strftime('%Y.%m.%d %H:%M:%S'))

                else:
                    item.setText(str(value))
                items.append(item)

            self.model.appendRow(items)

    @Slot()
    def executeQuery(self):
        sql = self.sqlEdit.toPlainText()
        result = self.query(sql)
        if result:
            path = os.path.join(self._home, 'last-sql.txt')
            open(path, 'w').write(sql)
            self.refresh(result)

    @Slot()
    def connectOneS(self):
        uri = self.connectionUriCombo.currentText().strip()
        if not uri:
            self.logEdit.appendPlainText('Need a connection string')
            return

        version = self.onesVersionCombo.currentText()
        comName = "V%s.COMConnector" % str(version).replace('.', '')

        pythoncom.CoInitialize()
        try:
            obj = win32com.client.Dispatch(comName)
            self._connection = obj.Connect(uri)
        except Exception as e:
            self.logEdit.appendPlainText(str(e))
            return

        self.connectAction.setDisabled(True)
        self.disconnectAction.setEnabled(True)
        self.queryAction.setEnabled(True)

        uri_history = list()
        for i in range(self.connectionUriCombo.count()):
            uri_history.append(self.connectionUriCombo.itemText(i))

        if uri not in uri_history:
            self.connectionUriCombo.clearEditText()
            self.connectionUriCombo.addItem(uri)
            self.connectionUriCombo.setCurrentIndex(len(uri_history))
            uri_history.append(uri)
            path = os.path.join(self._home, 'uri_history.txt')
            open(path, 'w').write('\n'.join(uri_history))

    @Slot()
    def disconnectOneS(self):
        pythoncom.CoUninitialize()
        self._connection = None
        self.connectAction.setEnabled(True)
        self.disconnectAction.setDisabled(True)
        self.queryAction.setDisabled(True)
コード例 #28
0
ファイル: loader.py プロジェクト: hineybush/keyplus
class FileSelector(QWidget):
    ScopeLayout = 0
    ScopeDevice = 1
    ScopeFirmware = 2
    ScopeAll = 3

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

        self.initUI()
        self.lastDir = None

    def initUI(self):

        self.scopeSelector = QComboBox()
        self.scopeSelector.addItem("Layout", FileSelector.ScopeLayout)
        self.scopeSelector.addItem("Device and RF", FileSelector.ScopeDevice)
        self.scopeSelector.addItem("Firmware Update",
                                   FileSelector.ScopeFirmware)
        # self.scopeSelector.addItem("All", FileSelector.ScopeAll)

        self.scopeSelector.currentIndexChanged.connect(self.scopeUpdate)

        self.layoutSettings = LayoutSettingsScope()
        self.deviceSettings = DeviceSettingsScope()
        self.firmwareSettings = FirmwareSettingsScope()

        self.scope = None

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.scopeSelector)

        self.stackedLayout = QStackedLayout()
        self.stackedLayout.addWidget(self.layoutSettings)
        self.stackedLayout.addWidget(self.deviceSettings)
        self.stackedLayout.addWidget(self.firmwareSettings)

        self.layout.addLayout(self.stackedLayout)

        self.setMinimumSize(0, 300)

        self.setLayout(self.layout)
        # self.updateUI(FileSelector.ScopeLayout)

    def scopeUpdate(self, index):
        self.stackedLayout.setCurrentIndex(index)

    def updateUI(self, scope):
        if self.scope == scope:
            return

        self.layout.removeWidget(self.layoutSettings)
        self.layout.removeWidget(self.deviceSettings)
        self.layout.removeWidget(self.firmwareSettings)

        if scope == FileSelector.ScopeLayout:
            self.layout.addWidget(self.layoutSettings)
        elif scope == FileSelector.ScopeDevice:
            self.layout.addWidget(self.deviceSettings)
        elif scope == FileSelector.ScopeFirmware:
            self.layout.addWidget(self.firmwareSettings)
        elif scope == FileSelector.ScopeAll:
            self.layout.addWidget(self.layoutSettings)
            self.layout.addWidget(self.deviceSettings)
            self.layout.addWidget(self.firmwareSettings)

    def getProgramingInfo(self):
        return self.scopeSelector.currentIndex()

    def getFirmwareFile(self):
        return self.firmwareSettings.getFirmwareFile()

    def getLayoutFile(self):
        return self.layoutSettings.getLayoutFile()

    def getRFLayoutFile(self):
        return self.deviceSettings.getCurrentSettings()[2]

    def getRFFile(self):
        return self.deviceSettings.getCurrentSettings()[1]

    def getTargetID(self):
        return self.deviceSettings.getCurrentSettings()[0]
コード例 #29
0
class ParameterBox(QWidget):
    '''ParameterBox is a widget to select certain parameters for the numerical
    simulation.
    
    Arguments
    ---------
    parent : QWidget
        the parent widget        
    '''
        
    def __init__(self, parent):
        super(ParameterBox, self).__init__(parent)
        
        
        '''
        sliders
        '''

        self.sliders = {}

        slider = ParameterSlider(self, 'F')        
        slider.set_range(0, 0.1, 0.001)
        slider.set_value(0.035)
        self.sliders['F'] = slider            

        slider = ParameterSlider(self, 'k')        
        slider.set_range(0, 0.1, 0.001)
        slider.set_value(0.06)
        self.sliders['k'] = slider
        
        slider = ParameterSlider(self, 'timesteps')
        slider.set_format('.0f')
        slider.set_range(0, 100000, 1000)
        slider.set_value(10000)        
        self.sliders['timesteps'] = slider
        
        slider = ParameterSlider(self, 'keyframe distance')
        slider.set_format('.0f')
        slider.set_range(1, 100, 1)
        slider.set_value(10)
        self.sliders['keyframe_distance'] = slider
        
        slider = ParameterSlider(self, 'size')        
        slider.set_format('.0f')
        slider.set_range(32, 256, 32)
        slider.set_value(128)
        self.sliders['size'] = slider
        
        
        '''
        Combo box for default settings
        '''        
        
        self.default_coefficients = QComboBox()
        self.default_coefficients.setEditable(False)            
        for key in sorted([key for key in predefined_coefficients]):
            self.default_coefficients.addItem(key)        
        self.default_coefficients.activated.connect(self._load_predefined)
        self.default_coefficients.setCurrentIndex(0)
        self._load_predefined(0)        
        
        
        '''
        create layout
        '''        

        box = QVBoxLayout()
        box.addWidget(self.default_coefficients)
        box.addWidget(self.sliders['F'])
        box.addWidget(self.sliders['k'])
        box.addWidget(self.sliders['timesteps'])
        box.addWidget(self.sliders['keyframe_distance'])
        box.addWidget(self.sliders['size'])
        self.setLayout(box)
        
    def _load_predefined(self, index):
        key = self.default_coefficients.itemText(index)
        if key in predefined_coefficients:            
            coefficients = predefined_coefficients[key]            
            self.sliders['F'].set_value(coefficients['F'])
            self.sliders['k'].set_value(coefficients['k'])            

    def parameters(self):                
        coefficients = {}
        coefficients['Du'] = 0.16
        coefficients['Dv'] = 0.08
        coefficients['F'] = self.sliders['F'].value()
        coefficients['k'] = self.sliders['k'].value()
        
        params = {}
        params['coefficients'] = coefficients
        params['keyframe_distance'] = int(self.sliders['keyframe_distance'].value())
        params['size'] = int(self.sliders['size'].value())
        params['timesteps'] = int(self.sliders['timesteps'].value())                          
        
        return params
コード例 #30
0
class Panel(QWidget):

    changed = Signal()

    def __init__(self, state, parent):
        super().__init__(parent)
        self.state = state
        self.form = parent
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()

    def makeEditor(self, tip=None):
        editor = Widgets.LineEdit.SpacesHtmlLineEdit(self.state, None)
        if tip is not None:
            self.form.tooltips.append((editor, tip))
        return editor

    def createWidgets(self):
        self.escapeFunctionComboBox = QComboBox()
        self.escapeFunctionComboBox.addItem("HTML:  &→&amp;  <→&lt;  >→&gt;")
        self.escapeFunctionComboBox.addItem("UCP:  <→<<>  >→<>>")
        self.form.tooltips.append((self.escapeFunctionComboBox, """\
<p><b>Escape</b></p>
<p>The character escaping to use.</p>"""))

        self.pageRangeSeparatorEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 8)
        self.form.tooltips.append((self.pageRangeSeparatorEdit, """\
<p><b>Page Range Separator</b></p>
<p>The character or text to use in page ranges (e.g., an en-dash
“\u2013”).</p>"""))

        self.stdFontStartEdit = self.makeEditor("""\
<p><b>Character, Start, Std. Font</b></p>
<p>The markup to use to start using the standard font family and
size.</p>{}""".format(BLANK_SPACE_HTML))
        self.stdFontEndEdit = self.makeEditor("""\
<p><b>Character, End, Std. Font</b></p>
<p>The markup to use to end using the standard font family and
size.</p>{}""".format(BLANK_SPACE_HTML))
        self.altFontStartEdit = self.makeEditor("""\
<p><b>Character, Start, Alt. Font</b></p>
<p>The markup to use to start using the alternative font family and
size.</p>{}""".format(BLANK_SPACE_HTML))
        self.altFontEndEdit = self.makeEditor("""\
<p><b>Character, End, Alt. Font</b></p>
<p>The markup to use to end using the alternative font family and
size.</p>{}""".format(BLANK_SPACE_HTML))
        self.monoFontStartEdit = self.makeEditor("""\
<p><b>Character, Start, Mono. Font</b></p>
<p>The markup to use to start using the monospaced font family and
size.</p>{}""".format(BLANK_SPACE_HTML))
        self.monoFontEndEdit = self.makeEditor("""\
<p><b>Character, End, Mono. Font</b></p>
<p>The markup to use to end using the monospaced font family and
size.</p>{}""".format(BLANK_SPACE_HTML))
        self.boldStartEdit = self.makeEditor("""\
<p><b>Character, Start, Bold</b></p>
<p>The markup to use to start bold text.</p>{}""".format(BLANK_SPACE_HTML))
        self.boldEndEdit = self.makeEditor("""\
<p><b>Character, End, Bold</b></p>
<p>The markup to use to end bold text.</p>{}""".format(BLANK_SPACE_HTML))
        self.italicStartEdit = self.makeEditor("""\
<p><b>Character, Start, Italic</b></p>
<p>The markup to use to start italic
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.italicEndEdit = self.makeEditor("""\
<p><b>Character, End, Italic</b></p>
<p>The markup to use to end italic text.</p>{}""".format(BLANK_SPACE_HTML))
        self.subscriptStartEdit = self.makeEditor("""\
<p><b>Character, Start, Subscript</b></p>
<p>The markup to use to start subscript
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.subscriptEndEdit = self.makeEditor("""\
<p><b>Character, End, Subscript</b></p>
<p>The markup to use to end subscript
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.superscriptStartEdit = self.makeEditor("""\
<p><b>Character, Start, Superscript</b></p>
<p>The markup to use to start superscript
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.superscriptEndEdit = self.makeEditor("""\
<p><b>Character, End, Superscript</b></p>
<p>The markup to use to end superscript
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.underlineStartEdit = self.makeEditor("""\
<p><b>Character, Start, Underline</b></p>
<p>The markup to use to start underlined
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.underlineEndEdit = self.makeEditor("""\
<p><b>Character, End, Underline</b></p>
<p>The markup to use to end underlined
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.strikeoutStartEdit = self.makeEditor("""\
<p><b>Character, Start, Strikeout</b></p>
<p>The markup to use to start strikeout
text.</p>{}""".format(BLANK_SPACE_HTML))
        self.strikeoutEndEdit = self.makeEditor("""\
<p><b>Character, End, Strikeout</b></p>
<p>The markup to use to end strikeout
text.</p>{}""".format(BLANK_SPACE_HTML))

        self.topLeftForm = QFormLayout()
        self.topLeftForm.addRow("E&scape", self.escapeFunctionComboBox)
        self.topRightForm = QFormLayout()
        self.topRightForm.addRow("&Page Range Separator",
                                 self.pageRangeSeparatorEdit)

        self.startForm = QFormLayout()
        self.startForm.addRow("", QLabel("Start"))
        self.startForm.addRow("Std. Fo&nt", self.stdFontStartEdit)
        self.startForm.addRow("Alt. &Font", self.altFontStartEdit)
        self.startForm.addRow("&Mono. Font", self.monoFontStartEdit)
        self.startForm.addRow("&Bold", self.boldStartEdit)
        self.startForm.addRow("&Italic", self.italicStartEdit)
        self.startForm.addRow("Subscrip&t", self.subscriptStartEdit)
        self.startForm.addRow("Supe&rscript", self.superscriptStartEdit)
        self.startForm.addRow("&Underline", self.underlineStartEdit)
        self.startForm.addRow("Stri&keout", self.strikeoutStartEdit)

        self.endForm = QFormLayout()
        self.endForm.addRow("", QLabel("End"))
        self.endForm.addRow(self.stdFontEndEdit)
        self.endForm.addRow(self.altFontEndEdit)
        self.endForm.addRow(self.monoFontEndEdit)
        self.endForm.addRow(self.boldEndEdit)
        self.endForm.addRow(self.italicEndEdit)
        self.endForm.addRow(self.subscriptEndEdit)
        self.endForm.addRow(self.superscriptEndEdit)
        self.endForm.addRow(self.underlineEndEdit)
        self.endForm.addRow(self.strikeoutEndEdit)

    def layoutWidgets(self):
        vbox = QVBoxLayout()
        grid = QGridLayout()
        grid.addLayout(self.topLeftForm, 0, 0)
        grid.addLayout(self.topRightForm, 0, 1)
        grid.addLayout(self.startForm, 1, 0)
        grid.addLayout(self.endForm, 1, 1)
        vbox.addLayout(grid)
        vbox.addStretch()

        self.setLayout(vbox)
        self.setTabOrder(self.stdFontStartEdit, self.stdFontEndEdit)
        self.setTabOrder(self.altFontStartEdit, self.altFontEndEdit)
        self.setTabOrder(self.monoFontStartEdit, self.monoFontEndEdit)
        self.setTabOrder(self.boldStartEdit, self.boldEndEdit)
        self.setTabOrder(self.italicStartEdit, self.italicEndEdit)
        self.setTabOrder(self.subscriptStartEdit, self.subscriptEndEdit)
        self.setTabOrder(self.superscriptStartEdit, self.superscriptEndEdit)
        self.setTabOrder(self.underlineStartEdit, self.underlineEndEdit)
        self.setTabOrder(self.strikeoutStartEdit, self.strikeoutEndEdit)

    def createConnections(self):
        self.escapeFunctionComboBox.currentIndexChanged.connect(self.changed)
        self.pageRangeSeparatorEdit.textChanged.connect(self.changed)
        self.stdFontStartEdit.textChanged.connect(self.changed)
        self.stdFontEndEdit.textChanged.connect(self.changed)
        self.altFontStartEdit.textChanged.connect(self.changed)
        self.altFontEndEdit.textChanged.connect(self.changed)
        self.monoFontStartEdit.textChanged.connect(self.changed)
        self.monoFontEndEdit.textChanged.connect(self.changed)
        self.boldStartEdit.textChanged.connect(self.changed)
        self.boldEndEdit.textChanged.connect(self.changed)
        self.italicStartEdit.textChanged.connect(self.changed)
        self.italicEndEdit.textChanged.connect(self.changed)
        self.subscriptStartEdit.textChanged.connect(self.changed)
        self.subscriptEndEdit.textChanged.connect(self.changed)
        self.superscriptStartEdit.textChanged.connect(self.changed)
        self.superscriptEndEdit.textChanged.connect(self.changed)
        self.underlineStartEdit.textChanged.connect(self.changed)
        self.underlineEndEdit.textChanged.connect(self.changed)
        self.strikeoutStartEdit.textChanged.connect(self.changed)
        self.strikeoutEndEdit.textChanged.connect(self.changed)

    def populateFromMarkup(self, markup):
        with Lib.BlockSignals(self):
            self.escapeFunctionComboBox.setCurrentIndex(
                0 if markup.escapefunction == "html" else 1)
            self.pageRangeSeparatorEdit.setPlainText(markup.RangeSeparator)
            self.stdFontStartEdit.setPlainText(markup.StdFontStart)
            self.stdFontEndEdit.setPlainText(markup.StdFontEnd)
            self.altFontStartEdit.setPlainText(markup.AltFontStart)
            self.altFontEndEdit.setPlainText(markup.AltFontEnd)
            self.monoFontStartEdit.setPlainText(markup.MonoFontStart)
            self.monoFontEndEdit.setPlainText(markup.MonoFontEnd)
            self.boldStartEdit.setPlainText(markup.BoldStart)
            self.boldEndEdit.setPlainText(markup.BoldEnd)
            self.italicStartEdit.setPlainText(markup.ItalicStart)
            self.italicEndEdit.setPlainText(markup.ItalicEnd)
            self.subscriptStartEdit.setPlainText(markup.SubscriptStart)
            self.subscriptEndEdit.setPlainText(markup.SubscriptEnd)
            self.superscriptStartEdit.setPlainText(markup.SuperscriptStart)
            self.superscriptEndEdit.setPlainText(markup.SuperscriptEnd)
            self.underlineStartEdit.setPlainText(markup.UnderlineStart)
            self.underlineEndEdit.setPlainText(markup.UnderlineEnd)
            self.strikeoutStartEdit.setPlainText(markup.StrikeoutStart)
            self.strikeoutEndEdit.setPlainText(markup.StrikeoutEnd)

    def updateMarkup(self, markup):
        markup.escapefunction = ("html"
                                 if self.escapeFunctionComboBox.currentIndex()
                                 == 0 else "ucp")
        markup.RangeSeparator = self.pageRangeSeparatorEdit.toPlainText()
        markup.AltFontStart = self.altFontStartEdit.toPlainText()
        markup.AltFontEnd = self.altFontEndEdit.toPlainText()
        markup.MonoFontStart = self.monoFontStartEdit.toPlainText()
        markup.MonoFontEnd = self.monoFontEndEdit.toPlainText()
        markup.StdFontStart = self.stdFontStartEdit.toPlainText()
        markup.StdFontEnd = self.stdFontEndEdit.toPlainText()
        markup.BoldStart = self.boldStartEdit.toPlainText()
        markup.BoldEnd = self.boldEndEdit.toPlainText()
        markup.ItalicStart = self.italicStartEdit.toPlainText()
        markup.ItalicEnd = self.italicEndEdit.toPlainText()
        markup.SubscriptEnd = self.subscriptStartEdit.toPlainText()
        markup.SubscriptStart = self.subscriptEndEdit.toPlainText()
        markup.SuperscriptEnd = self.superscriptStartEdit.toPlainText()
        markup.SuperscriptStart = self.superscriptEndEdit.toPlainText()
        markup.UnderlineStart = self.underlineStartEdit.toPlainText()
        markup.UnderlineEnd = self.underlineEndEdit.toPlainText()
        markup.StrikeoutStart = self.strikeoutStartEdit.toPlainText()
        markup.StrikeoutEnd = self.stdFontEndEdit.toPlainText()
コード例 #31
0
ファイル: guiv2.py プロジェクト: dylziez/SMG
class UiMain(QMainWindow):

    """ The main gui interface, invokes all windows and ties everything
     together
    """

    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()
        
    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""")
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(self.start_btn, SIGNAL("clicked()"),
                        lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL
                       ("clicked()"), self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off, SIGNAL
                       ("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)")
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(
                    target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
コード例 #32
0
class _PhotonIntensityResultOptionsToolItem(_ResultToolItem):
    def _initUI(self):
        # Variables
        solidangle_sr = self.options().detectors[self.key()].solidangle_sr
        self._factors = {
            "counts / (s.A)": solidangle_sr / physics.e,
            "counts / (s.nA)": solidangle_sr / physics.e / 1e9,
        }

        # Widgets
        self._cb_unit = QComboBox()
        self._cb_unit.addItem("counts / (sr.electron)")
        self._cb_unit.addItem("counts / (s.A)")
        self._cb_unit.addItem("counts / (s.nA)")

        self._chk_uncertainty = QCheckBox("Show uncertainties")
        self._chk_uncertainty.setChecked(True)

        self._chk_pg = QCheckBox("No fluorescence")
        self._chk_pg.setChecked(True)

        self._chk_cg = QCheckBox("Characteristic fluorescence")
        self._chk_cg.setChecked(True)

        self._chk_bg = QCheckBox("Bremsstrahlung fluorescence")
        self._chk_bg.setChecked(True)

        self._chk_tg = QCheckBox("Total")
        self._chk_tg.setChecked(True)

        self._chk_pe = QCheckBox("No fluorescence")
        self._chk_pe.setChecked(True)

        self._chk_ce = QCheckBox("Characteristic fluorescence")
        self._chk_ce.setChecked(True)

        self._chk_be = QCheckBox("Bremsstrahlung fluorescence")
        self._chk_be.setChecked(True)

        self._chk_te = QCheckBox("Total")
        self._chk_te.setChecked(True)

        # Layouts
        layout = _ResultToolItem._initUI(self)
        layout.addRow("Unit", self._cb_unit)
        layout.addRow(self._chk_uncertainty)

        boxlayout = QVBoxLayout()
        boxlayout.addWidget(self._chk_pg)
        boxlayout.addWidget(self._chk_cg)
        boxlayout.addWidget(self._chk_bg)
        boxlayout.addWidget(self._chk_tg)

        box_generated = QGroupBox("Generated intensities (no absorption)")
        box_generated.setLayout(boxlayout)
        layout.addRow(box_generated)

        boxlayout = QVBoxLayout()
        boxlayout.addWidget(self._chk_pe)
        boxlayout.addWidget(self._chk_ce)
        boxlayout.addWidget(self._chk_be)
        boxlayout.addWidget(self._chk_te)

        box_emitted = QGroupBox("Emitted intensities (with absorption)")
        box_emitted.setLayout(boxlayout)
        layout.addRow(box_emitted)

        # Signals
        self._cb_unit.currentIndexChanged.connect(self.stateChanged)
        self._chk_uncertainty.stateChanged.connect(self.stateChanged)
        self._chk_pg.stateChanged.connect(self.stateChanged)
        self._chk_cg.stateChanged.connect(self.stateChanged)
        self._chk_bg.stateChanged.connect(self.stateChanged)
        self._chk_tg.stateChanged.connect(self.stateChanged)
        self._chk_pe.stateChanged.connect(self.stateChanged)
        self._chk_ce.stateChanged.connect(self.stateChanged)
        self._chk_be.stateChanged.connect(self.stateChanged)
        self._chk_te.stateChanged.connect(self.stateChanged)

        return layout

    def showUncertainty(self):
        return self._chk_uncertainty.isChecked()

    def showGenerated(self):
        return (self._chk_pg.isChecked(), self._chk_cg.isChecked(), self._chk_bg.isChecked(), self._chk_tg.isChecked())

    def showEmitted(self):
        return (self._chk_pe.isChecked(), self._chk_ce.isChecked(), self._chk_be.isChecked(), self._chk_te.isChecked())

    def factor(self):
        unit = self._cb_unit.currentText()
        return self._factors.get(unit, 1.0)
コード例 #33
0
ファイル: SpecificOutput.py プロジェクト: ra2003/xindex
class Panel(QWidget):

    def __init__(self, state, config, parent):
        super().__init__(parent)
        self.state = state
        self.config = config
        self.form = parent
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()


    def createWidgets(self):
        settings = QSettings()

        self.txtGroupBox = QGroupBox("Plain Text Format (.txt)")
        self.indentLabel = QLabel("&Indent")
        self.indentComboBox = QComboBox()
        self.indentLabel.setBuddy(self.indentComboBox)
        oldIndent = IndentKind.TAB
        oldIndent = self.config.get(Gconf.Key.Indent, oldIndent)
        index = -1
        for i, indent in enumerate(IndentKind):
            text = indent.name.replace("_", " ").title()
            self.indentComboBox.addItem(text, indent.value)
            if indent is oldIndent:
                index = i
        self.indentComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.indentComboBox, """\
<p><b>Indent</b></p>
<p>The indentation to use when outputting an indented-style index in
plain text format for each level of indentation.</p>"""))

        self.rtfGroupBox = QGroupBox("Rich Text Format (.rtf)")
        self.rtfIndentLabel = QLabel("I&ndent")
        self.rtfIndentComboBox = QComboBox()
        self.rtfIndentLabel.setBuddy(self.rtfIndentComboBox)
        oldIndent = IndentKind(int(settings.value(Gopt.Key.IndentRTF,
                                                  Gopt.Default.IndentRTF)))
        index = -1
        for i, indent in enumerate(IndentKind):
            text = ("Indent" if i == 0 else
                    indent.name.replace("_", " ").title())
            self.rtfIndentComboBox.addItem(text, indent.value)
            if indent is oldIndent:
                index = i
        self.rtfIndentComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.rtfIndentComboBox, """\
<p><b>Indent</b></p>
<p>The indentation to use when outputting an indented-style index in
rich text format for each level of indentation.</p>"""))

        self.pdfGroupBox = QGroupBox("Portable Document Format (.pdf)")
        self.paperSizeLabel = QLabel("Paper Size")
        self.letterRadioButton = QRadioButton("&Letter")
        self.a4RadioButton = QRadioButton("&A4")
        size = PaperSizeKind(int(settings.value(Gopt.Key.PaperSize,
                                                Gopt.Default.PaperSize)))
        if size is PaperSizeKind.LETTER:
            self.letterRadioButton.setChecked(True)
        else:
            self.a4RadioButton.setChecked(True)
        self.form.tooltips.append((self.letterRadioButton, """\
<p><b>Paper Size, Letter</b></p>
<p>If checked, when outputting a PDF of the index, US Letter
8.5"x11"-sized pages will be used.</p>"""))
        self.form.tooltips.append((self.a4RadioButton, """\
<p><b>Paper Size, A4</b></p>
<p>If checked, when outputting a PDF of the index, European A4-sized
pages will be used.</p>"""))


    def layoutWidgets(self):
        hbox = QHBoxLayout()
        hbox.addWidget(self.indentLabel)
        hbox.addWidget(self.indentComboBox)
        hbox.addStretch()
        self.txtGroupBox.setLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(self.rtfIndentLabel)
        hbox.addWidget(self.rtfIndentComboBox)
        hbox.addStretch()
        self.rtfGroupBox.setLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(self.paperSizeLabel)
        hbox.addWidget(self.letterRadioButton)
        hbox.addWidget(self.a4RadioButton)
        hbox.addStretch()
        self.pdfGroupBox.setLayout(hbox)

        vbox = QVBoxLayout()
        vbox.addWidget(self.rtfGroupBox)
        vbox.addWidget(self.txtGroupBox)
        vbox.addWidget(self.pdfGroupBox)
        vbox.addStretch()

        self.setLayout(vbox)


    def createConnections(self):
        self.indentComboBox.currentIndexChanged.connect(self.setIndent)
        self.rtfIndentComboBox.currentIndexChanged.connect(
            self.setIndentRTF)


    def setIndent(self, index):
        index = self.indentComboBox.currentIndex()
        indent = int(self.indentComboBox.itemData(index))
        if bool(self.state.model):
            self.state.model.setConfig(Gconf.Key.Indent, indent)


    def setIndentRTF(self, index):
        index = self.rtfIndentComboBox.currentIndex()
        indent = int(self.rtfIndentComboBox.itemData(index))
        settings = QSettings()
        settings.setValue(Gopt.Key.IndentRTF, indent)
コード例 #34
0
 def createEditor(self, parent, option, index):
     comboBox = QComboBox(parent)
     comboBox.addItem(id_text)
     return comboBox
コード例 #35
0
class RenderParameterWidget(QWidget):
	"""
	RenderParameterWidget is a widget that is shown in the render property
	widget. It holds a combo box with which different visualizations can be
	chosen. Beneath the combo box it displays a widget in a scroll view that
	contains widgets with which parameters of the visualization can be adjusted.
	"""

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

		self.renderController = renderController
		self.renderController.visualizationChanged.connect(self.visualizationLoaded)

		self.paramWidget = None

		self.visTypeComboBox = QComboBox()
		for visualizationType in self.renderController.visualizationTypes:
			self.visTypeComboBox.addItem(visualizationType)

		layout = QGridLayout()
		layout.setAlignment(Qt.AlignTop)
		layout.setSpacing(10)
		layout.setContentsMargins(10, 0, 10, 0)
		if len(self.renderController.visualizationTypes) > 1:
			layout.addWidget(QLabel("Visualization type:"), 0, 0)
			layout.addWidget(self.visTypeComboBox, 0, 1)
		self.setLayout(layout)

		self.scrollArea = QScrollArea()
		self.scrollArea.setFrameShape(QFrame.NoFrame)
		self.scrollArea.setAutoFillBackground(False)
		self.scrollArea.setAttribute(Qt.WA_TranslucentBackground)
		self.scrollArea.setWidgetResizable(True)

		self.visTypeComboBox.currentIndexChanged.connect(self.visTypeComboBoxChanged)

	def UpdateWidgetFromRenderWidget(self):
		"""
		Update the parameter widget with a widget from the render widget.
		"""
		# Add the scroll area for the parameter widget if it is not there yet
		layout = self.layout()
		if layout.indexOf(self.scrollArea) == -1:
			layout.addWidget(self.scrollArea, 1, 0, 1, 2)
			self.setLayout(layout)

		# Clear the previous parameter widget
		if self.paramWidget is not None:
			self.paramWidget.setParent(None)
			if self.renderController.visualization is not None:
				self.renderController.visualization.disconnect(SIGNAL("updatedTransferFunction"), self.transferFunctionChanged)

		# Get a new parameter widget from the render widget
		self.paramWidget = self.renderController.getParameterWidget()
		Style.styleWidgetForTab(self.paramWidget)
		self.scrollArea.setWidget(self.paramWidget)

		if self.renderController.visualization is not None:
			self.renderController.visualization.updatedTransferFunction.connect(self.transferFunctionChanged)

		self.visTypeComboBox.setCurrentIndex(self.visTypeComboBox.findText(self.renderController.visualizationType))

	@Slot(int)
	def visTypeComboBoxChanged(self, index):
		"""
		Slot that changes the render type. Also updates parameters and makes
		sure that the renderWidget renders with the new visualizationType.
		:type index: any
		"""
		self.renderController.setVisualizationType(self.visTypeComboBox.currentText())
		self.UpdateWidgetFromRenderWidget()
		self.renderController.updateVisualization()

	def visualizationLoaded(self, visualization):
		self.UpdateWidgetFromRenderWidget()

	@Slot()
	def transferFunctionChanged(self):
		"""
		Slot that can be used when a transfer function has changed so that
		the render will be updated afterwards.
		Should be called on valueChanged by the widgets from the parameter widget.
		"""
		self.renderController.updateVisualization()
コード例 #36
0
ファイル: beso_fc_gui.py プロジェクト: DevinCharles/beso
class beso_gui(QDialog):
    def __init__(self):
        super().__init__()
        self.title = 'BESO Topology Optimization (experimental)'
        self.left = 250
        self.top = 30
        self.width = 550
        self.height = 730

        beso_gui.inp_file = ""
        beso_gui.beso_dir = os.path.dirname(__file__)

        self.initUI()

    # def closeEvent(self, event):
    #     self.close()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Select analysis file button
        button = QPushButton('Select analysis file', self)
        button.setToolTip('*.inp CalculiX analysis file.')
        button.move(10, 10)
        button.clicked.connect(self.on_click)

        # Text box - file path and name
        self.textbox_file_name = QLineEdit(self)
        self.textbox_file_name.move(120, 15)
        self.textbox_file_name.resize(420, 20)
        self.textbox_file_name.setText("None analysis file selected")
        self.textbox_file_name.setToolTip('Analysis file.')

        # Update button
        button1 = QPushButton('Update domains', self)
        button1.setToolTip(
            'Update naming inputs and material data from FreeCAD.')
        button1.move(10, 50)
        button1.clicked.connect(self.on_click1)

        # Domains definition

        # Label above domains definition
        label21 = QLabel('Domain 0', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(120, 50)

        label21 = QLabel('Domain 1', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(260, 50)

        label21 = QLabel('Domain 2', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(400, 50)

        label24 = QLabel('Material object', self)
        label24.move(20, 80)

        label25 = QLabel('Thickness object', self)
        label25.move(20, 110)

        label26 = QLabel('As design domain', self)
        label26.move(20, 140)

        label27 = QLabel('Stress limit [MPa]', self)
        label27.move(20, 170)

        # Combo box - select domain by material object
        self.combo = QComboBox(self)
        self.combo.setToolTip('Material object to define the domain.')
        self.combo.move(120, 80)
        self.combo.resize(140, 30)
        self.combo.currentIndexChanged.connect(self.on_change)

        self.combo1 = QComboBox(self)
        self.combo1.setToolTip('Material object to define the domain.')
        self.combo1.move(260, 80)
        self.combo1.resize(140, 30)
        self.combo1.currentIndexChanged.connect(self.on_change1)

        self.combo2 = QComboBox(self)
        self.combo2.setToolTip('Material object to define the domain.')
        self.combo2.move(400, 80)
        self.combo2.resize(140, 30)
        self.combo2.currentIndexChanged.connect(self.on_change2)

        # Combo box - select thickness object
        self.combo0t = QComboBox(self)
        self.combo0t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo0t.move(120, 110)
        self.combo0t.resize(140, 30)

        self.combo1t = QComboBox(self)
        self.combo1t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo1t.move(260, 110)
        self.combo1t.resize(140, 30)

        self.combo2t = QComboBox(self)
        self.combo2t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo2t.move(400, 110)
        self.combo2t.resize(140, 30)

        self.textbox3 = QLineEdit(self)
        self.textbox3.move(120, 170)
        self.textbox3.resize(40, 20)
        # self.textbox3.setText("")
        self.textbox3.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox4 = QLineEdit(self)
        self.textbox4.move(260, 170)
        self.textbox4.resize(40, 20)
        # self.textbox4.setText("")
        self.textbox4.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox5 = QLineEdit(self)
        self.textbox5.move(400, 170)
        self.textbox5.resize(40, 20)
        # self.textbox5.setText("")
        self.textbox5.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        # Check box - design or nondesign
        self.checkbox = QCheckBox('', self)
        self.checkbox.setChecked(True)
        self.checkbox.setToolTip('Check to be the design domain.')
        self.checkbox.move(120, 140)

        self.checkbox1 = QCheckBox('', self)
        self.checkbox1.setChecked(True)
        self.checkbox1.setToolTip('Check to be the design domain.')
        self.checkbox1.move(260, 140)

        self.checkbox2 = QCheckBox('', self)
        self.checkbox2.setChecked(True)
        self.checkbox2.setToolTip('Check to be the design domain.')
        self.checkbox2.move(400, 140)

        # Text box - stress limit
        self.textbox = QLineEdit(self)
        self.textbox.move(120, 170)
        self.textbox.resize(40, 20)
        # self.textbox.setText("")
        self.textbox.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox1 = QLineEdit(self)
        self.textbox1.move(260, 170)
        self.textbox1.resize(40, 20)
        # self.textbox1.setText("")
        self.textbox1.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox2 = QLineEdit(self)
        self.textbox2.move(400, 170)
        self.textbox2.resize(40, 20)
        # self.textbox2.setText("")
        self.textbox2.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        # Filters

        # Label above filter definition
        label31 = QLabel('Filter 0', self)
        label31.setStyleSheet("font-weight: bold")
        label31.move(120, 210)

        label32 = QLabel('Filter 1', self)
        label32.setStyleSheet("font-weight: bold")
        label32.move(260, 210)

        label33 = QLabel('Filter 2', self)
        label33.setStyleSheet("font-weight: bold")
        label33.move(400, 210)

        label34 = QLabel('Type', self)
        label34.move(20, 240)

        label35 = QLabel('Range [mm]', self)
        label35.move(20, 270)

        label36 = QLabel('Direction vector', self)
        label36.move(20, 300)

        label37 = QLabel('Apply to', self)
        label37.move(20, 330)

        # Combo box - select filter type
        self.combo6 = QComboBox(self)
        self.combo6.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo6.addItem("None")
        self.combo6.addItem("simple")
        self.combo6.addItem("casting")
        self.combo6.setCurrentIndex(1)
        self.combo6.move(120, 240)
        self.combo6.currentIndexChanged.connect(self.on_change6)

        self.combo7 = QComboBox(self)
        self.combo7.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo7.addItem("None")
        self.combo7.addItem("simple")
        self.combo7.addItem("casting")
        self.combo7.move(260, 240)
        self.combo7.currentIndexChanged.connect(self.on_change7)

        self.combo8 = QComboBox(self)
        self.combo8.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo8.addItem("None")
        self.combo8.addItem("simple")
        self.combo8.addItem("casting")
        self.combo8.move(400, 240)
        self.combo8.currentIndexChanged.connect(self.on_change8)

        # Text box - filter range
        self.textbox6 = QLineEdit(self)
        self.textbox6.move(120, 270)
        self.textbox6.resize(50, 20)
        # self.textbox6.setText("")
        self.textbox6.setToolTip(
            'Filter range [mm], recommended two times mesh size.')

        self.textbox7 = QLineEdit(self)
        self.textbox7.move(260, 270)
        self.textbox7.resize(50, 20)
        # self.textbox7.setText("")
        self.textbox7.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox7.setEnabled(False)

        self.textbox8 = QLineEdit(self)
        self.textbox8.move(400, 270)
        self.textbox8.resize(50, 20)
        # self.textbox8.setText("")
        self.textbox8.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox8.setEnabled(False)

        # Text box - casting direction
        self.textbox9 = QLineEdit(self)
        self.textbox9.move(120, 300)
        self.textbox9.resize(80, 20)
        self.textbox9.setText("0, 0, 1")
        self.textbox9.setEnabled(False)
        self.textbox9.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox10 = QLineEdit(self)
        self.textbox10.move(260, 300)
        self.textbox10.resize(80, 20)
        self.textbox10.resize(80, 20)
        self.textbox10.setText("0, 0, 1")
        self.textbox10.setEnabled(False)
        self.textbox10.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox11 = QLineEdit(self)
        self.textbox11.move(400, 300)
        self.textbox11.resize(80, 20)
        self.textbox11.setText("0, 0, 1")
        self.textbox11.setEnabled(False)
        self.textbox11.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        # list widget - select domains
        self.widget = QListWidget(self)
        self.widget.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget.move(120, 330)
        self.widget.resize(140, 120)
        self.widget.setSelectionMode(QAbstractItemView.MultiSelection)

        self.widget1 = QListWidget(self)
        self.widget1.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget1.move(260, 330)
        self.widget1.resize(140, 120)
        self.widget1.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget1.setEnabled(False)

        self.widget2 = QListWidget(self)
        self.widget2.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget2.move(400, 330)
        self.widget2.resize(140, 120)
        self.widget2.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget2.setEnabled(False)

        # Other settings
        label40 = QLabel('Other settings', self)
        label40.setStyleSheet("font-weight: bold")
        label40.move(10, 470)

        # AR, RR slider
        label41 = QLabel('Change per iteration:   low', self)
        label41.setFixedWidth(150)
        label41.move(10, 500)
        label42 = QLabel('high', self)
        label42.move(240, 500)

        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(1, 3)
        self.slider.setSingleStep(1)
        self.slider.setValue(2)
        self.slider.move(150, 500)
        self.slider.resize(80, 30)
        self.slider.setToolTip(
            'Sets mass change per iteration, which is controlled as\n'
            'slow:   mass_addition_ratio=0.01,  mass_removal_ratio=0.02\n'
            'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n'
            'fast:   mass_addition_ratio=0.03,  mass_removal_ratio=0.06')

        # optimization base combobox
        label51 = QLabel('Optimization base', self)
        label51.move(10, 530)
        self.combo51 = QComboBox(self)
        self.combo51.setToolTip(
            'Basic principle to determine if element should remain or be removed:\n'
            '"stiffness" to maximize stiffness (minimize compliance),\n'
            '"heat" to maximize heat flow.')
        self.combo51.addItem("stiffness")
        self.combo51.addItem("heat")
        self.combo51.move(120, 530)

        # mass goal ratio
        label52 = QLabel('Mass goal ratio', self)
        label52.move(10, 560)
        self.textbox52 = QLineEdit(self)
        self.textbox52.move(120, 560)
        self.textbox52.resize(50, 20)
        self.textbox52.setText("0.4")
        self.textbox52.setToolTip(
            'Fraction of all design domains masses to be achieved;\n'
            'between 0 and 1.')

        # generate conf. file button
        button21 = QPushButton('Generate conf. file', self)
        button21.setToolTip(
            'Writes configuration file with optimization parameters.')
        button21.move(10, 600)
        button21.clicked.connect(self.on_click21)

        # edit conf. file button
        button22 = QPushButton('Edit conf. file', self)
        button22.setToolTip('Opens configuration file for hand modifications.')
        button22.move(10, 630)
        button22.clicked.connect(self.on_click22)

        # run optimization button
        button23 = QPushButton('Run optimization', self)
        button23.setToolTip('Writes configuration file and runs optimization.')
        button23.move(10, 660)
        button23.clicked.connect(self.on_click23)

        # generate conf file and run optimization button
        button24 = QPushButton('Generate conf.\nfile and run\noptimization',
                               self)
        button24.setToolTip('Writes configuration file and runs optimization.')
        button24.move(120, 600)
        button24.resize(100, 90)
        button24.clicked.connect(self.on_click24)

        # help buttons
        label41 = QLabel('Help', self)
        label41.move(440, 560)

        button31 = QPushButton('Example', self)
        button31.setToolTip(
            'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD')
        button31.move(440, 590)
        # button31.resize(80, 50)
        button31.clicked.connect(self.on_click31)

        button32 = QPushButton('Conf. comments', self)
        button32.setToolTip(
            'https://github.com/fandaL/beso/blob/master/beso_conf.py')
        button32.move(440, 620)
        # button32.resize(80, 50)
        button32.clicked.connect(self.on_click32)

        button33 = QPushButton('Close', self)
        button33.move(440, 690)
        # button33.resize(80, 50)
        button33.clicked.connect(self.on_click33)

        # open log file
        button40 = QPushButton('Open log file', self)
        button40.setToolTip('Opens log file in your text editor.\n'
                            '(Does not refresh automatically.)')
        button40.move(10, 690)
        button40.clicked.connect(self.on_click40)

        self.on_click1()  # first update
        self.show()

    # @pyqtSlot()
    def on_click(self):
        ex2 = SelectFile()
        self.show()
        self.textbox_file_name.setText(self.inp_file)

    def on_click1(self):
        # get material objects
        self.materials = []
        self.thicknesses = []
        for obj in App.ActiveDocument.Objects:
            if obj.Name[:23] in ["MechanicalSolidMaterial", "SolidMaterial"]:
                self.materials.append(obj)
            elif obj.Name[:17] == "ElementGeometry2D":
                self.thicknesses.append(obj)
        # update materials combo boxes
        self.combo.clear()
        self.combo.addItem("None")
        self.combo1.clear()
        self.combo1.addItem("None")
        self.combo2.clear()
        self.combo2.addItem("None")
        self.combo0t.clear()
        self.combo0t.addItem("None")
        self.combo1t.clear()
        self.combo1t.addItem("None")
        self.combo2t.clear()
        self.combo2t.addItem("None")
        self.widget.clear()
        self.widget.addItem("All defined")
        self.widget.addItem("Domain 0")
        self.widget.addItem("Domain 1")
        self.widget.addItem("Domain 2")
        self.widget.setCurrentItem(self.widget.item(0))
        self.widget1.clear()
        self.widget1.addItem("All defined")
        self.widget1.addItem("Domain 0")
        self.widget1.addItem("Domain 1")
        self.widget1.addItem("Domain 2")
        self.widget1.setCurrentItem(self.widget1.item(0))
        self.widget2.clear()
        self.widget2.addItem("All defined")
        self.widget2.addItem("Domain 0")
        self.widget2.addItem("Domain 1")
        self.widget2.addItem("Domain 2")
        self.widget2.setCurrentItem(self.widget2.item(0))
        for mat in self.materials:
            self.combo.addItem(mat.Label)
            self.combo1.addItem(mat.Label)
            self.combo2.addItem(mat.Label)
        if self.materials:
            self.combo.setCurrentIndex(1)
        for th in self.thicknesses:
            self.combo0t.addItem(th.Label)
            self.combo1t.addItem(th.Label)
            self.combo2t.addItem(th.Label)

    def on_click21(self):
        """Overwrite beso_conf.py file in the macro directory"""

        file_name = os.path.split(self.textbox_file_name.text())[1]
        path = os.path.split(self.textbox_file_name.text())[0]

        fea = ccxtools.FemToolsCcx()
        fea.setup_ccx()
        path_calculix = fea.ccx_binary

        optimization_base = self.combo51.currentText()

        elset_id = self.combo.currentIndex() - 1
        thickness_id = self.combo0t.currentIndex() - 1
        if elset_id != -1:
            if thickness_id != -1:
                elset = self.materials[elset_id].Name + self.thicknesses[
                    thickness_id].Name
            else:  # 0 means None thickness selected
                elset = self.materials[elset_id].Name + "Solid"
            modulus = float(
                self.materials[elset_id].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id].Name)
            poisson = float(
                self.materials[elset_id].Material["PoissonRatio"].split()[0])
            try:
                density = float(self.materials[elset_id].Material["Density"].
                                split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                density = 0.
            try:
                conductivity = float(
                    self.materials[elset_id].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                conductivity = 0.
            try:
                if self.materials[elset_id].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion = float(self.materials[elset_id].
                                      Material["ThermalExpansionCoefficient"].
                                      split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion = float(
                        self.materials[elset_id].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                expansion = 0.
            try:
                specific_heat = float(
                    self.materials[elset_id].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                specific_heat = 0.
            if thickness_id != -1:
                thickness = str(
                    self.thicknesses[thickness_id].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id].Name)
            else:
                thickness = 0.
            optimized = self.checkbox.isChecked()
            if self.textbox.text():
                von_mises = float(self.textbox.text())
            else:
                von_mises = 0.

        elset_id1 = self.combo1.currentIndex() - 1
        thickness_id1 = self.combo0t.currentIndex() - 1
        if elset_id1 != -1:
            if thickness_id1 != -1:
                elset1 = self.materials[elset_id1].Name + self.thicknesses[
                    thickness_id1].Name
            else:  # 0 means None thickness selected
                elset1 = self.materials[elset_id1].Name + "Solid"
            modulus1 = float(
                self.materials[elset_id1].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id1].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id1].Name)
            poisson1 = float(
                self.materials[elset_id1].Material["PoissonRatio"].split()[0])
            try:
                density1 = float(self.materials[elset_id1].Material["Density"].
                                 split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id1].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                density1 = 0.
            try:
                conductivity1 = float(
                    self.materials[elset_id1].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id1].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                conductivity1 = 0.
            try:
                if self.materials[elset_id1].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion1 = float(self.materials[elset_id1].
                                       Material["ThermalExpansionCoefficient"].
                                       split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id1].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion1 = float(
                        self.materials[elset_id1].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                expansion1 = 0.
            try:
                specific_heat1 = float(
                    self.materials[elset_id1].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id1].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                specific_heat1 = 0.
            if thickness_id1 != -1:
                thickness1 = str(
                    self.thicknesses[thickness_id1].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id1].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id1].Name)
            else:
                thickness1 = 0.
            optimized1 = self.checkbox1.isChecked()
            if self.textbox1.text():
                von_mises1 = float(self.textbox1.text())
            else:
                von_mises1 = 0.

        elset_id2 = self.combo2.currentIndex() - 1
        thickness_id2 = self.combo0t.currentIndex() - 1
        if elset_id2 != -1:
            if thickness_id2 != -1:
                elset2 = self.materials[elset_id2].Name + self.thicknesses[
                    thickness_id2].Name
            else:  # 0 means None thickness selected
                else2t = self.materials[elset_id2].Name + "Solid"
            modulus2 = float(
                self.materials[elset_id2].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id2].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id2].Name)
            poisson2 = float(
                self.materials[elset_id2].Material["PoissonRatio"].split()[0])
            try:
                density2 = float(self.materials[elset_id2].Material["Density"].
                                 split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id2].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                density2 = 0.
            try:
                conductivity2 = float(
                    self.materials[elset_id2].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id2].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                conductivity2 = 0.
            try:
                if self.materials[elset_id2].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion2 = float(self.materials[elset_id2].
                                       Material["ThermalExpansionCoefficient"].
                                       split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id2].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion2 = float(
                        self.materials[elset_id2].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                expansion2 = 0.
            try:
                specific_heat2 = float(
                    self.materials[elset_id2].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id2].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                specific_heat2 = 0.
            if thickness_id2 != -1:
                thickness2 = str(
                    self.thicknesses[thickness_id2].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id2].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id2].Name)
            else:
                thickness2 = 0.
            optimized2 = self.checkbox2.isChecked()
            if self.textbox2.text():
                von_mises2 = float(self.textbox2.text())
            else:
                von_mises2 = 0.

        with open(os.path.join(self.beso_dir, "beso_conf.py"), "w") as f:
            f.write(
                "# This is the configuration file with input parameters. It will be executed as python commands\n"
            )
            f.write("# Written by beso_fc_gui.py at {}\n".format(
                datetime.datetime.now()))
            f.write("\n")
            f.write("path_calculix = '{}'\n".format(path_calculix))
            f.write("path = '{}'\n".format(path))
            f.write("file_name = '{}'\n".format(file_name))
            f.write("\n")

            if elset_id != -1:
                f.write("elset_name = '{}'\n".format(elset))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density * 1e-6, density))
                if thickness:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness, thickness))
                if von_mises:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus * 1e-6, poisson, density * 1e-6,
                            conductivity * 1e-6, expansion * 1e-6,
                            specific_heat * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n"
                    .format(modulus, poisson, density, conductivity, expansion,
                            specific_heat))
                f.write("\n")
            if elset_id1 != -1:
                f.write("elset_name = '{}'\n".format(elset1))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized1))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density1 * 1e-6, density1))
                if thickness1:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness1, thickness1))
                if von_mises1:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises1 * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises1))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY"
                    "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus1 * 1e-6, poisson1, density1 * 1e-6,
                            conductivity1 * 1e-6, expansion1 * 1e-6,
                            specific_heat1 * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n"
                    "*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n".
                    format(modulus1, poisson1, density1, conductivity1,
                           expansion1, specific_heat1))
                f.write("\n")
            if elset_id2 != -1:
                f.write("elset_name = '{}'\n".format(elset2))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized2))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density2 * 1e-6, density2))
                if thickness2:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness2, thickness2))
                if von_mises2:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises2 * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises2))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY"
                    "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus2 * 1e-6, poisson2, density2 * 1e-6,
                            conductivity2 * 1e-6, expansion2 * 1e-6,
                            specific_heat2 * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n"
                    .format(modulus2, poisson2, density2, conductivity2,
                            expansion2, specific_heat2))
                f.write("\n")
            f.write("mass_goal_ratio = " + self.textbox52.text())
            f.write("\n")

            f.write("filter_list = [")
            filter = self.combo6.currentText()
            range = self.textbox6.text()
            direction = self.textbox9.text()
            selection = [item.text() for item in self.widget.selectedItems()]
            filter_domains = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains.append(elset)
                if "Domain 1" in selection:
                    filter_domains.append(elset1)
                if "Domain 2" in selection:
                    filter_domains.append(elset2)
            if filter == "simple":
                f.write("['simple', {}".format(range))
                for dn in filter_domains:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter == "casting":
                f.write("['casting', {}, ({})".format(range, direction))
                for dn in filter_domains:
                    f.write(", '{}'".format(dn))
                f.write("],\n")

            filter1 = self.combo7.currentText()
            range1 = self.textbox7.text()
            direction1 = self.textbox10.text()
            selection = [item.text() for item in self.widget1.selectedItems()]
            filter_domains1 = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains1.append(elset)
                if "Domain 1" in selection:
                    filter_domains1.append(elset1)
                if "Domain 2" in selection:
                    filter_domains1.append(elset2)
            if filter1 == "simple":
                f.write("               ['simple', {}".format(range1))
                for dn in filter_domains1:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter1 == "casting":
                f.write("               ['casting', {}, ({})".format(
                    range1, direction1))
                for dn in filter_domains1:
                    f.write(", '{}'".format(dn))
                f.write("],\n")

            filter2 = self.combo8.currentText()
            range2 = self.textbox8.text()
            direction2 = self.textbox11.text()
            selection = [item.text() for item in self.widget2.selectedItems()]
            filter_domains2 = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains2.append(elset)
                if "Domain 1" in selection:
                    filter_domains2.append(elset1)
                if "Domain 2" in selection:
                    filter_domains2.append(elset2)
            if filter2 == "simple":
                f.write("               ['simple', {}".format(range2))
                for dn in filter_domains2:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter2 == "casting":
                f.write("               ['casting', {}, ({})".format(
                    range2, direction2))
                for dn in filter_domains2:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            f.write("               ]\n")
            f.write("\n")

            f.write("optimization_base = '{}'\n".format(optimization_base))
            f.write("\n")

            slider_position = self.slider.value()
            if slider_position == 1:
                f.write("mass_addition_ratio = 0.01\n")
                f.write("mass_removal_ratio = 0.02\n")
            if slider_position == 2:
                f.write("mass_addition_ratio = 0.015\n")
                f.write("mass_removal_ratio = 0.03\n")
            if slider_position == 3:
                f.write("mass_addition_ratio = 0.03\n")
                f.write("mass_removal_ratio = 0.06\n")
            f.write("ratio_type = 'relative'\n")
            f.write("\n")

    def on_click22(self):
        """Open beso_conf.py in FreeCAD editor"""
        FreeCADGui.insert(os.path.join(self.beso_dir, "beso_conf.py"))

    def on_click23(self):
        """"Run optimization"""
        # run in own thread (not freezing FreeCAD):      needs also to comment "plt.show()" on the end of beso_main.py
        # self.optimization_thread = RunOptimization("beso_main")
        # self.optimization_thread.start()

        # run in foreground (freeze FreeCAD)
        exec(open(os.path.join(beso_gui.beso_dir, "beso_main.py")).read())

    def on_click24(self):
        self.on_click21()  # generate beso_conf.py
        self.on_click23()  # run optimization

    def on_click31(self):
        webbrowser.open_new_tab(
            "https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD")

    def on_click32(self):
        webbrowser.open_new_tab(
            "https://github.com/fandaL/beso/blob/master/beso_conf.py")

    def on_click33(self):
        self.close()

    def on_click40(self):
        """Open log file"""
        if self.textbox_file_name.text() in [
                "None analysis file selected", ""
        ]:
            print("None analysis file selected")
        else:
            log_file = os.path.normpath(self.textbox_file_name.text()[:-4] +
                                        ".log")
            webbrowser.open(log_file)

    def on_change(self):
        if self.combo.currentText() == "None":
            self.combo0t.setEnabled(False)
            self.checkbox.setEnabled(False)
            self.textbox.setEnabled(False)
        else:
            self.combo0t.setEnabled(True)
            self.checkbox.setEnabled(True)
            self.textbox.setEnabled(True)

    def on_change1(self):
        if self.combo1.currentText() == "None":
            self.combo1t.setEnabled(False)
            self.checkbox1.setEnabled(False)
            self.textbox1.setEnabled(False)
        else:
            self.combo1t.setEnabled(True)
            self.checkbox1.setEnabled(True)
            self.textbox1.setEnabled(True)

    def on_change2(self):
        if self.combo2.currentText() == "None":
            self.combo2t.setEnabled(False)
            self.checkbox2.setEnabled(False)
            self.textbox2.setEnabled(False)
        else:
            self.combo2t.setEnabled(True)
            self.checkbox2.setEnabled(True)
            self.textbox2.setEnabled(True)

    def on_change6(self):
        if self.combo6.currentText() == "None":
            self.textbox6.setEnabled(False)
            self.textbox9.setEnabled(False)
            self.widget.setEnabled(False)
        elif self.combo6.currentText() == "casting":
            self.textbox6.setEnabled(True)
            self.textbox9.setEnabled(True)
            self.widget.setEnabled(True)
        else:
            self.textbox6.setEnabled(True)
            self.textbox9.setEnabled(False)
            self.widget.setEnabled(True)

    def on_change7(self):
        if self.combo7.currentText() == "None":
            self.textbox7.setEnabled(False)
            self.textbox10.setEnabled(False)
            self.widget1.setEnabled(False)
        elif self.combo7.currentText() == "casting":
            self.textbox7.setEnabled(True)
            self.textbox10.setEnabled(True)
            self.widget1.setEnabled(True)
        else:
            self.textbox7.setEnabled(True)
            self.textbox10.setEnabled(False)
            self.widget1.setEnabled(True)

    def on_change8(self):
        if self.combo8.currentText() == "None":
            self.textbox8.setEnabled(False)
            self.textbox11.setEnabled(False)
            self.widget2.setEnabled(False)
        elif self.combo8.currentText() == "casting":
            self.textbox8.setEnabled(True)
            self.textbox11.setEnabled(True)
            self.widget2.setEnabled(True)
        else:
            self.textbox8.setEnabled(True)
            self.textbox11.setEnabled(False)
            self.widget2.setEnabled(True)
コード例 #37
0
 def createEditor(self, parent, option, index):
     comboBox = QComboBox(parent)
     comboBox.addItem(id_text)
     return comboBox
コード例 #38
0
class MassAttribute_UI(QDialog):
    """
    The main UI
    """
    class Applikator(QObject):
        """
        This is the core applier which toggle the display of the corresponding widget and handling events' connections
        """
        def __init__(self, parent=None):
            super(MassAttribute_UI.Applikator, self).__init__()
            self.root = parent

        def widget_event(self, t):
            """
            Return the correct widget's event depending on attribute's type
            :param t: the attribute's type
            :type  t: str
            :return: the event
            :rtype : Signal
            """
            return {
                'float': self.root.W_EDI_float.valueChanged,
                'enum': self.root.W_EDI_enum.currentIndexChanged,
                'int': self.root.W_EDI_int.valueChanged,
                'bool': self.root.W_EDI_bool.stateChanged,
                'str': self.root.W_EDI_str.textChanged,
                'd3': self.root.W_EDI_d3.valuesChanged,
                'd4': self.root.W_EDI_d4.valuesChanged,
                'color': self.root.W_EDI_color.colorChanged
            }[t]

        def unset_editors(self):
            """
            Toggle off all editors and disconnect the current one
            """
            for widget in (self.root.W_EDI_float, self.root.W_EDI_int,
                           self.root.W_EDI_enum, self.root.W_EDI_bool,
                           self.root.W_EDI_str, self.root.W_EDI_d3,
                           self.root.W_EDI_d4, self.root.W_EDI_color):
                widget.setVisible(False)

            # trying to force disconnection
            try:
                self.widget_event(self.root.ctx).disconnect(
                    self.root.apply_value)
            except (KeyError, RuntimeError):
                pass

        def prepare(applier_name):
            """
            A decorator to prepare the attribute depending on type for the corresponding widget and getting the
            attribute's value
            :param applier_name: attribute's type
            :type  applier_name: str
            """
            def sub_wrapper(func):
                def wrapper(self, attr_path):
                    self.unset_editors()
                    self.root.ctx = applier_name
                    self.root.__getattribute__('W_EDI_%s' %
                                               applier_name).setVisible(True)
                    ret = func(self, cmds.getAttr(attr_path), attr_path)
                    return ret

                return wrapper

            return sub_wrapper

        @staticmethod
        def get_bounds(obj, attr, min_default, max_default):
            """
            Try to retrieve the range for the given attribute, if min or max fail it'll set default values
            :param         obj: the object's name
            :type          obj: str
            :param        attr: attribute's name
            :type         attr: str
            :param min_default: minimum default value
            :param max_default: max default value
            :type  min_default: float | int
            :type  max_default: float | int
            :return: minimum, maximum
            :rtype : tuple
            """
            try:
                assert cmds.attributeQuery(attr, n=obj, mxe=True)
                maxi = cmds.attributeQuery(attr, n=obj, max=True)[0]
            except (RuntimeError, AssertionError):
                maxi = max_default
            try:
                assert cmds.attributeQuery(attr, n=obj, mne=True)
                mini = cmds.attributeQuery(attr, n=obj, min=True)[0]
            except (RuntimeError, AssertionError):
                mini = min_default
            return mini, maxi

        @prepare('float')
        def apply_float(self, value, path):
            """
            Float attribute case
            :param value: attribute's value
            :param  path: attribute's path = obj.attr
            """
            obj, attr = path.split('.', 1)
            self.root.W_EDI_float.setRange(
                *self.get_bounds(obj, attr, -100.0, 100.0))
            self.root.W_EDI_float.setValue(value)

        @prepare('enum')
        def apply_enum(self, value, path):
            """Enum case"""
            self.root.W_EDI_enum.clear()
            obj, attr = path.split('.', 1)
            try:
                enums = [
                    enum.split('=')[0] for enum in cmds.attributeQuery(
                        attr, n=obj, listEnum=True)[0].split(':')
                ]
            except RuntimeError:
                self.apply_int(path)
            else:
                self.root.W_EDI_enum.addItems(enums)
                self.root.W_EDI_enum.setCurrentIndex(
                    enums.index(cmds.getAttr(path, asString=True)))

        @prepare('int')
        def apply_int(self, value, path):
            """Integer case"""
            obj, attr = path.split('.', 1)
            self.root.W_EDI_int.setRange(
                *self.get_bounds(obj, attr, -1000, 1000))
            self.root.W_EDI_int.setValue(value)

        @prepare('bool')
        def apply_bool(self, value, path):
            """Boolean case"""
            self.root.W_EDI_bool.setChecked(value)
            self.root.W_EDI_bool.setText(path.split('.', 1)[1])

        @prepare('str')
        def apply_str(self, value, path):
            """String case"""
            self.root.W_EDI_str.setText(value)

        @prepare('d3')
        def apply_d3(self, value, path):
            """3D array case"""
            self.root.W_EDI_d3.setValues(value[0])

        @prepare('d4')
        def apply_d4(self, value, path):
            """4D array case"""
            self.root.W_EDI_d4.setValues(value[0])

        @prepare('color')
        def apply_color(self, value, path):
            """Color case"""
            try:
                colors = value[0]
                self.root.W_EDI_color.setColor([int(c * 255) for c in colors])
            except TypeError:
                self.apply_int(value, path)

    class Attribute(str):
        """
        A custom string attribute class to ship more information into the string variable
        """
        def __new__(cls, path='', super_type=Object):
            obj, attr = path.split('.', 1)

            str_obj = str.__new__(cls, attr)

            str_obj.obj, str_obj.attr = obj, attr
            str_obj.path = path
            str_obj.super_type = super_type
            str_obj.type = None

            return str_obj

    # static variables to pre-load icons and attributes short names
    ctx_icons = {
        'float': QIcon(':render_decomposeMatrix.png'),
        'enum': QIcon(':showLineNumbers.png'),
        'bool': QIcon(':out_decomposeMatrix.png'),
        'time': QIcon(':time.svg'),
        'byte': QIcon(':out_defaultTextureList.png'),
        'angle': QIcon(':angleDim.png'),
        'string': QIcon(':text.png'),
        'float3': QIcon(':animCurveTA.svg'),
        'float4': QIcon(':animCurveTA.svg'),
        'color': QIcon(':clampColors.svg')
    }

    for ctx in ('doubleLinear', 'double', 'long', 'short'):
        ctx_icons[ctx] = ctx_icons['float']

    ctx_icons['double3'] = ctx_icons['float3']
    ctx_icons['double4'] = ctx_icons['float4']

    ctx_wide = {
        'float': ('float', 'doubleLinear', 'double', 'long', 'short'),
        'enum': ('enum', ),
        'bool': ('bool', ),
        'time': ('time', ),
        'byte': ('byte', ),
        'angle': ('doubleAngle', ),
        'string': ('string', ),
        'float3': ('double3', 'float3'),
        'float4': ('double4', 'float4'),
        'color': ('color', )
    }

    def __init__(self, parent=None):
        super(MassAttribute_UI, self).__init__(parent)
        # Abstract
        self.applier = self.Applikator(self)
        self.selection = []
        self.callback = None
        self.ctx = None
        # storing found attributes' types to avoid double check
        self.solved = {}
        self.setLocale(QLocale.C)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAttribute(Qt.WA_QuitOnClose)

        self.setFixedWidth(300)
        self.setWindowTitle('Massive Attribute Modifier')

        # UI
        L_main = QVBoxLayout()

        self.WV_title = QLabel('')
        self.WV_title.setVisible(False)
        self.WV_title.setFont(QFont('Verdana', 10))
        self.WV_title.setContentsMargins(0, 0, 0, 7)

        self.WB_select = QPushButton('Select')
        self.WB_select.setVisible(False)
        self.WB_select.setFixedWidth(50)
        self.WB_select.clicked.connect(lambda: cmds.select(self.selection))

        self.WB_update = QPushButton('Update')
        self.WB_update.setFixedWidth(50)
        self.WB_update.clicked.connect(
            lambda: self.update_attributes(cmds.ls(sl=True)))

        self.WV_search = Filter()
        self.WV_search.textChanged.connect(self.filter)

        self.WC_cases = QCheckBox('Case sensitive')
        self.WC_cases.stateChanged.connect(self.filter)

        self.WC_types = QCheckBox('Type filtering')

        self.WL_attrtype = QComboBox()
        self.WL_attrtype.setEnabled(False)

        for i, ctx in enumerate(sorted(self.ctx_wide)):
            self.WL_attrtype.addItem(ctx.title())
            self.WL_attrtype.setItemIcon(i, self.ctx_icons[ctx])

        L_attrtype = line(self.WC_types, self.WL_attrtype)

        self.WC_types.stateChanged.connect(
            partial(self.update_attributes, self.selection))
        self.WC_types.stateChanged.connect(self.WL_attrtype.setEnabled)
        self.WL_attrtype.currentIndexChanged.connect(self.filter)

        self.WC_liveu = QCheckBox('Live')
        self.WC_liveu.stateChanged.connect(self.WB_update.setDisabled)
        self.WC_liveu.stateChanged.connect(self.set_callback)

        self.WC_histo = QCheckBox('Load history')
        self.WC_histo.setChecked(True)
        self.WC_histo.stateChanged.connect(
            partial(self.update_attributes, self.selection))

        self.WC_child = QCheckBox('Children')
        self.WC_child.stateChanged.connect(
            partial(self.update_attributes, self.selection))

        options = group(
            'Options', line(self.WC_cases, L_attrtype),
            line(self.WC_child, self.WC_histo, self.WC_liveu, self.WB_update))
        options.layout().setSpacing(2)

        self.WL_attributes = QTreeWidget()
        self.WL_attributes.setStyleSheet(
            'QTreeView {alternate-background-color: #1b1b1b;}')
        self.WL_attributes.setAlternatingRowColors(True)
        self.WL_attributes.setHeaderHidden(True)
        self.WL_attributes.setRootIsDecorated(False)

        self.objs_attr = set()
        self.shps_attr = set()

        self.W_EDI_float = FloatBox()
        self.W_EDI_int = IntBox()
        self.W_EDI_enum = QComboBox()
        self.W_EDI_bool = QCheckBox()
        self.W_EDI_str = QLineEdit()
        self.W_EDI_d3 = Double3()
        self.W_EDI_d4 = Double4()
        self.W_EDI_color = ColorPicker()

        # Final layout
        L_title = line(self.WV_title, self.WB_select)
        L_title.setStretch(0, 1)
        L_main.addLayout(L_title)
        L_main.setAlignment(Qt.AlignLeft)
        L_main.addWidget(self.WV_search)
        L_main.addWidget(options)
        L_main.addWidget(self.WL_attributes)
        L_edits = col(self.W_EDI_bool, self.W_EDI_int, self.W_EDI_float,
                      self.W_EDI_enum, self.W_EDI_str, self.W_EDI_d3,
                      self.W_EDI_d4, self.W_EDI_color)
        L_edits.setContentsMargins(0, 8, 0, 0)
        L_main.addLayout(L_edits)
        L_main.setStretch(3, 1)
        L_main.setSpacing(2)

        self.appliers = {
            'float': self.applier.apply_float,
            'enum': self.applier.apply_enum,
            'bool': self.applier.apply_bool,
            'time': self.applier.apply_float,
            'byte': self.applier.apply_int,
            'angle': self.applier.apply_float,
            'string': self.applier.apply_str,
            'float3': self.applier.apply_d3,
            'float4': self.applier.apply_d4,
            'color': self.applier.apply_color
        }

        self.setLayout(L_main)

        # final settings
        self.WL_attributes.itemSelectionChanged.connect(self.update_setter)
        self.applier.unset_editors()

    def closeEvent(self, *args, **kwargs):
        self.set_callback(False)

    def set_callback(self, state):
        """
        Toggle selection event callback
        :param state: checkbox's state
        :type  state: bool | int
        """
        if state and not self.callback:
            self.callback = MEventMessage.addEventCallback(
                'SelectionChanged', self.update_attributes)
            self.update_attributes(cmds.ls(sl=True))

        elif not state and self.callback:
            MMessage.removeCallback(self.callback)
            self.callback = None

    @staticmethod
    def format_title(nodes):
        """
        Extract the matching characters from a given nodes selection, if begin matches it will return "joint*" with a
        wildcard when names don't match
        :param nodes: objects' list
        :type  nodes: list | tuple
        :return: the formatted name with the corresponding characters
        :rtype : str
        """
        res = None

        if nodes:
            # we get the first node as a reference
            node = nodes[0]
            # and compare with the other nodes
            subs = [w for w in nodes if w != node]

            l = 1
            valid = True
            # will continue until l (length) match the full name's length or until names don't match
            while l < len(node) and valid:
                for sub in subs:
                    if not sub.startswith(node[:l]):
                        valid = False
                        break

                else:
                    l += 1

            # if matching characters isn't long enough we only display the number of nodes selected
            if l <= 3:
                res = '%i objects' % len(nodes)

            # otherwise showing matching pattern
            elif l < len(node) or len(nodes) > 1:
                res = node[:l - 1] + '* (%i objects)' % len(nodes)

            else:
                res = node

        return res

    @staticmethod
    def get_history(node):
        """
        Extract history for the given node
        :rtype: list
        """
        return cmds.listHistory(node, il=2, pdo=True) or []

    @staticmethod
    def get_shapes(node):
        """
        Extract shape(s) for the given node
        :rtype: list
        """
        return cmds.listRelatives(node, s=True, ni=True, f=True)

    def get_attributes_type(self, attrs):
        """
        For a given list of attributes of type Attribute, will loop through and fill the type parameter of the
         attribute with the corresponding type, if type is invalid or not handled, it'll remove it
        :param attrs: attributes' list
        :type  attrs: [MassAttribute_UI.Attribute]
        :return: cleaned and filled attributes' list
        :rtype: [MassAttribute_UI.Attribute]
        """
        attrs = list(attrs)
        # first we sort the attributes' list
        attrs.sort()

        # then we try to extract the attribute's type
        for i, attr in enumerate(attrs):
            try:
                if attr.attr in self.solved:
                    attr.type = self.solved[attr.attr]
                    raise RuntimeError
                tpe = cmds.getAttr(attr.path, typ=True)
                assert tpe
                attr.type = tpe
                self.solved[attr.attr] = tpe
            except (AssertionError, ValueError, RuntimeError):
                pass

        # defining a to-remove list
        rm_list = set()

        layers = {'3': 'XYZ', '4': 'XYZW'}
        for i, attr in enumerate(attrs):
            if i in rm_list:
                continue

            # we handle some special cases here, if ever the attribute list contains RGB and separate R, G and B we
            # assume it's a color, if it's a double3 or float3 and we find the corresponding XYZ, we remove then to
            # avoid duplicates

            if attr.endswith('RGB'):
                if '%sR' % attr[:-3] in attrs:
                    attr.type = 'color'
                    for chan in 'RGB':
                        rm_list.add(attrs.index('%s%s' % (attr[:-3], chan)))

            # if the attribute's type isn't in the list, we remove
            elif attr.type not in MassAttribute_UI.ctx_icons:
                rm_list.add(i)

            elif attr.endswith('R'):
                if '%sG' % attr[:-1] in attrs and attr[:-1] in attrs:
                    attr.type = 'color'
                    for chan in 'RGB':
                        rm_list.add(attrs.index('%s%s' % (attr[:-1], chan)))

            elif attr.type in ('double3', 'double4', 'float3', 'float4'):
                if '%sX' % attr in attrs:
                    for chan in layers[attr.type[-1]]:
                        rm_list.add(attrs.index('%s%s' % (attr, chan)))

        # finally cleaning the list
        for i in sorted(rm_list, reverse=True):
            attrs.pop(i)

        return attrs

    def apply_value(self, value):
        """
        When the value is modified in the UI, we forward the given value and applies to the object's
        :param value: attribute's value, mixed type
        :type  value: mixed
        """
        # We get the only selected object in list and get it's super type (Shape, History or Object) and
        # type (float, int, string)
        item = self.WL_attributes.selectedItems()[0]
        attr = item.attribute
        shape = attr.super_type == Shape
        histo = attr.super_type == History
        tpe = item.attribute.type

        # eq dict for each context
        value = {
            'bool': bool,
            'int': int,
            'float': float,
            'enum': int,
            'str': str,
            'd3': list,
            'd4': list,
            'color': list
        }[self.ctx](value)

        # converting the selection into a set
        cmds.undoInfo(openChunk=True)
        targets = set(self.selection)

        # we propagate to children if 'Children' checkbox is on
        if self.WC_child.isChecked():
            for obj in list(targets):
                targets |= set(cmds.listRelatives(obj, ad=True))

        # if the target attribute is on the history, we add all selection's history to the list
        if histo:
            for obj in list(targets):
                targets.remove(obj)
                targets |= set(self.get_history(obj))

        # then we loop through target objects
        for obj in targets:
            # if the target is on the shape we get object's shape
            if shape and not histo:
                shapes = self.get_shapes(obj)

                if obj in shapes:
                    continue
                else:
                    obj = shapes[0]

            # then we try to apply depending on attribute's type
            try:
                correct_path = attr.path.replace(attr.obj, obj)

                if tpe == 'string':
                    cmds.setAttr(correct_path, value, type='string')

                elif tpe in ('double3', 'double4', 'float3', 'float4',
                             'color'):
                    cmds.setAttr(correct_path,
                                 *value,
                                 type='double%d' % len(value))

                else:
                    cmds.setAttr(correct_path, value)

            except RuntimeError:
                pass

        cmds.undoInfo(closeChunk=True)

    def update_setter(self):
        """
        When the list's selection changes we update the applier widget
        """
        item = self.WL_attributes.selectedItems()
        # abort if no item is selected
        if not len(item):
            return

        # getting attribute's parameter
        attr = item[0].attribute

        if len(self.selection):
            try:
                # looping until we find a context having the current attribute's type
                for applier in self.ctx_wide:
                    if attr.type in self.ctx_wide[applier]:
                        break
                # then we apply for the given path (obj.attribute)
                self.appliers[applier](attr.path)

                # and connecting event to the self.apply_value function
                self.applier.widget_event(self.ctx).connect(self.apply_value)

            # otherwise selection or type is invalid
            except IndexError:
                self.ctx = None

    def update_attributes(self, selection=None, *args):
        """
        Update the attributes for the given selection, looping through objects' attributes, finding attr in common
        between all objects then cleaning the lists, doing the same for shapes and / or histories
        :param selection: object's selection
        """
        # redefining lists as set to intersect union etc
        self.objs_attr = set()
        self.shps_attr = set()

        # pre init
        self.WL_attributes.clear()
        self.applier.unset_editors()

        self.selection = selection or (cmds.ls(
            sl=True) if self.WC_liveu.isChecked() else self.selection)

        self.WV_title.setText(self.format_title(self.selection))
        self.WV_title.setVisible(bool(len(self.selection)))
        self.WB_select.setVisible(bool(len(self.selection)))

        if not len(self.selection):
            return

        def get_usable_attrs(obj, super_type):
            """
            Small internal function to get a compatible attributes' list for the given object and assign the given
            super_type to it (Object, Shape or History)
            :param        obj: object's name
            :type         obj: str
            :param super_type: attribute's main type
            :type  super_type: Object | Shape | History
            :return:
            """
            return set([
                MassAttribute_UI.Attribute('%s.%s' % (obj, attr), super_type)
                for attr in cmds.listAttr(
                    obj, se=True, ro=False, m=True, w=True)
            ])

        if len(self.selection):
            self.objs_attr = get_usable_attrs(self.selection[0], Object)

            # if we also want the object's history we add it to the initial set
            if self.WC_histo.isChecked():
                for histo in self.get_history(self.selection[0]):
                    self.objs_attr |= get_usable_attrs(histo, History)

            # filling the shape's set
            for shape in (self.get_shapes(self.selection[0]) or []):
                self.shps_attr |= get_usable_attrs(shape, Shape)

            # if selection's length bigger than one we compare by intersection with the other sets
            if len(self.selection) > 1:
                for obj in self.selection:
                    sub_attr = get_usable_attrs(obj, Object)

                    if self.WC_histo.isChecked():
                        for histo in self.get_history(obj):
                            sub_attr |= get_usable_attrs(histo, History)

                    self.objs_attr.intersection_update(sub_attr)

                    for shape in (self.get_shapes(self.selection[0]) or []):
                        self.shps_attr.intersection_update(
                            get_usable_attrs(shape, Shape))

            # finally getting all intersecting attributes' types
            self.objs_attr = self.get_attributes_type(self.objs_attr)
            self.shps_attr = self.get_attributes_type(self.shps_attr)

        # and filtering the list
        self.filter()

    def add_set(self, iterable, title=None):
        """
        Adding the given iterable to the list with a first Separator object with given title
        :param iterable: list of item's attributes
        :param    title: Separator's name
        """
        if len(iterable):
            # if title is given we first add a Separator item to indicate coming list title
            if title:
                self.WL_attributes.addTopLevelItem(
                    QTreeWidget_Separator(title))

            items = []
            for attr in sorted(iterable):
                item = QTreeWidgetItem([attr])
                # assigning the attribute itself inside a custom parameter
                item.attribute = attr
                items.append(item)

            # finally adding all the items to the list
            self.WL_attributes.addTopLevelItems(items)

    def filter(self):
        """
        Filter the list with UI's parameters, such as name or type filtering, etc
        """
        # pre cleaning
        self.WL_attributes.clear()

        # using regex compile to avoid re execution over many attributes
        mask = self.WV_search.text()
        case = 0 if self.WC_cases.isChecked() else re.IGNORECASE
        re_start = re.compile(r'^%s.*?' % mask, case)
        re_cont = re.compile(r'.*?%s.*?' % mask, case)

        # getting the four different lists
        obj_start = set([at for at in self.objs_attr if re_start.search(at)])
        shp_start = set([at for at in self.shps_attr if re_start.search(at)])

        # if type filtering is one we only extract the wanted attribute's type
        if self.WC_types.isChecked():
            obj_start = set([
                at for at in obj_start if at.type in self.ctx_wide[
                    self.WL_attrtype.currentText().lower()]
            ])
            shp_start = set([
                at for at in shp_start if at.type in self.ctx_wide[
                    self.WL_attrtype.currentText().lower()]
            ])

        # finally adding the current sets if there is a mask we add the also the containing matches
        if mask:
            # getting contains filtering and type containers filtering
            obj_contains = obj_start.symmetric_difference(
                set([at for at in self.objs_attr if re_cont.search(at)]))
            shp_contains = shp_start.symmetric_difference(
                set([at for at in self.shps_attr if re_cont.search(at)]))
            if self.WC_types.isChecked():
                obj_contains = set([
                    at for at in obj_contains if at.type in self.ctx_wide[
                        self.WL_attrtype.currentText().lower()]
                ])
                shp_contains = set([
                    at for at in shp_contains if at.type in self.ctx_wide[
                        self.WL_attrtype.currentText().lower()]
                ])

            # adding the sets
            self.add_set(obj_start, 'Obj attributes starting with')
            self.add_set(obj_contains, 'Obj attributes containing')
            self.add_set(shp_start, 'Shape attributes starting with')
            self.add_set(shp_contains, 'Shape attributes containing')

        else:
            self.add_set(obj_start, 'Object\'s attributes')
            self.add_set(shp_start, 'Shape\'s attributes')

        # and we select the first one if ever there is something in the list
        if self.WL_attributes.topLevelItemCount():
            self.WL_attributes.setItemSelected(
                self.WL_attributes.topLevelItem(1), True)
コード例 #39
0
ファイル: AnyIMU.py プロジェクト: bhowiebkr/AnyIMU
class AnyIMU_window(QMainWindow):
  def __init__(self, parent=None):
    super(AnyIMU_window, self).__init__(parent)
    self.setWindowTitle('AnyIMU')
    self.resize(450, 700)
    os.system('cls')
    self.dcm = DCM()

    self.accDataCurr = None
    self.gyrDataCurr = None
    self.magDataCurr = None
    self.barDataCurr = None
    self.serialThread = None
    self.skipDataCount = 5

    # The plot widget
    self.accPlotWidget = SensorDisplay(name='Accelerometer')
    self.gyrPlotWidget = SensorDisplay(name='Gyroscope')
    self.magPlotWidget = SensorDisplay(name='Magnetometer')
    self.barPlotWidget = SensorDisplay(name='Barometer')

    self.accPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='int', dataName='X')
    self.accPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='int', dataName='Y')
    self.accPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='int', dataName='Z')

    self.gyrPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='int', dataName='X')
    self.gyrPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='int', dataName='Y')
    self.gyrPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='int', dataName='Z')

    self.magPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='int', dataName='X')
    self.magPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='int', dataName='Y')
    self.magPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='int', dataName='Z')

    self.barPlotWidget.addPlot(fillLevelIn=0, brushIn=(200,0,0,100), penIn=(255,0,0), dataType='float', dataName='TEMP')
    self.barPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,200,0,100), penIn=(0,255,0), dataType='float', dataName='PRS')
    self.barPlotWidget.addPlot(fillLevelIn=0, brushIn=(0,0,200,100), penIn=(0,0,255), dataType='float', dataName='ALT')
                                                                                      
    # the main layout and widgets
    self.mainWidget = QWidget()
    self.setCentralWidget(self.mainWidget)
    self.mainLayout = QGridLayout()
    self.mainWidget.setLayout(self.mainLayout)
    connectionLayout = QHBoxLayout()

    # widgets
    serialLab = QLabel('Serial Port:')
    self.serialLine = QLineEdit('COM3')
    self.serialLine.setFixedWidth(100)
    baudRateLab = QLabel('Baud Rate:')
    self.baudRateCombo = QComboBox()
    for baud in [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200]: self.baudRateCombo.addItem(str(baud))
    default = self.baudRateCombo.findText('9600')
    self.baudRateCombo.setCurrentIndex(default)  
    self.viewport = Viewport()

    # Debugging stuff----------------------------------
    debugLayout = QHBoxLayout()

    # these are used to offset the the rotation
    self.xAdd = QSpinBox()
    self.yAdd = QSpinBox()
    self.zAdd = QSpinBox()

    for each in [self.xAdd, self.yAdd, self.zAdd]:
      each.setMinimum(-180)  # min
      each.setMaximum(180)   # max
      each.setSingleStep(90) # change this to a small value if need be

    # these are used for inverting the rotations
    self.xMult = QCheckBox()
    self.yMult = QCheckBox()
    self.zMult = QCheckBox()

    self.xAdd.setValue(0)
    self.yAdd.setValue(90)  # in my case I need to offset by 90 in the Y axis
    self.zAdd.setValue(0)
    self.xMult.setChecked(False)
    self.yMult.setChecked(True)   # in my case I need to invert the Y axis on the acc
    self.zMult.setChecked(False)

    for each in [self.xAdd, self.yAdd, self.zAdd, self.xMult, self.yMult, self.zMult]:
      debugLayout.addWidget(each)

    # Debugging stuff----------------------------------
    
    self.serialBtn = QPushButton('Connect')

    # add widgets to layout
    connectionLayout.addWidget(serialLab)
    connectionLayout.addWidget(self.serialLine)
    connectionLayout.addWidget(baudRateLab)
    connectionLayout.addWidget(self.baudRateCombo)
    connectionLayout.addWidget(self.serialBtn)
    connectionLayout.addStretch()

    self.mainLayout.addLayout(connectionLayout, 0,0,1,2)
    self.mainLayout.addWidget(self.viewport, 1,0,1,2)
    self.mainLayout.addWidget(self.accPlotWidget, 2,0,1,1)
    self.mainLayout.addWidget(self.gyrPlotWidget, 2,1,1,1)
    self.mainLayout.addWidget(self.magPlotWidget, 3,0,1,1)
    self.mainLayout.addWidget(self.barPlotWidget, 3,1,1,1)
    self.mainLayout.addLayout(debugLayout, 4,0,1,2)


    self.serialBtn.clicked.connect(self.serialBtnCmd)

    self.serialBtnCmd()

  # ---------------------------------------------------------------------------------------
  def setupSerialThread(self):
    portVal = self.serialLine.text()
    baudRate = int(self.baudRateCombo.currentText())

    self.serialThread = SerialThread()
    self.serialThread.serialConn(portVal, baudRate)
    self.serialThread.progress.connect(self.update, Qt.QueuedConnection)
    
    if not self.serialThread.isRunning():
      self.serialThread.start()       

  # ---------------------------------------------------------------------------------------
  def update(self, line):
    if self.skipDataCount: # skip the first couple lines of data, because there could be some junk
      self.skipDataCount-=1
      return

    try:
      data = map(float, line.split(','))
      dataChunks =[data[x:x+3] for x in xrange(0, len(data), 3)]
    except ValueError, e:
      print 'ERROR', e
      return

    self.accDataCurr = map(int, dataChunks[0])
    self.gyrDataCurr = map(int, dataChunks[1])
    self.magDataCurr = map(int, dataChunks[2])
    self.barDataCurr = dataChunks[3]

    self.accPlotWidget.update(self.accDataCurr)
    self.gyrPlotWidget.update(self.gyrDataCurr)
    self.magPlotWidget.update(self.magDataCurr)
    self.barPlotWidget.update(self.barDataCurr)

    eulerAngles = self.dcm.update(self.accDataCurr, self.gyrDataCurr, self.magDataCurr)
    self.viewport.updateView(eulerAngles)
コード例 #40
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.setWindowTitle("Copy Character — {}".format(
            QApplication.applicationName()))
        QShortcut(QKeySequence(QKeySequence.FindNext), self, self.findNext)
        self.state = state
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.findSizes(self.fontComboBox.currentFont())
        self.setToFamily(self.state.stdFontFamily)
        self.setToNearestSize(self.state.stdFontSize)
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        self.fontLabel = QLabel("Fon&t:")
        self.fontComboBox = QFontComboBox()
        self.tooltips.append((self.fontComboBox, """\
<p><b>Font</b></p>
<p>The font for displaying the characters.</p>"""))
        self.fontLabel.setBuddy(self.fontComboBox)
        self.sizeLabel = QLabel("&Size:")
        self.sizeComboBox = QComboBox()
        self.tooltips.append((self.sizeComboBox, """\
<p><b>Size</b></p>
<p>The size of font for displaying the characters.</p>"""))
        self.sizeLabel.setBuddy(self.sizeComboBox)
        self.scrollArea = QScrollArea()
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.panel = Panel()
        self.scrollArea.setWidget(self.panel)
        self.copyTextLabel = QLabel("Copy T&ext")
        self.copyTextLineEdit = QLineEdit()
        self.tooltips.append((self.copyTextLineEdit, """\
<p><b>Copy Text editor</b></p>
<p>The text for copying to the clipboard when <b>Copy</b> is
pressed.</p>"""))
        self.copyTextLabel.setBuddy(self.copyTextLineEdit)
        self.findTextLabel = QLabel("&Find Text")
        self.findTextLineEdit = QLineEdit()
        self.tooltips.append((self.findTextLineEdit, """\
<p><b>Find Text editor</b></p>
<p>The name or partial name of Unicode characters to be found, e.g.,
“star” will match many characters, including U+22C6 “Star
operator”.</p>"""))
        self.findTextLabel.setBuddy(self.findTextLineEdit)
        self.buttonBox = QDialogButtonBox()
        self.addSelectedButton = QPushButton(QIcon(":/add.svg"),
                                             "&Add Selected")
        self.tooltips.append((self.addSelectedButton, """\
<p><b>Add Selected</b></p>
<p>Append the selected character to the <b>Copy Text</b> editor.</p>"""))
        self.buttonBox.addButton(self.addSelectedButton,
                                 QDialogButtonBox.ActionRole)
        self.findNextButton = QPushButton(QIcon(":/edit-find.svg"),
                                          "Find &Next")
        self.tooltips.append((self.findNextButton, """\
<p><b>Find Next</b></p>
<p>Find the next character whose Unicode name contains or equals the
<b>Find Text</b>.</p>"""))
        self.buttonBox.addButton(self.findNextButton,
                                 QDialogButtonBox.ActionRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Copy Character dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)

    def layoutWidgets(self):
        topLayout = QHBoxLayout()
        topLayout.addWidget(self.fontLabel)
        topLayout.addWidget(self.fontComboBox, 1)
        topLayout.addWidget(self.sizeLabel)
        topLayout.addWidget(self.sizeComboBox)

        bottomLayout = QHBoxLayout()
        bottomLayout.addWidget(self.copyTextLabel)
        bottomLayout.addWidget(self.copyTextLineEdit)
        bottomLayout.addWidget(self.findTextLabel)
        bottomLayout.addWidget(self.findTextLineEdit)

        layout = QVBoxLayout()
        layout.addLayout(topLayout)
        layout.addWidget(self.scrollArea, 1)
        layout.addLayout(bottomLayout)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def createConnections(self):
        self.fontComboBox.activated[str].connect(self.panel.updateFont)
        self.sizeComboBox.currentIndexChanged[str].connect(
            self.panel.updateSize)
        self.panel.characterSelected.connect(self.copyTextLineEdit.insert)
        self.panel.fontResized.connect(self.updateSize)
        self.addSelectedButton.clicked.connect(self.addSelected)
        self.helpButton.clicked.connect(self.help)
        self.buttonBox.rejected.connect(self.accept)
        self.findNextButton.clicked.connect(self.findNext)
        self.findTextLineEdit.returnPressed.connect(self.findNext)

    def help(self):
        self.state.help("xix_ref_dlg_copychr.html")

    def findSizes(self, font):
        fontDatabase = QFontDatabase()
        currentSize = self.sizeComboBox.currentText()
        with Lib.BlockSignals(self.sizeComboBox):
            self.sizeComboBox.clear()
            if fontDatabase.isSmoothlyScalable(font.family(),
                                               fontDatabase.styleString(font)):
                for size in QFontDatabase.standardSizes():
                    self.sizeComboBox.addItem(str(size))
            else:
                for size in fontDatabase.smoothSizes(
                        font.family(), fontDatabase.styleString(font)):
                    self.sizeComboBox.addItem(str(size))
            self.sizeComboBox.setEditable(False)
        sizeIndex = self.sizeComboBox.findText(currentSize)
        if sizeIndex == -1:
            self.sizeComboBox.setCurrentIndex(
                max(0,
                    self.sizeComboBox.count() / 3))
        else:
            self.sizeComboBox.setCurrentIndex(sizeIndex)

    def accept(self):
        clipboard = QApplication.clipboard()
        text = self.copyTextLineEdit.text() or self.panel.currentChar
        clipboard.setText(text, QClipboard.Clipboard)
        clipboard.setText(text, QClipboard.Selection)
        if text:
            say("Copied “{}” to the clipboard".format(text), SAY_TIMEOUT)
        super().accept()

    def addSelected(self):
        char = self.panel.currentChar
        if char:
            self.copyTextLineEdit.setText(self.copyTextLineEdit.text() + char)
        self.findNextButton.setFocus()

    def setToFamily(self, family):
        family = family.casefold()
        for i in range(self.fontComboBox.count()):
            if self.fontComboBox.itemText(i).casefold() == family:
                self.fontComboBox.setCurrentIndex(i)
                break

    def setToNearestSize(self, size):
        below = 0
        belowIndex = -1
        above = 999
        aboveIndex = -1
        for i in range(self.sizeComboBox.count()):
            sz = int(self.sizeComboBox.itemText(i))
            if sz == size:
                self.sizeComboBox.setCurrentIndex(i)
                break
            if sz < size and sz > below:
                below = sz
                belowIndex = i
            if sz > size and sz < above:
                above = sz
                aboveIndex = i
        else:
            if abs(size - below) < abs(size - above):
                self.sizeComboBox.setCurrentIndex(belowIndex)
            else:
                self.sizeComboBox.setCurrentIndex(aboveIndex)

    def findNext(self):
        text = self.findTextLineEdit.text().strip().casefold()
        if text:
            start = self.panel.currentChar
            start = ord(start) if start else ord(" ")
            for i in range(start + 1, MAX_CHAR):
                try:
                    char = chr(i)
                    name = unicodedata.name(char).casefold()
                    if text in name:
                        self.panel.currentChar = char
                        self.panel.update()
                        y = (self.panel.squareSize * i) // COLUMNS
                        self.scrollArea.ensureVisible(0, y)
                        break
                except ValueError:
                    pass
            else:
                self.panel.currentChar = " "
                self.findNext()

    def keyPressEvent(self, event):
        key = event.key()
        if key in {Qt.Key_Enter, Qt.Key_Return}:
            if self.findTextLineEdit.text().strip():
                self.findNext()
            else:
                self.addSelectedButton.setFocus()

    def updateSize(self, squareSize):
        self.setMinimumWidth((COLUMNS + (1.5 if WIN else 1)) * squareSize)
コード例 #41
0
ファイル: tools.py プロジェクト: nocl/calculate-3-console-gui
class ToolOther(QtGui.QWidget):
    def __init__(self, parent, ClientObj):
        QtGui.QWidget.__init__(self, parent)
        self.user_config = ClientObj.user_config
        self._parent = parent

        self.grid = QtGui.QGridLayout(self)

        self.grid.setContentsMargins(2, 2, 2, 2)
        self.grid.setSpacing(2)
        self.grid.setColumnStretch(0, 3)
        self.grid.setColumnStretch(1, 5)

        # lang settings
        self.lang_lbl = LabelWordWrap(_("Select Language"), self)
        self.lang_lbl.setMaximumWidth(self.lang_lbl.sizeHint().width())

        self.lang_ComboBox = QComboBox(self)
        lang_dict = {"en": _("English"), "ru": _("Russian"), "fr": _("French")}

        for lang in lang_dict:
            self.lang_ComboBox.addItem(lang_dict[lang])
            self.lang_ComboBox.setItemData(self.lang_ComboBox.count() - 1, lang)
            if ClientObj.lang == lang:
                self.lang_ComboBox.setCurrentIndex(self.lang_ComboBox.count() - 1)

        # add lang settings in grid
        self.grid.addWidget(self.lang_lbl, 0, 0)
        self.grid.addWidget(self.lang_ComboBox, 0, 1)

        # add open file in grid
        self.cert_path_lbl = LabelWordWrap(_("Path to Certificates"), self)
        self.cert_path_lbl.setMaximumWidth(self.cert_path_lbl.sizeHint().width())

        self.fd_cert = FileOpenWgt(self, "dir", _("Certificate Directory"), "~/.calculate")

        self.fd_cert.setToolTip(_("Empty to default path"))
        self.fd_cert.setText(ClientObj.path_to_cert)

        self.grid.addWidget(self.cert_path_lbl, 1, 0)
        self.grid.addWidget(self.fd_cert, 1, 1)

        #        # add timeout in grid
        #        self.timeout_lbl = LabelWordWrap(_('Timeout'), self)
        #        self.timeout_lbl.setMaximumWidth(self.timeout_lbl.sizeHint().width())
        #
        #        self.timeout_lineedit = QtGui.QLineEdit(self)
        #
        #        self.timeout_lineedit.setText(str(ClientObj.timeout))
        #
        #        self.grid.addWidget(self.timeout_lbl, 2, 0)
        #        self.grid.addWidget(self.timeout_lineedit, 2, 1)

        # add spacer
        self.grid.addItem(QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding), 5, 0, 1, 2)

        # connect all with change value slot
        self.lang_ComboBox.currentIndexChanged.connect(self.changed_val)
        self.fd_cert.textChanged.connect(self.changed_val)
        #        self.timeout_lineedit.textChanged.connect(self.changed_val)

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

    def changed_val(self):
        self._parent.changed_flag = True

    def check_cfg(self, flag, config, part, param, value):
        # if param not exists in config
        if not flag:
            part_flag = False
            temp_cfg = []
            for line in config:
                temp_cfg.append(line)
                # add new line in config
                if line.startswith(part):
                    temp_cfg.append("%s = %s\n" % (param, value))
                    part_flag = True

            config = temp_cfg
            # if part not exists
            if not part_flag:
                config.append("\n")
                config.append("%s\n" % part)
                config.append("%s = %s\n" % (param, value))
        return config

    def save_changes(self, ClientObj):
        def wrapper():
            if not os.path.isfile(self.user_config):
                f = open(self.user_config, "w")
                f.close()

            fc = open(self.user_config, "r")
            config = fc.readlines()
            fc.close()
            new_config = []

            lang_flag = False
            cert_flag = False
            #            timeout_flag = False
            for line in config:
                if line.startswith("lang "):
                    lang_flag = True
                    new_config.append("lang = %s\n" % self.lang_ComboBox.itemData(self.lang_ComboBox.currentIndex()))
                elif line.startswith("path_to_cert "):
                    cert_flag = True
                    if os.path.isdir(self.fd_cert.text()):
                        new_config.append("path_to_cert = %s\n" % self.fd_cert.text())
                    elif not self.fd_cert.text():
                        new_config.append("path_to_cert = no\n")
                    else:
                        new_config.append(line)
                #                elif line.startswith('timeout '):
                #                    timeout_flag = True
                #                    try:
                #                        timeout = int(self.timeout_lineedit.text())
                #                    except ValueError:
                #                        timeout = ClientObj.timeout
                #                    new_config.append('timeout = %d\n' %timeout)
                else:
                    new_config.append(line)

            new_config = self.check_cfg(
                lang_flag, new_config, "[other]", "lang", self.lang_ComboBox.itemData(self.lang_ComboBox.currentIndex())
            )

            if not self.fd_cert.text().lower():
                new_config = self.check_cfg(cert_flag, new_config, "[other]", "path_to_cert", "no")
            elif os.path.isdir(self.fd_cert.text()):
                new_config = self.check_cfg(cert_flag, new_config, "[other]", "path_to_cert", self.fd_cert.text())

            #            try:
            #                timeout = int(self.timeout_lineedit.text())
            #            except ValueError:
            #                timeout = ClientObj.timeout
            #            new_config = self.check_cfg (timeout_flag, new_config, \
            #                                '[other]', 'timeout', timeout)

            fnc = open(self.user_config, "w")
            for line in new_config:
                fnc.write(line)
            fnc.close()

            # read config for changed parameters
            ClientObj.create_user_config()
            ClientObj.read_user_config(ClientObj.user_config)

            # reset unsaved changes flag
            self._parent.changed_flag = False
            if ClientObj.client:
                from session_function import client_post_cert

                ClientObj.lang = self.lang_ComboBox.itemData(self.lang_ComboBox.currentIndex())
                if ClientObj.client:
                    try:
                        client_post_cert(ClientObj.client, ClientObj.lang)
                    except:
                        return
                    ClientObj.methods_list = client_list_methods(ClientObj.sid, ClientObj.client)
                    from DisplayMethod import DisplayMethod

                    if type(ClientObj.MainWidget.MainFrameWgt) == DisplayMethod:
                        ClientObj.MainWidget.display_methods()

        return wrapper
コード例 #42
0
class TransformationFaceUI(QWidget):
    def __init__(self, oriPath, protoPath, oriPointsPath, protoPointsPath,
                 regionsPath):
        super(TransformationFaceUI, self).__init__()
        #Initialize the data or object we need

        localParas, points = preprocess(oriPath, protoPath, oriPointsPath,
                                        protoPointsPath, regionsPath, 'L2')
        self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas
        self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points
        self.oriPoints = np.array(self.oriPoints)
        self.protoPoints = np.array(self.protoPoints)
        self.e = 2
        self.alpha = 1
        self.oriPath = oriPath
        self.protoPath = protoPath
        self.oriPointsPath = oriPointsPath
        self.protoPointsPath = protoPointsPath
        self.regionsPath = regionsPath
        self.transform = 'Local Affine Transformation'
        self.newImg = None
        self.initUI()

    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 10))
        self.setGeometry(300, 200, 810, 430)
        self.setWindowTitle('Transformation on Human Face')

        #Method choose combobox
        self.comboAffineLabel = QLabel(self)
        self.comboAffineLabel.setText('Transformation Method:')
        self.comboAffineLabel.setGeometry(60, 270, 230, 30)

        self.comboAffine = QComboBox(self)
        self.comboAffine.addItem("Local Affine Transformation")
        self.comboAffine.addItem("Moving Least Squares")
        self.comboAffine.addItem("Morphing")
        self.comboAffine.setGeometry(22, 290, 225, 30)
        self.comboAffine.activated[str].connect(self.affineChoiceChange)

        #The button to choose the original figure
        self.oriBtn = QPushButton('Choose Original Picture', self)
        self.oriBtn.setToolTip('Choose Original Picture')
        self.oriBtn.setGeometry(20, 330, 230, 30)
        self.oriBtn.clicked.connect(self.showOriDialog)

        #The button to choose the proto figure
        self.protoBtn = QPushButton('Choose Proto Picture', self)
        self.protoBtn.setToolTip('Choose Proto Picture')
        self.protoBtn.setGeometry(20, 365, 230, 30)
        self.protoBtn.clicked.connect(self.showProtoDialog)

        #The distance function choose combobox
        self.comboLabel = QLabel(self)
        self.comboLabel.setText('Distance Fun:')
        self.comboLabel.setGeometry(310, 280, 200, 30)

        self.comboDis = QComboBox(self)
        self.comboDis.addItem("L2")
        self.comboDis.addItem("L1")
        self.comboDis.setGeometry(410, 280, 80, 30)

        self.comboDis.activated[str].connect(self.distanceChoiceChange)

        #E choose slider

        self.eLabel = QLabel(self)
        self.eLabel.setText('E Value:0.00')
        self.eLabel.setGeometry(310, 320, 200, 30)
        self.eSld = QSlider(Qt.Horizontal, self)
        self.eSld.setRange(0, 10**5)
        self.eSld.setFocusPolicy(Qt.NoFocus)
        self.eSld.setGeometry(390, 320, 120, 30)
        self.eSld.valueChanged[int].connect(self.changeEValue)

        #alpha choose slider
        self.aLabel = QLabel(self)
        self.aLabel.setText('Alpha Value:0.00')
        self.aLabel.setGeometry(310, 360, 200, 30)
        self.aSld = QSlider(Qt.Horizontal, self)
        self.aSld.setRange(0, 10**5)
        self.aSld.setFocusPolicy(Qt.NoFocus)
        self.aSld.setGeometry(410, 360, 100, 30)
        self.aSld.valueChanged[int].connect(self.changeAlphaValue)

        # Picture show
        self.oriTextLabel = QLabel(self)
        self.protoTextLabel = QLabel(self)
        self.transTextLabel = QLabel(self)
        self.oriTextLabel.setText('The Orginal Picture')
        self.protoTextLabel.setText('The Proto Picture')
        self.transTextLabel.setText('The Picture after Transformation')

        self.oriTextLabel.move(70, 5)
        self.protoTextLabel.move(350, 5)
        self.transTextLabel.move(580, 5)

        self.oriLabel = QLabel(self)
        self.protoLabel = QLabel(self)
        self.transLabel = QLabel(self)

        pixmap = QPixmap(self.oriPath)
        pixmap2 = QPixmap(self.protoPath)
        self.oriLabel.setPixmap(pixmap)
        self.protoLabel.setPixmap(pixmap2)
        self.transLabel.setPixmap(pixmap)

        #Position setting
        self.oriLabel.setGeometry(20, 20, 230, 230)
        self.protoLabel.setGeometry(290, 20, 230, 230)
        self.transLabel.setGeometry(560, 20, 230, 230)
        self.oriLabel.setScaledContents(True)
        self.protoLabel.setScaledContents(True)
        self.transLabel.setScaledContents(True)
        #Load button
        self.loadOriBtn = QPushButton('Load Ori Points', self)
        self.loadOriBtn.setToolTip('Load Control Points From Txt File')
        self.loadOriBtn.setGeometry(550, 280, 130, 30)
        self.loadOriBtn.clicked.connect(self.showLoadOriDialog)

        self.loadProtoBtn = QPushButton('Load Proto Points', self)
        self.loadProtoBtn.setToolTip('Load Control Points From Txt File')
        self.loadProtoBtn.setGeometry(680, 280, 130, 30)
        self.loadProtoBtn.clicked.connect(self.showLoadProtoDialog)
        #Face ++ button
        self.faceBtn = QPushButton('Face++ Keypoint', self)
        self.faceBtn.setToolTip('Save the Face++ Keypoints')
        self.faceBtn.setGeometry(550, 315, 130, 30)
        self.faceBtn.clicked.connect(self.detectKeyPoints)
        #Load region Button
        self.loadRegionBtn = QPushButton('Load Regions', self)
        self.loadRegionBtn.setToolTip('Load Regions From Txt File')
        self.loadRegionBtn.setGeometry(680, 315, 130, 30)
        self.loadRegionBtn.clicked.connect(self.showLoadRegionDialog)

        #Save Button setting
        self.saveBtn = QPushButton('Save', self)
        self.saveBtn.setToolTip(
            'Transform this picture to the shape of Baboon')
        self.saveBtn.setGeometry(560, 350, 110, 40)
        self.saveBtn.clicked.connect(self.saveImg)

        #Transform action button
        self.confirmBtn = QPushButton('Generate', self)
        self.confirmBtn.setToolTip('Generate')
        self.confirmBtn.setGeometry(680, 350, 110, 40)
        self.confirmBtn.clicked.connect(self.transformAction)

        self.show()

    #Invoke face++ and save which is connected to the facebtn
    def detectKeyPoints(self):
        print(self.oriPath)
        save_points('face_keypoints_ori.txt',
                    detect((self.oriPath).encode('utf-8')))

    #Save img connected to the save button
    def saveImg(self):
        if self.newImg == None:
            QtGui.QMessageBox.information(self, "Error",
                                          "There is not transformed figure")
        result = Image.fromarray(self.newImg)
        filenames = self.oriPath.split('/')
        filenames[len(filenames) -
                  1] = 'trans_' + filenames[len(filenames) - 1]
        newPath = '/'.join(filenames)
        result.save(newPath)

    #Connected to the transform button did the deformation and show it
    def transformAction(self):

        try:
            #For different methods have different solution
            if self.transform == 'Morphing':
                self.oriImg = np.array(Image.open(self.oriPath))
                self.protoImg = np.array(Image.open(self.protoPath))
                if self.oriImg.shape != self.protoImg.shape:
                    QtGui.QMessageBox.information(
                        self, "Error",
                        "It is image morphing and required the same size of two images,please choose other images"
                    )
                    return
                newImg = morphingAction((self.oriPath).encode('utf-8'),
                                        self.protoPath.encode('utf-8'),
                                        self.protoPointsPath.encode('utf-8'),
                                        self.alpha)
            else:
                localParas, points = preprocess(self.oriPath, self.protoPath,
                                                self.oriPointsPath,
                                                self.protoPointsPath,
                                                self.regionsPath, 'L2')
                if points == None:
                    QtGui.QMessageBox.information(self, "Error", localParas)
                    return
                self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas
                self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points
                if self.oriImg.shape[len(self.oriImg.shape) -
                                     1] != self.protoImg.shape[
                                         len(self.protoImg.shape) - 1]:
                    QtGui.QMessageBox.information(
                        self, "Error",
                        "The type of the figures is not the same, please choose another figure"
                    )
                    return
                if self.transform == 'Local Affine Transformation':
                    newImg = local_affine_transformation(
                        self.oriImg, self.protoImg, self.e, self.regionsPoints,
                        self.is_in_regions_fun, self.distance_funs,
                        self.affine_funs)
                elif self.transform == "Moving Least Squares":
                    newImg = affine_points_MLS(self.oriImg, self.protoImg,
                                               self.oriPoints,
                                               self.protoPoints, self.alpha)
        except BaseException:

            QtGui.QMessageBox.information(
                self, "Error",
                "There are error in the point choice or other things.")
            newImg = morphingAction((self.oriPath).encode('utf-8'),
                                    self.protoPath.encode('utf-8'),
                                    self.protoPointsPath.encode('utf-8'),
                                    self.alpha)

        self.newImg = np.uint8(newImg)
        newImg = rgb2bgr(np.uint8(newImg))

        qimage = QImage(newImg, newImg.shape[1], newImg.shape[0],
                        QImage.Format_ARGB32)
        pixmap_array = QPixmap.fromImage(qimage)
        self.transLabel.setPixmap(pixmap_array)
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################

#The file chooser , all of the function begin with show is the same but for different parameter.

    def showProtoDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Open file', '/home', "Image Files (*.png *.jpg *.bmp)")
        if fname != None and fname != '':
            self.protoPath = fname
            self.protoLabel.setPixmap(QPixmap(self.protoPath))

    def showLoadOriDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.oriPointsPath = fname

    def showLoadRegionDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.regionsPath = fname

    def showLoadProtoDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                                                     '/home',
                                                     "Text files (*.txt)")
        if fname != None and fname != '':
            self.protoPointsPath = fname

    def showOriDialog(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self, 'Open file', '/home', "Image Files (*.png *.jpg *.bmp)")
        if fname != None and fname != '':
            self.oriPath = fname
            print(self.oriPath)
            self.oriLabel.setPixmap(QPixmap(self.oriPath))

    #Connected with eSld change the e value in LAT method
    def changeEValue(self, x):
        self.e = 4.0 * x / 10**5
        self.eLabel.setText('E Value:' + str('%.2f' % self.e))

    #Connected with aSld change the alpha value in MLS and Morphing method(but the alpha range is not the same)
    def changeAlphaValue(self, x):
        if self.transform == 'Moving Least Squares':
            self.alpha = 2.0 * x / 10**5
        elif self.transform == 'Morphing':
            self.alpha = 1.0 * x / 10**5
        self.aLabel.setText('Alpha Value:' + str('%.2f' % self.alpha))

    #Connected to the method combobox
    def affineChoiceChange(self, item):

        if self.transform in ['Moving Least Squares', 'Morphing'] and item in [
                'Moving Least Squares', 'Morphing'
        ] and item != self.transform:
            self.alpha = 0.0
            self.aSld.setValue(self.alpha)
        self.transform = item

    #Connected to the distance combobox
    def distanceChoiceChange(self, item):
        self.oriImg, self.protoImg, self.protoPoints, self.affine_funs = preprocess(
            oriPath, protoPath, oriPointsPath, protoPointsPath, item)
コード例 #43
0
ファイル: mass_attr.py プロジェクト: DavideAlidosi/May9
class MassAttribute_UI(QDialog):
    """
    The main UI
    """
    class Applikator(QObject):
        """
        This is the core applier which toggle the display of the corresponding widget and handling events' connections
        """
        def __init__(self, parent=None):
            super(MassAttribute_UI.Applikator, self).__init__()
            self.root = parent

        def widget_event(self, t):
            """
            Return the correct widget's event depending on attribute's type
            :param t: the attribute's type
            :type  t: str
            :return: the event
            :rtype : Signal
            """
            return {'float': self.root.W_EDI_float.valueChanged, 'enum': self.root.W_EDI_enum.currentIndexChanged,
                    'int': self.root.W_EDI_int.valueChanged, 'bool': self.root.W_EDI_bool.stateChanged,
                    'str': self.root.W_EDI_str.textChanged, 'd3': self.root.W_EDI_d3.valuesChanged,
                    'd4': self.root.W_EDI_d4.valuesChanged, 'color': self.root.W_EDI_color.colorChanged}[t]

        def unset_editors(self):
            """
            Toggle off all editors and disconnect the current one
            """
            for widget in (self.root.W_EDI_float, self.root.W_EDI_int, self.root.W_EDI_enum,
                           self.root.W_EDI_bool, self.root.W_EDI_str, self.root.W_EDI_d3,
                           self.root.W_EDI_d4, self.root.W_EDI_color):
                widget.setVisible(False)

            # trying to force disconnection
            try:
                self.widget_event(self.root.ctx).disconnect(self.root.apply_value)
            except (KeyError, RuntimeError):
                pass

        def prepare(applier_name):
            """
            A decorator to prepare the attribute depending on type for the corresponding widget and getting the
            attribute's value
            :param applier_name: attribute's type
            :type  applier_name: str
            """
            def sub_wrapper(func):
                def wrapper(self, attr_path):
                    self.unset_editors()
                    self.root.ctx = applier_name
                    self.root.__getattribute__('W_EDI_%s' % applier_name).setVisible(True)
                    ret = func(self, cmds.getAttr(attr_path), attr_path)
                    return ret
                return wrapper
            return sub_wrapper

        @staticmethod
        def get_bounds(obj, attr, min_default, max_default):
            """
            Try to retrieve the range for the given attribute, if min or max fail it'll set default values
            :param         obj: the object's name
            :type          obj: str
            :param        attr: attribute's name
            :type         attr: str
            :param min_default: minimum default value
            :param max_default: max default value
            :type  min_default: float | int
            :type  max_default: float | int
            :return: minimum, maximum
            :rtype : tuple
            """
            try:
                assert cmds.attributeQuery(attr, n=obj, mxe=True)
                maxi = cmds.attributeQuery(attr, n=obj, max=True)[0]
            except (RuntimeError, AssertionError):
                maxi = max_default
            try:
                assert cmds.attributeQuery(attr, n=obj, mne=True)
                mini = cmds.attributeQuery(attr, n=obj, min=True)[0]
            except (RuntimeError, AssertionError):
                mini = min_default
            return mini, maxi

        @prepare('float')
        def apply_float(self, value, path):
            """
            Float attribute case
            :param value: attribute's value
            :param  path: attribute's path = obj.attr
            """
            obj, attr = path.split('.', 1)
            self.root.W_EDI_float.setRange(*self.get_bounds(obj, attr, -100.0, 100.0))
            self.root.W_EDI_float.setValue(value)

        @prepare('enum')
        def apply_enum(self, value, path):
            """Enum case"""
            self.root.W_EDI_enum.clear()
            obj, attr = path.split('.', 1)
            try:
                enums = [enum.split('=')[0] for enum in cmds.attributeQuery(attr, n=obj, listEnum=True)[0].split(':')]
            except RuntimeError:
                self.apply_int(path)
            else:
                self.root.W_EDI_enum.addItems(enums)
                self.root.W_EDI_enum.setCurrentIndex(enums.index(cmds.getAttr(path, asString=True)))

        @prepare('int')
        def apply_int(self, value, path):
            """Integer case"""
            obj, attr = path.split('.', 1)
            self.root.W_EDI_int.setRange(*self.get_bounds(obj, attr, -1000, 1000))
            self.root.W_EDI_int.setValue(value)

        @prepare('bool')
        def apply_bool(self, value, path):
            """Boolean case"""
            self.root.W_EDI_bool.setChecked(value)
            self.root.W_EDI_bool.setText(path.split('.', 1)[1])

        @prepare('str')
        def apply_str(self, value, path):
            """String case"""
            self.root.W_EDI_str.setText(value)

        @prepare('d3')
        def apply_d3(self, value, path):
            """3D array case"""
            self.root.W_EDI_d3.setValues(value[0])

        @prepare('d4')
        def apply_d4(self, value, path):
            """4D array case"""
            self.root.W_EDI_d4.setValues(value[0])

        @prepare('color')
        def apply_color(self, value, path):
            """Color case"""
            try:
                colors = value[0]
                self.root.W_EDI_color.setColor([int(c * 255) for c in colors])
            except TypeError:
                self.apply_int(value, path)

    class Attribute(str):
        """
        A custom string attribute class to ship more information into the string variable
        """
        def __new__(cls, path='', super_type=Object):
            obj, attr = path.split('.', 1)

            str_obj = str.__new__(cls, attr)

            str_obj.obj, str_obj.attr = obj, attr
            str_obj.path = path
            str_obj.super_type = super_type
            str_obj.type = None

            return str_obj

    # static variables to pre-load icons and attributes short names
    ctx_icons = {'float': QIcon(':render_decomposeMatrix.png'),
                 'enum': QIcon(':showLineNumbers.png'),
                 'bool': QIcon(':out_decomposeMatrix.png'),
                 'time': QIcon(':time.svg'),
                 'byte': QIcon(':out_defaultTextureList.png'),
                 'angle': QIcon(':angleDim.png'),
                 'string': QIcon(':text.png'),
                 'float3': QIcon(':animCurveTA.svg'),
                 'float4': QIcon(':animCurveTA.svg'),
                 'color': QIcon(':clampColors.svg')}

    for ctx in ('doubleLinear', 'double', 'long', 'short'):
        ctx_icons[ctx] = ctx_icons['float']

    ctx_icons['double3'] = ctx_icons['float3']
    ctx_icons['double4'] = ctx_icons['float4']

    ctx_wide = {'float': ('float', 'doubleLinear', 'double', 'long', 'short'),
                'enum': ('enum',),
                'bool': ('bool',),
                'time': ('time',),
                'byte': ('byte',),
                'angle': ('doubleAngle',),
                'string': ('string',),
                'float3': ('double3', 'float3'),
                'float4': ('double4', 'float4'),
                'color': ('color',)}

    def __init__(self, parent=None):
        super(MassAttribute_UI, self).__init__(parent)
        # Abstract
        self.applier = self.Applikator(self)
        self.selection = []
        self.callback = None
        self.ctx = None
        # storing found attributes' types to avoid double check
        self.solved = {}
        self.setLocale(QLocale.C)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAttribute(Qt.WA_QuitOnClose)

        self.setFixedWidth(300)
        self.setWindowTitle('Massive Attribute Modifier')

        # UI
        L_main = QVBoxLayout()

        self.WV_title = QLabel('')
        self.WV_title.setVisible(False)
        self.WV_title.setFont(QFont('Verdana', 10))
        self.WV_title.setContentsMargins(0, 0, 0, 7)

        self.WB_select = QPushButton('Select')
        self.WB_select.setVisible(False)
        self.WB_select.setFixedWidth(50)
        self.WB_select.clicked.connect(lambda: cmds.select(self.selection))

        self.WB_update = QPushButton('Update')
        self.WB_update.setFixedWidth(50)
        self.WB_update.clicked.connect(lambda:self.update_attributes(cmds.ls(sl=True)))

        self.WV_search = Filter()
        self.WV_search.textChanged.connect(self.filter)

        self.WC_cases = QCheckBox('Case sensitive')
        self.WC_cases.stateChanged.connect(self.filter)

        self.WC_types = QCheckBox('Type filtering')

        self.WL_attrtype = QComboBox()
        self.WL_attrtype.setEnabled(False)

        for i, ctx in enumerate(sorted(self.ctx_wide)):
            self.WL_attrtype.addItem(ctx.title())
            self.WL_attrtype.setItemIcon(i, self.ctx_icons[ctx])

        L_attrtype = line(self.WC_types, self.WL_attrtype)

        self.WC_types.stateChanged.connect(partial(self.update_attributes, self.selection))
        self.WC_types.stateChanged.connect(self.WL_attrtype.setEnabled)
        self.WL_attrtype.currentIndexChanged.connect(self.filter)

        self.WC_liveu = QCheckBox('Live')
        self.WC_liveu.stateChanged.connect(self.WB_update.setDisabled)
        self.WC_liveu.stateChanged.connect(self.set_callback)

        self.WC_histo = QCheckBox('Load history')
        self.WC_histo.setChecked(True)
        self.WC_histo.stateChanged.connect(partial(self.update_attributes, self.selection))

        self.WC_child = QCheckBox('Children')
        self.WC_child.stateChanged.connect(partial(self.update_attributes, self.selection))

        options = group('Options', line(self.WC_cases, L_attrtype),
                        line(self.WC_child, self.WC_histo, self.WC_liveu, self.WB_update))
        options.layout().setSpacing(2)

        self.WL_attributes = QTreeWidget()
        self.WL_attributes.setStyleSheet('QTreeView {alternate-background-color: #1b1b1b;}')
        self.WL_attributes.setAlternatingRowColors(True)
        self.WL_attributes.setHeaderHidden(True)
        self.WL_attributes.setRootIsDecorated(False)

        self.objs_attr = set()
        self.shps_attr = set()

        self.W_EDI_float = FloatBox()
        self.W_EDI_int = IntBox()
        self.W_EDI_enum = QComboBox()
        self.W_EDI_bool = QCheckBox()
        self.W_EDI_str = QLineEdit()
        self.W_EDI_d3 = Double3()
        self.W_EDI_d4 = Double4()
        self.W_EDI_color = ColorPicker()

        # Final layout
        L_title = line(self.WV_title, self.WB_select)
        L_title.setStretch(0, 1)
        L_main.addLayout(L_title)
        L_main.setAlignment(Qt.AlignLeft)
        L_main.addWidget(self.WV_search)
        L_main.addWidget(options)
        L_main.addWidget(self.WL_attributes)
        L_edits = col(self.W_EDI_bool, self.W_EDI_int, self.W_EDI_float,
                      self.W_EDI_enum, self.W_EDI_str, self.W_EDI_d3, self.W_EDI_d4,
                      self.W_EDI_color)
        L_edits.setContentsMargins(0, 8, 0, 0)
        L_main.addLayout(L_edits)
        L_main.setStretch(3, 1)
        L_main.setSpacing(2)

        self.appliers = {'float': self.applier.apply_float,
                         'enum': self.applier.apply_enum,
                         'bool': self.applier.apply_bool,
                         'time': self.applier.apply_float,
                         'byte': self.applier.apply_int,
                         'angle': self.applier.apply_float,
                         'string': self.applier.apply_str,
                         'float3': self.applier.apply_d3,
                         'float4': self.applier.apply_d4,
                         'color': self.applier.apply_color}

        self.setLayout(L_main)

        # final settings
        self.WL_attributes.itemSelectionChanged.connect(self.update_setter)
        self.applier.unset_editors()

    def closeEvent(self, *args, **kwargs):
        self.set_callback(False)

    def set_callback(self, state):
        """
        Toggle selection event callback
        :param state: checkbox's state
        :type  state: bool | int
        """
        if state and not self.callback:
            self.callback = MEventMessage.addEventCallback('SelectionChanged', self.update_attributes)
            self.update_attributes(cmds.ls(sl=True))

        elif not state and self.callback:
            MMessage.removeCallback(self.callback)
            self.callback = None

    @staticmethod
    def format_title(nodes):
        """
        Extract the matching characters from a given nodes selection, if begin matches it will return "joint*" with a
        wildcard when names don't match
        :param nodes: objects' list
        :type  nodes: list | tuple
        :return: the formatted name with the corresponding characters
        :rtype : str
        """
        res = None

        if nodes:
            # we get the first node as a reference
            node = nodes[0]
            # and compare with the other nodes
            subs = [w for w in nodes if w != node]

            l = 1
            valid = True
            # will continue until l (length) match the full name's length or until names don't match
            while l < len(node) and valid:
                for sub in subs:
                    if not sub.startswith(node[:l]):
                        valid = False
                        break

                else:
                    l += 1

            # if matching characters isn't long enough we only display the number of nodes selected
            if l <= 3:
                res = '%i objects' % len(nodes)

            # otherwise showing matching pattern
            elif l < len(node) or len(nodes) > 1:
                res = node[:l - 1] + '* (%i objects)' % len(nodes)

            else:
                res = node

        return res

    @staticmethod
    def get_history(node):
        """
        Extract history for the given node
        :rtype: list
        """
        return cmds.listHistory(node, il=2, pdo=True) or []

    @staticmethod
    def get_shapes(node):
        """
        Extract shape(s) for the given node
        :rtype: list
        """
        return cmds.listRelatives(node, s=True, ni=True, f=True)

    def get_attributes_type(self, attrs):
        """
        For a given list of attributes of type Attribute, will loop through and fill the type parameter of the
         attribute with the corresponding type, if type is invalid or not handled, it'll remove it
        :param attrs: attributes' list
        :type  attrs: [MassAttribute_UI.Attribute]
        :return: cleaned and filled attributes' list
        :rtype: [MassAttribute_UI.Attribute]
        """
        attrs = list(attrs)
        # first we sort the attributes' list
        attrs.sort()

        # then we try to extract the attribute's type
        for i, attr in enumerate(attrs):
            try:
                if attr.attr in self.solved:
                    attr.type = self.solved[attr.attr]
                    raise RuntimeError
                tpe = cmds.getAttr(attr.path, typ=True)
                assert tpe
                attr.type = tpe
                self.solved[attr.attr] = tpe
            except (AssertionError, ValueError, RuntimeError):
                pass

        # defining a to-remove list
        rm_list = set()

        layers = {'3': 'XYZ', '4': 'XYZW'}
        for i, attr in enumerate(attrs):
            if i in rm_list:
                continue

            # we handle some special cases here, if ever the attribute list contains RGB and separate R, G and B we
            # assume it's a color, if it's a double3 or float3 and we find the corresponding XYZ, we remove then to
            # avoid duplicates

            if attr.endswith('RGB'):
                if '%sR' % attr[:-3] in attrs:
                    attr.type = 'color'
                    for chan in 'RGB':
                        rm_list.add(attrs.index('%s%s' % (attr[:-3], chan)))

            # if the attribute's type isn't in the list, we remove
            elif attr.type not in MassAttribute_UI.ctx_icons:
                rm_list.add(i)

            elif attr.endswith('R'):
                if '%sG' % attr[:-1] in attrs and attr[:-1] in attrs:
                    attr.type = 'color'
                    for chan in 'RGB':
                        rm_list.add(attrs.index('%s%s' % (attr[:-1], chan)))

            elif attr.type in ('double3', 'double4', 'float3', 'float4'):
                if '%sX' % attr in attrs:
                    for chan in layers[attr.type[-1]]:
                        rm_list.add(attrs.index('%s%s' % (attr, chan)))

        # finally cleaning the list
        for i in sorted(rm_list, reverse=True):
            attrs.pop(i)

        return attrs

    def apply_value(self, value):
        """
        When the value is modified in the UI, we forward the given value and applies to the object's
        :param value: attribute's value, mixed type
        :type  value: mixed
        """
        # We get the only selected object in list and get it's super type (Shape, History or Object) and
        # type (float, int, string)
        item = self.WL_attributes.selectedItems()[0]
        attr = item.attribute
        shape = attr.super_type == Shape
        histo = attr.super_type == History
        tpe = item.attribute.type

        # eq dict for each context
        value = {'bool': bool,
                 'int': int,
                 'float': float,
                 'enum': int,
                 'str': str,
                 'd3': list,
                 'd4': list,
                 'color': list}[self.ctx](value)

        # converting the selection into a set
        cmds.undoInfo(openChunk=True)
        targets = set(self.selection)

        # we propagate to children if 'Children' checkbox is on
        if self.WC_child.isChecked():
            for obj in list(targets):
                targets |= set(cmds.listRelatives(obj, ad=True))

        # if the target attribute is on the history, we add all selection's history to the list
        if histo:
            for obj in list(targets):
                targets.remove(obj)
                targets |= set(self.get_history(obj))

        # then we loop through target objects
        for obj in targets:
            # if the target is on the shape we get object's shape
            if shape and not histo:
                shapes = self.get_shapes(obj)

                if obj in shapes:
                    continue
                else:
                    obj = shapes[0]

            # then we try to apply depending on attribute's type
            try:
                correct_path = attr.path.replace(attr.obj, obj)

                if tpe == 'string':
                    cmds.setAttr(correct_path, value, type='string')

                elif tpe in ('double3', 'double4', 'float3', 'float4', 'color'):
                    cmds.setAttr(correct_path, *value, type='double%d' % len(value))

                else:
                    cmds.setAttr(correct_path, value)

            except RuntimeError:
                pass

        cmds.undoInfo(closeChunk=True)

    def update_setter(self):
        """
        When the list's selection changes we update the applier widget
        """
        item = self.WL_attributes.selectedItems()
        # abort if no item is selected
        if not len(item):
            return

        # getting attribute's parameter
        attr = item[0].attribute

        if len(self.selection):
            try:
                # looping until we find a context having the current attribute's type
                for applier in self.ctx_wide:
                    if attr.type in self.ctx_wide[applier]:
                        break
                # then we apply for the given path (obj.attribute)
                self.appliers[applier](attr.path)

                # and connecting event to the self.apply_value function
                self.applier.widget_event(self.ctx).connect(self.apply_value)

            # otherwise selection or type is invalid
            except IndexError:
                self.ctx = None

    def update_attributes(self, selection=None, *args):
        """
        Update the attributes for the given selection, looping through objects' attributes, finding attr in common
        between all objects then cleaning the lists, doing the same for shapes and / or histories
        :param selection: object's selection
        """
        # redefining lists as set to intersect union etc
        self.objs_attr = set()
        self.shps_attr = set()

        # pre init
        self.WL_attributes.clear()
        self.applier.unset_editors()

        self.selection = selection or (cmds.ls(sl=True) if self.WC_liveu.isChecked() else self.selection)

        self.WV_title.setText(self.format_title(self.selection))
        self.WV_title.setVisible(bool(len(self.selection)))
        self.WB_select.setVisible(bool(len(self.selection)))

        if not len(self.selection):
            return

        def get_usable_attrs(obj, super_type):
            """
            Small internal function to get a compatible attributes' list for the given object and assign the given
            super_type to it (Object, Shape or History)
            :param        obj: object's name
            :type         obj: str
            :param super_type: attribute's main type
            :type  super_type: Object | Shape | History
            :return:
            """
            return set([MassAttribute_UI.Attribute('%s.%s' % (obj, attr), super_type) for attr in
                        cmds.listAttr(obj, se=True, ro=False, m=True, w=True)])

        if len(self.selection):
            self.objs_attr = get_usable_attrs(self.selection[0], Object)

            # if we also want the object's history we add it to the initial set
            if self.WC_histo.isChecked():
                for histo in self.get_history(self.selection[0]):
                    self.objs_attr |= get_usable_attrs(histo, History)

            # filling the shape's set
            for shape in (self.get_shapes(self.selection[0]) or []):
                self.shps_attr |= get_usable_attrs(shape, Shape)

            # if selection's length bigger than one we compare by intersection with the other sets
            if len(self.selection) > 1:
                for obj in self.selection:
                    sub_attr = get_usable_attrs(obj, Object)

                    if self.WC_histo.isChecked():
                        for histo in self.get_history(obj):
                            sub_attr |= get_usable_attrs(histo, History)

                    self.objs_attr.intersection_update(sub_attr)

                    for shape in (self.get_shapes(self.selection[0]) or []):
                        self.shps_attr.intersection_update(get_usable_attrs(shape, Shape))

            # finally getting all intersecting attributes' types
            self.objs_attr = self.get_attributes_type(self.objs_attr)
            self.shps_attr = self.get_attributes_type(self.shps_attr)

        # and filtering the list
        self.filter()

    def add_set(self, iterable, title=None):
        """
        Adding the given iterable to the list with a first Separator object with given title
        :param iterable: list of item's attributes
        :param    title: Separator's name
        """
        if len(iterable):
            # if title is given we first add a Separator item to indicate coming list title
            if title:
                self.WL_attributes.addTopLevelItem(QTreeWidget_Separator(title))

            items = []
            for attr in sorted(iterable):
                item = QTreeWidgetItem([attr])
                # assigning the attribute itself inside a custom parameter
                item.attribute = attr
                items.append(item)

            # finally adding all the items to the list
            self.WL_attributes.addTopLevelItems(items)

    def filter(self):
        """
        Filter the list with UI's parameters, such as name or type filtering, etc
        """
        # pre cleaning
        self.WL_attributes.clear()

        # using regex compile to avoid re execution over many attributes
        mask = self.WV_search.text()
        case = 0 if self.WC_cases.isChecked() else re.IGNORECASE
        re_start = re.compile(r'^%s.*?' % mask, case)
        re_cont = re.compile(r'.*?%s.*?' % mask, case)

        # getting the four different lists
        obj_start = set([at for at in self.objs_attr if re_start.search(at)])
        shp_start = set([at for at in self.shps_attr if re_start.search(at)])

        # if type filtering is one we only extract the wanted attribute's type
        if self.WC_types.isChecked():
            obj_start = set([at for at in obj_start if
                             at.type in self.ctx_wide[self.WL_attrtype.currentText().lower()]])
            shp_start = set([at for at in shp_start if
                             at.type in self.ctx_wide[self.WL_attrtype.currentText().lower()]])

        # finally adding the current sets if there is a mask we add the also the containing matches
        if mask:
            # getting contains filtering and type containers filtering
            obj_contains = obj_start.symmetric_difference(set([at for at in self.objs_attr if re_cont.search(at)]))
            shp_contains = shp_start.symmetric_difference(set([at for at in self.shps_attr if re_cont.search(at)]))
            if self.WC_types.isChecked():
                obj_contains = set([at for at in obj_contains if
                                    at.type in self.ctx_wide[self.WL_attrtype.currentText().lower()]])
                shp_contains = set([at for at in shp_contains if
                                    at.type in self.ctx_wide[self.WL_attrtype.currentText().lower()]])

            # adding the sets
            self.add_set(obj_start, 'Obj attributes starting with')
            self.add_set(obj_contains, 'Obj attributes containing')
            self.add_set(shp_start, 'Shape attributes starting with')
            self.add_set(shp_contains, 'Shape attributes containing')

        else:
            self.add_set(obj_start, 'Object\'s attributes')
            self.add_set(shp_start, 'Shape\'s attributes')

        # and we select the first one if ever there is something in the list
        if self.WL_attributes.topLevelItemCount():
            self.WL_attributes.setItemSelected(self.WL_attributes.topLevelItem(1), True)
class LandmarkTransformationTool(TransformationTool):
	"""
	LandmarkTransformationTool
	"""
	updatedLandmarks = Signal(list)

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

		self.fixedPickerType = SurfaceType
		self.movingPickerType = SurfaceType

		self.fixedPicker = self._pickerForType(self.fixedPickerType)
		self.movingPicker = self._pickerForType(self.movingPickerType)

		self.landmarkPointSets = []  # Sets of points
		self.landmarkIndicators = []  # All the landmark indicator objects

		self.originalTransform = None
		self.originalScalingTransform = None

		self.activeIndex = 0
		self.landmarkTransformType = 0  # Rigid, Similarity or Affine

	@overrides(TransformationTool)
	def getParameterWidget(self):
		self.pointsWidget = PointsWidget()

		self.landmarkComboBox = QComboBox()
		self.landmarkComboBox.addItem("Rigid body")
		self.landmarkComboBox.addItem("Similarity")
		self.landmarkComboBox.addItem("Affine")

		layout = QGridLayout()
		layout.setAlignment(Qt.AlignTop)
		layout.setContentsMargins(0, 0, 0, 0)
		layout.addWidget(QLabel("Transform type:"), 0, 0)
		layout.addWidget(self.landmarkComboBox, 0, 1)
		layout.addWidget(self.pointsWidget, 1, 0, 1, 2)
		
		self.updatedLandmarks.connect(self.pointsWidget.setPoints)
		self.landmarkComboBox.currentIndexChanged.connect(self.landmarkTransformTypeChanged)
		self.pointsWidget.activeLandmarkChanged.connect(self.setActiveLandmark)
		self.pointsWidget.landmarkDeleted.connect(self.deleteLandmark)

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

	@overrides(TransformationTool)
	def setRenderWidgets(self, fixed=None, moving=None, multi=None):
		self.fixedWidget = fixed
		self.movingWidget = moving
		self.multiWidget = multi

		self.fixedPicker.setWidget(self.fixedWidget)
		self.movingPicker.setWidget(self.movingWidget)

		self.fixedPicker.pickedLocation.connect(self.pickedFixedLocation)
		self.movingPicker.pickedLocation.connect(self.pickedMovingLocation)

		# Save the original complete transform
		self.originalTransform = self.multiWidget.transformations.completeTransform()
		self.originalScalingTransform = self.multiWidget.transformations.scalingTransform()

		# Add a new transform on top of the others
		currentProject = ProjectController.Instance().currentProject
		transform = Transformation(vtkTransform(), Transformation.TypeLandmark, currentProject.movingData)
		self.multiWidget.transformations.append(transform)

		statusWidget = StatusWidget.Instance()
		statusWidget.setText("Place landmarks in both volumes to create a landmark transform. "
			"Available methods for placing landmarks are the surface type and the two-step type.")

	def setLandmarkWidgets(self, fixed, moving):
		self.fixedLandmarkWidget = fixed
		self.movingLandmarkWidget = moving

		self.fixedLandmarkWidget.landmarkTypeChanged.connect(self.landmarkToolTypeChanged)
		self.movingLandmarkWidget.landmarkTypeChanged.connect(self.landmarkToolTypeChanged)

		self.fixedPicker.setPropertiesWidget(self.fixedLandmarkWidget)
		self.movingPicker.setPropertiesWidget(self.movingLandmarkWidget)

	@overrides(TransformationTool)
	def cancelTransform(self):
		del self.multiWidget.transformations[-1]

	@overrides(TransformationTool)
	def applyTransform(self):
		# Add the landmark point sets to the transformation
		transformation = self.multiWidget.transformations[-1]
		transformation.landmarks = self.landmarkPointSets

	@overrides(TransformationTool)
	def cleanUp(self):
		self.fixedPicker.cleanUp()
		self.movingPicker.cleanUp()

		for landmarkIndicator in self.landmarkIndicators:
			landmarkIndicator.cleanUp()

		self.landmarkPointSets = []

		self.fixedWidget.render()
		self.movingWidget.render()
		self.multiWidget.render()

		self.fixedLandmarkWidget.setVisible(False)
		self.movingLandmarkWidget.setVisible(False)

		self.toolFinished.emit()

	@Slot(int)
	def setActiveLandmark(self, index):
		self.activeIndex = index
		self._update()

		if self.activeIndex < len(self.landmarkPointSets):
			landmarkSet = self.landmarkPointSets[self.activeIndex]
			self._focusCamera(self.fixedWidget, landmarkSet[0])
			self._focusCamera(self.movingWidget, landmarkSet[1])

		self.fixedWidget.render()
		self.movingWidget.render()
		self.multiWidget.render()

	@Slot(int)
	def deleteLandmark(self, index):
		if index < len(self.landmarkPointSets):
			del self.landmarkPointSets[index]
		indices = []
		for i in range(len(self.landmarkIndicators)):
			indicator = self.landmarkIndicators[i]
			if indicator.id == index:
				indicator.cleanUp()
				indices.append(i)

		indices.reverse()
		for i in indices:
			del self.landmarkIndicators[i]

		for indicator in self.landmarkIndicators:
			if indicator.id > index:
				indicator.id -= 1

		self.activeIndex = len(self.landmarkPointSets)
		self.pointsWidget.activeIndex = self.activeIndex
		# self.activeIndex = -1
		self._updateTransform()
		self._update()
		self.updatedLandmarks.emit(self.landmarkPointSets)

		self.fixedWidget.render()
		self.movingWidget.render()
		self.multiWidget.render()

	@Slot(int)
	def landmarkTransformTypeChanged(self, value):
		"""
		Called when the transformation type is changed
		from the combo box. Rigid, Similarity or Affine.
		"""
		if value == 2 and len(self.landmarkPointSets) < 3:
			self.landmarkComboBox.setCurrentIndex(self.landmarkTransformType)
			# TODO: let the user know that some more landmark point sets are needed...
			# Or: solve in another way by only calculating the affine transform when
			# there are actually 3 or more complete landmark point sets
			return
		self.landmarkTransformType = value
		self._updateTransform()
		self.multiWidget.render()

	@Slot(list)
	def pickedFixedLocation(self, location):
		"""
		Place spheres in fixed widget and in multi-widget.
		The input location should be in local data coordinates.
		"""
		self._pickedLocation(location, "fixed")

	@Slot(list)
	def pickedMovingLocation(self, location):
		"""
		Place spheres in moving widget and in multi-widget.
		The input location should be in local data coordinates.
		"""
		self._pickedLocation(location, "moving")

	@Slot(object)
	def landmarkToolTypeChanged(self, widget):
		if widget is self.fixedLandmarkWidget:
			self.fixedPickerType = widget.landmarkType
			self.fixedPicker.cleanUp()
			self.fixedPicker.pickedLocation.disconnect()
			self.fixedPicker = self._pickerForType(self.fixedPickerType)
			self.fixedPicker.setWidget(self.fixedWidget)
			self.fixedPicker.pickedLocation.connect(self.pickedFixedLocation)
			self.fixedPicker.setPropertiesWidget(self.fixedLandmarkWidget)
			if type(self.fixedPicker) == TwoStepPicker:
				self.fixedPicker.pickedLocation.connect(self.fixedLandmarkWidget.twoStepWidget.pickedLocation)
			self.fixedWidget.render()
		elif widget is self.movingLandmarkWidget:
			self.movingPickerType = widget.landmarkType
			self.movingPicker.cleanUp()
			self.movingPicker.pickedLocation.disconnect()
			self.movingPicker = self._pickerForType(self.movingPickerType)
			self.movingPicker.setWidget(self.movingWidget)
			self.movingPicker.pickedLocation.connect(self.pickedMovingLocation)
			self.movingPicker.setPropertiesWidget(self.movingLandmarkWidget)
			if type(self.movingPicker) == TwoStepPicker:
				self.movingPicker.pickedLocation.connect(self.movingLandmarkWidget.twoStepWidget.pickedLocation)
			self.movingWidget.render()

	# Private methods

	def _pickerForType(self, pickerType):
		"""
		Returns a picker object depending on the given picker type.
		"""
		if pickerType == SurfaceType:
			return SurfacePicker()
		elif pickerType == TwoStepType:
			return TwoStepPicker()

	def _pickedLocation(self, location, landmarkType):
		if self.activeIndex < len(self.landmarkPointSets):
			# Just update the landmark
			landmarks = [x for x in self.landmarkIndicators if (x.id == self.activeIndex and x.flag == landmarkType)]
			for landmark in landmarks:
				landmark.position = location

			index = 0 if landmarkType == "fixed" else 1
			if not self.landmarkPointSets[self.activeIndex][index]:
				# Add another landmark indicator if there was no landmark
				self._addLandmarkIndicator(location, landmarkType)

			self.landmarkPointSets[self.activeIndex][index] = location
		else:
			# Add the location to the landmark points as a set
			landmarkSet = [location, None] if (landmarkType == "fixed") else [None, location]
			self.landmarkPointSets.append(landmarkSet)
			self._addLandmarkIndicator(location, landmarkType)

		self._updateTransform()
		self._update()
		self.updatedLandmarks.emit(self.landmarkPointSets)
		self.multiWidget.render()
		self.movingWidget.render()

	def _updateTransform(self):
		"""
		Update the landmark transform
		"""
		if PointsSetsIsEmpty(self.landmarkPointSets):
			return

		numberOfSets = NumberOfSets(self.landmarkPointSets)
		fixedPoints = vtkPoints()
		movingPoints = vtkPoints()
		fixedPoints.SetNumberOfPoints(numberOfSets)
		movingPoints.SetNumberOfPoints(numberOfSets)

		pointsetIndex = 0
		for index in range(len(self.landmarkPointSets)):
			pointset = self.landmarkPointSets[index]
			if pointset[0] and pointset[1]:
				fixedPoint = pointset[0]
				movingPoint = pointset[1]
				# Transform the point from the moving landmark with the original transform
				transPoint = self.originalTransform.TransformPoint(movingPoint)
				fixedPoints.SetPoint(pointsetIndex, fixedPoint)
				movingPoints.SetPoint(pointsetIndex, transPoint)
				pointsetIndex += 1

		landmarkTransform = vtkLandmarkTransform()
		if self.landmarkTransformType == 0:
			landmarkTransform.SetModeToRigidBody()
		elif self.landmarkTransformType == 1:
			landmarkTransform.SetModeToSimilarity()
		elif self.landmarkTransformType == 2:
			landmarkTransform.SetModeToAffine()
		landmarkTransform.SetSourceLandmarks(fixedPoints)
		landmarkTransform.SetTargetLandmarks(movingPoints)
		landmarkTransform.Update()

		transform = TransformWithMatrix(landmarkTransform.GetMatrix())
		transform.Inverse()
		
		transformation = self.multiWidget.transformations[-1]
		assert transformation.transformType == Transformation.TypeLandmark
		transformation.transform = transform
		self.multiWidget.transformations[-1] = transformation
		self._updateLandmarkTransforms()

	def _update(self):
		for landmark in self.landmarkIndicators:
			landmark.active = landmark.id == self.activeIndex
			landmark.update()
		self._updateLandmarkTransforms()

	def _updateLandmarkTransforms(self):
		# Update the transforms
		for landmarkIndicator in self.landmarkIndicators:
			if landmarkIndicator.flag == "moving" and landmarkIndicator.renderer == self.movingWidget.renderer:
				# landmarkIndicator.transform = self.multiWidget.transformations.scalingTransform()
				# landmarkIndicator.update()
				pass
			elif landmarkIndicator.flag == "moving" and landmarkIndicator.renderer == self.multiWidget.renderer:
				landmarkIndicator.transform = self.multiWidget.transformations.completeTransform()
				landmarkIndicator.update()

	def _addLandmarkIndicator(self, location, landmarkType):
		imageData = self.fixedWidget.imageData if landmarkType == "fixed" else self.movingWidget.imageData
		bounds = imageData.GetBounds()
		sizes = [bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]]
		smallest = min(sizes)
		scale = smallest / 30.0

		# Create landmark for the correct widget
		widget = self.fixedWidget if landmarkType == "fixed" else self.movingWidget
		landmark = self._landmarkForWidget(widget, landmarkType)
		landmark.id = self.activeIndex
		landmark.position = location
		landmark.scale = scale

		# Create landmark for multi widget
		landmarkMulti = self._landmarkForWidget(self.multiWidget, landmarkType)
		landmarkMulti.id = self.activeIndex
		landmarkMulti.position = location
		landmarkMulti.scale = scale

		self.landmarkIndicators.append(landmark)
		self.landmarkIndicators.append(landmarkMulti)

	def _focusCamera(self, widget, location):
		if not location:
			return

		transform = TransformWithMatrix(widget.volume.GetMatrix())
		worldPoint = transform.TransformPoint(location)

		camera = widget.renderer.GetActiveCamera()
		camera.SetFocalPoint(worldPoint)

	def _landmarkForWidget(self, widget, landmarkType):
		return Landmark(index=self.activeIndex,
			renderer=widget.renderer,
			overlay=widget.rendererOverlay,
			flag=landmarkType)
コード例 #45
0
    def _init_widgets(self):

        layout = QGridLayout()

        row = 0

        # name

        name_label = QLabel(self)
        name_label.setText("Name")

        txt_name = QLineEdit(self)
        txt_name.setText(NameGenerator.random_name())
        self._name_edit = txt_name

        layout.addWidget(name_label, row, 0)
        layout.addWidget(txt_name, row, 1)
        row += 1

        # base state

        state_label = QLabel(self)
        state_label.setText('Base state')

        base_state_combo = QStateComboBox(self._workspace.instance.states,
                                          self)
        self._base_state_combo = base_state_combo

        layout.addWidget(state_label, row, 0)
        layout.addWidget(base_state_combo, row, 1)
        row += 1

        # mode

        mode_label = QLabel(self)
        mode_label.setText("Mode")

        mode_combo = QComboBox(self)
        mode_combo.addItem("Symbolic", "symbolic")
        mode_combo.addItem("Static", "static")
        mode_combo.addItem("Fast-path", "fastpath")
        self._mode_combo = mode_combo

        layout.addWidget(mode_label, row, 0)
        layout.addWidget(mode_combo, row, 1)
        row += 1

        # custom code

        code_label = QLabel(self)
        code_label.setText('Initialization code')

        self._editor = pyqode.core.api.CodeEdit()
        self._editor.modes.append(
            pyqode.core.modes.PygmentsSyntaxHighlighter(
                self._editor.document()))
        self._editor.modes.append(pyqode.core.modes.CaretLineHighlighterMode())

        self._editor.insertPlainText(self.INITIAL_INIT_CODE)

        layout.addWidget(code_label, row, 0)
        layout.addWidget(self._editor, row, 1)
        row += 1

        # buttons

        ok_button = QPushButton(self)
        ok_button.setText('OK')
        ok_button.clicked.connect(self._on_ok_clicked)
        self._ok_button = ok_button

        cancel_button = QPushButton(self)
        cancel_button.setText('Cancel')
        cancel_button.clicked.connect(self._on_cancel_clicked)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)

        self.main_layout.addLayout(layout)
        self.main_layout.addLayout(buttons_layout)
コード例 #46
0
class OptionSection(QWidget):
  """
  Collects options and returns proper representation when requested
  """
  def __init__(self, parent=None):
    super(OptionSection, self).__init__(parent)
    #create widgets
    label_buffer_size = QLabel("Buffer Size")
    self.spinbox_buffer_size = ValidatedSpinBox()
    self.spinbox_buffer_size.setSingleStep(10)
    self.spinbox_buffer_size.setMaximum(9999999)
    self.spinbox_buffer_size.setSuffix(" bytes")
    self.spinbox_buffer_size.setValue(55)
    label_timeout = QLabel("Timeout")
    self.spinbox_timeout = ValidatedSpinBox()
    self.spinbox_timeout.setMaximum(9999999)
    self.spinbox_timeout.setSuffix(" ms")
    self.spinbox_timeout.setSingleStep(100)
    self.spinbox_timeout.setValue(1000)
    label_delay = QLabel("Delay Between Packets")
    self.spinbox_delay = ValidatedSpinBox()
    self.spinbox_delay.setMaximum(9999999)
    self.spinbox_delay.setSuffix(" ms")
    self.spinbox_delay.setSingleStep(100)
    self.spinbox_delay.setValue(1000)
    label_delay_distribution = QLabel("Delay Distribution")
    self.combobox_delay_distribution = QComboBox()
    self.combobox_delay_distribution.addItem("Constant")
    self.combobox_delay_distribution.insertSeparator(10)
    self.combobox_delay_distribution.addItems(["Uniform", "Gaussian", "Poisson", "Exponential"])
    label_packet_count = QLabel("Packets to Send")
    self.spinbox_packet_count = ValidatedSpinBox()
    self.spinbox_packet_count.setMaximum(9999999)
    self.spinbox_packet_count.setValue(3)
    #setup layout
    layout = QFormLayout()
    layout.addRow(label_buffer_size, self.spinbox_buffer_size)
    layout.addRow(label_timeout, self.spinbox_timeout)
    layout.addRow(label_delay, self.spinbox_delay)
    layout.addRow(label_delay_distribution, self.combobox_delay_distribution)
    layout.addRow(label_packet_count, self.spinbox_packet_count)
    self.setLayout(layout)
    
  def getOptions(self):
    """
    Return a RequestData object representing selected options
    """
    buf_size = self.spinbox_buffer_size.value()
    timeout = self.spinbox_timeout.value()
    delay = self.spinbox_delay.value() / 1000
    packet_count = self.spinbox_packet_count.value()
    selected_distribution = self.combobox_delay_distribution.currentIndex()
    if selected_distribution == 0:
      distribution = RequestData.DISTRIBUTION_CONSTANT
    elif selected_distribution == 1:
      distribution = RequestData.DISTRIBUTION_UNIFORM
    elif selected_distribution == 2:
      distribution = RequestData.DISTRIBUTION_GAUSSIAN
    elif selected_distribution == 3:
      distribution = RequestData.DISTRIBUTION_POISSON
    elif selected_distribution == 4:
      distribution = RequestData.DISTRIBUTION_EXPONENTIAL
    
    return RequestData(buf_size, timeout, delay, packet_count, distribution)
  
  def disableWidgets(self):
    for widget in [self.spinbox_buffer_size, self.spinbox_delay,
                   self.spinbox_packet_count, self.spinbox_timeout, 
                   self.combobox_delay_distribution]:
      widget.setEnabled(False)
  
  def enableWidgets(self):
    for widget in [self.spinbox_buffer_size, self.spinbox_delay,
                   self.spinbox_packet_count, self.spinbox_timeout, 
                   self.combobox_delay_distribution]:
      widget.setEnabled(True)
コード例 #47
0
class GeometryWizardPage(_ExpandableOptionsWizardPage):

    def __init__(self, options, parent=None):
        _ExpandableOptionsWizardPage.__init__(self, options, parent)
        self.setTitle('Geometry')

    def _initUI(self):
        # Variables
        self._widgets = {}

        # Widgets
        self._cb_geometry = QComboBox()

        self._wdg_geometry = QStackedWidget()
        policy = self._wdg_geometry.sizePolicy()
        policy.setVerticalStretch(True)
        self._wdg_geometry.setSizePolicy(policy)

        # Layouts
        layout = _ExpandableOptionsWizardPage._initUI(self)
        layout.addRow("Type of geometry", self._cb_geometry)
        layout.addRow(self._wdg_geometry)

        # Signals
        self._cb_geometry.currentIndexChanged.connect(self._onGeometryChanged)
        self._cb_geometry.currentIndexChanged.connect(self.valueChanged)

        return layout

    def _onGeometryChanged(self):
        newindex = self._cb_geometry.currentIndex()
        oldwidget = self._wdg_geometry.currentWidget()
        newwidget = self._wdg_geometry.widget(newindex)
        if newwidget is None:
            return

        try:
            newwidget.setValue(oldwidget.value())
        except:
            newwidget.setValue(self.options().geometry)

        self._wdg_geometry.setCurrentIndex(newindex)

        # See https://qt-project.org/faq/answer/how_can_i_get_a_qstackedwidget_to_automatically_switch_size_depending_on_th
        oldwidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        newwidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self._wdg_geometry.adjustSize()

    def _find_material_class(self, programs):
        highest_class = Material

        for program in programs:
            converter = program.converter_class
            for clasz in converter.MATERIALS:
                if issubclass(clasz, highest_class):
                    highest_class = clasz

        return highest_class

    def initializePage(self):
        _ExpandableOptionsWizardPage.initializePage(self)

        # Clear
        self._widgets.clear()
        for i in reversed(range(self._cb_geometry.count())):
            self._cb_geometry.removeItem(i)
            self._wdg_geometry.removeWidget(self._wdg_geometry.widget(i))

        # Populate combo box
        it = self._iter_widgets('pymontecarlo.ui.gui.options.geometry',
                                'GEOMETRIES')
        for clasz, widget_class, programs in it:
            widget = widget_class()
            widget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
            widget.setMaterialClass(self._find_material_class(programs))

            self._widgets[clasz] = widget

            program_text = ', '.join(map(attrgetter('name'), programs))
            text = '{0} ({1})'.format(widget.accessibleName(), program_text)
            self._cb_geometry.addItem(text)
            self._wdg_geometry.addWidget(widget)

            widget.valueChanged.connect(self.valueChanged)

        # Select geometry
        geometry = self.options().geometry

        widget = self._widgets.get(geometry.__class__)
        if widget is None:
            widget = next(iter(self._widgets.values()))

        widget.setValue(geometry)
        self._wdg_geometry.setCurrentWidget(widget)
        self._cb_geometry.setCurrentIndex(self._wdg_geometry.currentIndex())

    def validatePage(self):
        if not self._wdg_geometry.currentWidget().hasAcceptableInput():
            return False

        self.options().geometry = self._wdg_geometry.currentWidget().value()

        return True

    def expandCount(self):
        try:
            return len(expand(self._wdg_geometry.currentWidget().value()))
        except:
            return 0
コード例 #48
0
ファイル: gui.py プロジェクト: Radymus/label-marker
class Ui_MainWindow(object):
    
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.FilterLbl = QLabel(self.centralwidget)
        self.FilterLbl.setGeometry(QtCore.QRect(30, 150, 60, 15))
        self.FilterLbl.setObjectName("FilterLbl")
        self.FilterCB = QComboBox(self.centralwidget)
        self.FilterCB.setGeometry(QtCore.QRect(450, 150, 100, 22))
        self.FilterCB.setObjectName("FilterCB")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")         
        self.FilterTF = QLineEdit(self.centralwidget)
        self.FilterTF.setGeometry(QtCore.QRect(100, 150, 320, 20))        
        self.tableView = QTableWidget(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 180, 781, 511))
        self.tableView.setObjectName("tableView")
        self.tableView.setColumnCount(4)
        self.tableView.setRowCount(0)
        item = QTableWidgetItem("Cena za kg/l")
        self.tableView.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem("Cena ze kus")
        self.tableView.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem(u"Gramaž")
        self.tableView.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem("Popis")
        item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(8)
        item.setFont(font)
        self.tableView.setHorizontalHeaderItem(3, item)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        
        self.SaveBtn = QPushButton(self.centralwidget)
        self.SaveBtn.setGeometry(QtCore.QRect(30, 10, 100, 23))
        self.SaveBtn.setObjectName("SaveBtn")
        self.PrintSelectedToFileBtn = QPushButton(self.centralwidget)
        self.PrintSelectedToFileBtn.setGeometry(QtCore.QRect(225, 10, 100, 23))        
        self.PrintSelectedToFileBtn.setObjectName("PrintSelectedToFileBtn")
        self.PriceForUnitTF = QLineEdit(self.centralwidget)
        self.PriceForUnitTF.setGeometry(QtCore.QRect(100, 70, 113, 20))
        self.PriceForUnitTF.setObjectName("PriceForUnitTF")
        self.PriceForUnitLbl = QLabel(self.centralwidget)
        self.PriceForUnitLbl.setGeometry(QtCore.QRect(30, 70, 60, 13))
        self.PriceForUnitLbl.setObjectName("PriceForUnitLbl")
        self.ArtikelTF = QLineEdit(self.centralwidget)
        self.ArtikelTF.setGeometry(QtCore.QRect(100, 100, 113, 20))
        self.ArtikelTF.setObjectName("ArtikelTF")
        self.ArtikelLbl = QLabel(self.centralwidget)
        self.ArtikelLbl.setGeometry(QtCore.QRect(30, 100, 46, 13))
        self.ArtikelLbl.setObjectName("ArtikelLbl")
        self.DescriptionLbl = QLabel(self.centralwidget)
        self.DescriptionLbl.setGeometry(QtCore.QRect(455, 70, 75, 13))
        self.DescriptionLbl.setObjectName("DescriptionLbl")
        self.UnitLbl = QLabel(self.centralwidget)
        self.UnitLbl.setGeometry(QtCore.QRect(250, 70, 60, 15))
        self.UnitLbl.setObjectName("UnitLbl")
        self.WeightLbl = QLabel(self.centralwidget)
        self.WeightLbl.setGeometry(QtCore.QRect(250, 100, 60, 13))
        self.WeightLbl.setObjectName("UnitLbl")
        self.WeightTF = QLineEdit(self.centralwidget)
        self.WeightTF.setGeometry(QtCore.QRect(320, 100, 100, 20))
        self.WeightTF.setObjectName("WeightTF")        
        self.UnitCB = QComboBox(self.centralwidget)
        self.UnitCB.setGeometry(QtCore.QRect(320, 70, 100, 22))
        self.UnitCB.setObjectName("UnitCB")
        self.UnitCB.addItem("")
        self.UnitCB.addItem("")
        self.DescriptionTE = QPlainTextEdit(self.centralwidget)
        self.DescriptionTE.setGeometry(QtCore.QRect(540, 30, 241, 61))
        self.DescriptionTE.setObjectName("DescriptionTE")
        self.PrintToFileBtn = QPushButton(self.centralwidget)
        self.PrintToFileBtn.setGeometry(QtCore.QRect(140, 10, 75, 23))
        self.PrintToFileBtn.setObjectName("PrintToFileBtn")
        self.AddRecordBtn = QPushButton(self.centralwidget)
        self.AddRecordBtn.setGeometry(QtCore.QRect(450, 100, 75, 23))
        self.AddRecordBtn.setObjectName("AddRecordBtn")        
        self.SaveChangeBtn = QPushButton(self.centralwidget)
        self.SaveChangeBtn.setGeometry(QtCore.QRect(550, 100, 75, 23))
        self.SaveChangeBtn.setObjectName("SaveChangeBtn")
        self.DeleteRecordBtn = QPushButton(self.centralwidget)
        self.DeleteRecordBtn.setGeometry(QtCore.QRect(650, 100, 75, 23))
        self.DeleteRecordBtn.setObjectName("DeleteRecordBtn")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
   
        self.FilterTF.textChanged.connect(self.on_lineEdit_textChanged)
        self.FilterCB.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def myFilter(self,col=None):
        filt = self.FilterTF.text()
        for ix in range(self.tableView.rowCount()):
            match = False
            if col == None:
                for jx in range(self.tableView.columnCount()):
                    item = self.tableView.item(ix,jx)
                    if filt in item.text():
                        match = True
                        break
                self.tableView.setRowHidden(ix, not match)
            else:
                item = self.tableView.item(ix, col)
                if filt in item.text():
                    match = True
                self.tableView.setRowHidden(ix, not match)

    #@QtCore.pyqtSlot(str)
    def on_lineEdit_textChanged(self, text):
        self.myFilter()

    #@QtCore.pyqtSlot(int)
    def on_comboBox_currentIndexChanged(self, index):
        self.myFilter(col=index)
        
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Stitky - {0}".format(__version__)))
        self.SaveBtn.setText(_translate("MainWindow", "Uloz stav tabulky"))
        self.PrintSelectedToFileBtn.setText(_translate("MainWindow", "Tisk vybranych"))
        self.PriceForUnitLbl.setText(_translate("MainWindow", "Cena za kus:"))
        self.ArtikelLbl.setText(_translate("MainWindow", "Artikl:"))
        self.DescriptionLbl.setText(_translate("MainWindow", "Popis produktu:"))
        self.UnitLbl.setText(_translate("MainWindow", "Jednotka:"))
        self.FilterLbl.setText(_translate("MainWindow", "Filtr:"))
        self.WeightLbl.setText(_translate("MainWindow", "Hmotnost:"))
        self.PrintToFileBtn.setText(_translate("MainWindow", "Vytvor txt"))
        self.SaveChangeBtn.setText(_translate("MainWindow", "Uloz zmeny"))
        self.AddRecordBtn.setText(_translate("MainWindow", "Pridej zaznam"))
        self.DeleteRecordBtn.setText(_translate("MainWindow", "Smaz zaznam"))
        self.UnitCB.setItemText(0, _translate("MainWindow", "g"))
        self.UnitCB.setItemText(1, _translate("MainWindow", "ml"))
        self.FilterCB.setItemText(0, _translate("MainWindow", "Cena za kg/l"))
        self.FilterCB.setItemText(1, _translate("MainWindow", "Cena ze kus"))
        self.FilterCB.setItemText(2, _translate("MainWindow", "Gramaz"))
        self.FilterCB.setItemText(3, _translate("MainWindow", "Popis"))
コード例 #49
0
class UiMain(QMainWindow):
    """ The main gui interface, invokes all windows and ties everything
     together
    """
    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()

        # self.update()
        CheckUpdateThread = Thread(target=self.update)
        CheckUpdateThread.setName('CheckUpdateThread')
        CheckUpdateThread.run()

    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>"""
            )
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(
            self.start_btn, SIGNAL("clicked()"),
            lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL("clicked()"),
                        self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off,
                        SIGNAL("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)"
        )
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
コード例 #50
0
class ExposureControl(QWidget):

    class Mode(Enum):
        AUTO = 1
        TV = 2
        AV = 4
        MANUAL = 8

        def __or__(self, other):
            return self.value | other.value

    def __init__(self, camera):
        super(ExposureControl, self).__init__()
        self.camera = camera
        self.initUI()

    def initUI(self):
        layout = QGridLayout()

        title = QLabel("Exposure")
        title.setAlignment(Qt.AlignCenter)
        layout.addWidget(title, 0, 0, 1, 4)

        btnAuto = OptionButton()
        btnAuto.setText("Full Auto")
        _safelyConnect(btnAuto.clicked, self.camera.setAutoExposure)
        btnAuto.setChecked(True)

        layout.addWidget(btnAuto, 1, 0)

        btnTV = OptionButton()
        btnTV.setText("Tv")
        _safelyConnect(btnTV.clicked, self.camera.setShutterPriority)

        layout.addWidget(btnTV, 1, 1)

        btnAV = OptionButton()
        btnAV.setText("Av")
        _safelyConnect(btnAV.clicked, self.camera.setAperturePriority)

        layout.addWidget(btnAV, 1, 2)

        btnManual = OptionButton()
        btnManual.setText("M")
        _safelyConnect(btnManual.clicked, self.camera.setManualExposure)

        layout.addWidget(btnManual, 1, 3)

        layout.addWidget(QLabel("Aperture"), 2, 0)

        self.aperture = QComboBox(self)
        for a in list(Aperture):
            self.aperture.addItem(a.label, userData=a)
        self.aperture.currentIndexChanged.connect(self.setAperture)
        self.aperture.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.aperture.setEnabled(False)

        layout.addWidget(self.aperture, 2, 1, 1, 3)

        layout.addWidget(QLabel("Shutter"), 3, 0)

        self.shutter = QComboBox(self)
        for s in list(Shutter):
            self.shutter.addItem(s.label, userData=s)
        self.shutter.currentIndexChanged.connect(self.setShutter)
        self.shutter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.shutter.setEnabled(False)

        layout.addWidget(self.shutter, 3, 1, 1, 3)

        layout.addWidget(QLabel("Gain"), 4, 0)

        self.gain = QComboBox(self)
        for g in list(Gain):
            self.gain.addItem(g.label, userData=g)
        self.gain.currentIndexChanged.connect(self.setGain)
        self.gain.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.gain.setEnabled(False)

        layout.addWidget(self.gain, 4, 1, 1, 3)

        self.exposureButtons = QButtonGroup()
        self.exposureButtons.addButton(btnAuto, self.Mode.AUTO.value)
        self.exposureButtons.addButton(btnTV, self.Mode.TV.value)
        self.exposureButtons.addButton(btnAV, self.Mode.AV.value)
        self.exposureButtons.addButton(btnManual, self.Mode.MANUAL.value)

        self.exposureButtons.buttonClicked.connect(self.onExposureMethodSelected)

        layout.setRowStretch(0, 0)
        layout.setRowStretch(1, 1)
        layout.setRowStretch(2, 1)
        layout.setRowStretch(3, 1)
        layout.setRowStretch(4, 1)

        self.setLayout(layout)

    def onExposureMethodSelected(self):
        checked = self.exposureButtons.checkedId()
        self.aperture.setEnabled(checked & (self.Mode.MANUAL | self.Mode.AV))
        self.shutter.setEnabled(checked & (self.Mode.MANUAL | self.Mode.TV))
        self.gain.setEnabled(checked & self.Mode.MANUAL.value)

    @handlePyroErrors
    def setAperture(self, idx):
        ap = self.aperture.itemData(idx)
        self.camera.setAperture(ap)

    @handlePyroErrors
    def setShutter(self, idx):
        sh = self.shutter.itemData(idx)
        self.camera.setShutter(sh)

    @handlePyroErrors
    def setGain(self, idx):
        g = self.gain.itemData(idx)
        self.camera.setGain(g)
コード例 #51
0
class Panel(QWidget):

    def __init__(self, state, config, parent):
        super().__init__(parent)
        self.state = state
        self.config = config
        self.form = parent
        self.createWidgets()
        self.layoutWidgets()


    def createWidgets(self):
        self.formatPanel = Widgets.FormatPanel.Panel(self.state, self)
        formatActions = self.formatPanel.formatActions

        self.seePrefixLabel = QLabel("Pref&ix")
        self.seePrefixTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 3, formatActions=formatActions)
        self.seePrefixLabel.setBuddy(self.seePrefixTextEdit)
        self.seePrefixTextEdit.setHtml(self.config.get(
                                       Gconf.Key.SubSeePrefix))
        self.form.tooltips.append((self.seePrefixTextEdit, """\
<p><b>See, Prefix</b></p>
<p>The text to separate a subentry's <i>see</i> cross-refs from the term
or pages that precede them.</p>{}""".format(BLANK_SPACE_HTML)))
        self.seeLabel = QLabel("T&ext")
        self.seeTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 10, formatActions=formatActions)
        self.seeLabel.setBuddy(self.seeTextEdit)
        self.seeTextEdit.setHtml(self.config.get(Gconf.Key.SubSee))
        self.form.tooltips.append((self.seeTextEdit, """\
<p><b>See, Text</b></p>
<p>The text to indicate a subentry's <i>see</i>
cross-ref(s).</p>{}""".format(BLANK_SPACE_HTML)))
        self.seeSepLabel = QLabel("Sepa&rator")
        self.seeSepTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 3, formatActions=formatActions)
        self.seeSepLabel.setBuddy(self.seeSepTextEdit)
        self.seeSepTextEdit.setHtml(self.config.get(
                                    Gconf.Key.SubSeeSeparator))
        self.form.tooltips.append((self.seeSepTextEdit, """\
<p><b>See, Separator</b></p>
<p>The text to separate each of a subentry's <i>see</i> cross-references if
there are more than one.</p>{}""".format(BLANK_SPACE_HTML)))
        self.seeSuffixLabel = QLabel("Su&ffix")
        self.seeSuffixTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 3, formatActions=formatActions)
        self.seeSuffixLabel.setBuddy(self.seeSuffixTextEdit)
        self.seeSuffixTextEdit.setHtml(self.config.get(
                                       Gconf.Key.SubSeeSuffix))
        self.form.tooltips.append((self.seeSuffixTextEdit, """\
<p><b>See, Suffix</b></p>
<p>The text to follow a subentry's <i>see</i>
cross-references</p>{}""".format(BLANK_SPACE_HTML)))

        self.seeAlsoPrefixLabel = QLabel("&Prefix")
        self.seeAlsoPrefixTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 3, formatActions=formatActions)
        self.seeAlsoPrefixLabel.setBuddy(self.seeAlsoPrefixTextEdit)
        self.seeAlsoPrefixTextEdit.setHtml(self.config.get(
                                           Gconf.Key.SubSeeAlsoPrefix))
        self.form.tooltips.append((self.seeAlsoPrefixTextEdit, """\
<p><b>See Also, Prefix</b></p>
<p>The text to separate a subentry's <i>see also</i> cross-refs from the
term or pages that precede them.</p>{}""".format(BLANK_SPACE_HTML)))
        self.seeAlsoLabel = QLabel("Te&xt")
        self.seeAlsoTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 10, formatActions=formatActions)
        self.seeAlsoLabel.setBuddy(self.seeAlsoTextEdit)
        self.seeAlsoTextEdit.setHtml(self.config.get(Gconf.Key.SubSeeAlso))
        self.form.tooltips.append((self.seeAlsoTextEdit, """\
<p><b>See Also, Text</b></p>
<p>The text to indicate a subentry's <i>see also</i>
cross-ref(s).</p>{}""".format(BLANK_SPACE_HTML)))
        self.seeAlsoSepLabel = QLabel("&Separator")
        self.seeAlsoSepTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 3, formatActions=formatActions)
        self.seeAlsoSepLabel.setBuddy(self.seeAlsoSepTextEdit)
        self.seeAlsoSepTextEdit.setHtml(self.config.get(
                                        Gconf.Key.SubSeeAlsoSeparator))
        self.form.tooltips.append((self.seeAlsoSepTextEdit, """\
<p><b>See Also, Separator</b></p>
<p>The text to separate each of a subentry's <i>see also</i>
cross-references if there are more than one.</p>{}""".format(
            BLANK_SPACE_HTML)))
        self.seeAlsoSuffixLabel = QLabel("S&uffix")
        self.seeAlsoSuffixTextEdit = Widgets.LineEdit.SpacesHtmlLineEdit(
            self.state, 3, formatActions=formatActions)
        self.seeAlsoSuffixLabel.setBuddy(self.seeAlsoSuffixTextEdit)
        self.seeAlsoSuffixTextEdit.setHtml(self.config.get(
                                           Gconf.Key.SubSeeAlsoSuffix))
        self.form.tooltips.append((self.seeAlsoSuffixTextEdit, """\
<p><b>See Also, Suffix</b></p>
<p>The text to follow a subentry's <i>see also</i>
cross-references</p>{}""".format(BLANK_SPACE_HTML)))
        self.seeAlsoPositionLabel = QLabel("P&osition")
        self.seeAlsoPositionComboBox = QComboBox()
        self.seeAlsoPositionLabel.setBuddy(self.seeAlsoPositionComboBox)
        seeAlsoPos = self.config.get(Gconf.Key.SubSeeAlsoPosition)
        index = -1
        for i, pos in enumerate(SeeAlsoPositionKind):
            self.seeAlsoPositionComboBox.addItem(pos.text, pos.value)
            if pos is seeAlsoPos:
                index = i
        self.seeAlsoPositionComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.seeAlsoPositionComboBox, """\
<p><b>Position</b></p>
<p>Where <i>see also</i> cross-references should appear in relation to the
subentry they belong to.</p>"""))

        self.formatPanel.state.editors = [
            self.seePrefixTextEdit, self.seeTextEdit,
            self.seeSepTextEdit, self.seeSuffixTextEdit,
            self.seeAlsoPrefixTextEdit, self.seeAlsoTextEdit,
            self.seeAlsoSepTextEdit, self.seeAlsoSuffixTextEdit]


    def layoutWidgets(self):
        layout = QVBoxLayout()
        hbox = QHBoxLayout()
        hbox.addStretch()
        hbox.addWidget(self.formatPanel)
        layout.addLayout(hbox)

        seeGroup = QGroupBox("See")
        form = QFormLayout()
        form.addRow(self.seeLabel, self.seeTextEdit)
        hbox = QHBoxLayout()
        hbox.addWidget(self.seePrefixTextEdit)
        hbox.addWidget(self.seeSepLabel)
        hbox.addWidget(self.seeSepTextEdit)
        hbox.addWidget(self.seeSuffixLabel)
        hbox.addWidget(self.seeSuffixTextEdit)
        form.addRow(self.seePrefixLabel, hbox)
        seeGroup.setLayout(form)
        layout.addWidget(seeGroup)

        alsoGroup = QGroupBox("See Also")
        form = QFormLayout()
        form.addRow(self.seeAlsoLabel, self.seeAlsoTextEdit)
        hbox = QHBoxLayout()
        hbox.addWidget(self.seeAlsoPrefixTextEdit)
        hbox.addWidget(self.seeAlsoSepLabel)
        hbox.addWidget(self.seeAlsoSepTextEdit)
        hbox.addWidget(self.seeAlsoSuffixLabel)
        hbox.addWidget(self.seeAlsoSuffixTextEdit)
        form.addRow(self.seeAlsoPrefixLabel, hbox)
        form.addRow(self.seeAlsoPositionLabel, self.seeAlsoPositionComboBox)
        alsoGroup.setLayout(form)
        layout.addWidget(alsoGroup)

        layout.addStretch(2)

        self.setLayout(layout)
コード例 #52
0
class AudioTest(QMainWindow):

    def __init__(self, filename=None):
        QMainWindow.__init__(self)
        self.pullTimer = QTimer(self)

        # Owned by layout
        self.modeButton = None
        self.suspendResumeButton = None
        self.deviceBox = None

        self.device = QAudioDeviceInfo.defaultOutputDevice()
        self.generator = None
        self.audioOutput = None
        self.output = None
        self.fmt = QAudioFormat()
        self.pullMode = False
        self.buf = QByteArray(BUFFER_SIZE, 0)
        self.dump = filename

        self.initializeWindow()
        self.initializeAudio()

    def initializeWindow(self):
        window = QWidget()
        layout = QVBoxLayout()

        self.deviceBox = QComboBox(self)
        for info in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.deviceBox.addItem(info.deviceName(), info)

        self.deviceBox.activated[int].connect(self.deviceChanged)
        layout.addWidget(self.deviceBox)

        self.modeButton = QPushButton(self)
        self.modeButton.setText(PUSH_MODE_LABEL)
        self.modeButton.clicked.connect(self.toggleMode)
        layout.addWidget(self.modeButton)

        self.suspendResumeButton = QPushButton(self)
        self.suspendResumeButton.setText(SUSPEND_LABEL)
        self.suspendResumeButton.clicked.connect(self.toggleSuspendResume)
        layout.addWidget(self.suspendResumeButton)

        window.setLayout(layout)
        self.setCentralWidget(window)
        window.show()

    def initializeAudio(self):
        self.pullTimer.timeout.connect(self.pullTimerExpired)

        self.pullMode = True

        self.fmt.setFrequency(DATA_FREQUENCY_HZ)
        self.fmt.setChannels(1)
        self.fmt.setSampleSize(16)
        self.fmt.setCodec('audio/pcm')
        self.fmt.setByteOrder(QAudioFormat.LittleEndian)
        self.fmt.setSampleType(QAudioFormat.SignedInt)

        info = QAudioDeviceInfo(QAudioDeviceInfo.defaultOutputDevice())
        if not info.isFormatSupported(self.fmt):
            print 'Default format not supported - trying to use nearest'
            self.fmt = info.nearestFormat(self.fmt)

        self.generator = Generator(self.fmt, DURATION_SECONDS * 1000000,
                                   TONE_FREQUENCY_HZ, self, self.dump)

        self.createAudioOutput()

    def createAudioOutput(self):
        self.audioOutput = QAudioOutput(self.device, self.fmt, self)
        self.audioOutput.notify.connect(self.notified)
        self.audioOutput.stateChanged.connect(self.stateChanged)
        self.generator.start()
        self.audioOutput.start(self.generator)

    # Slots
    def notified(self):
        print 'Bytes free %d, elapsed usecs %d, processed usecs %d' % (
                self.audioOutput.bytesFree(),
                self.audioOutput.elapsedUSecs(),
                self.audioOutput.processedUSecs())

    def pullTimerExpired(self):
        if self.audioOutput.state() != QAudio.StoppedState:
            chunks = self.audioOutput.bytesFree() / self.audioOutput.periodSize()
            while chunks:
                data = self.generator.read(self.audioOutput.periodSize())
                self.output.write(data)
                if len(data) != self.audioOutput.periodSize():
                    break
                chunks -= 1

    def toggleMode(self):
        self.pullTimer.stop()
        self.audioOutput.stop()

        if self.pullMode:
            self.modeButton.setText(PULL_MODE_LABEL)
            self.output = self.audioOutput.start()
            self.pullMode = False
            self.pullTimer.start(5)
        else:
            self.modeButton.setText(PUSH_MODE_LABEL)
            self.pullMode = True
            self.audioOutput.start(self.generator)

        self.suspendResumeButton.setText(SUSPEND_LABEL)

    def toggleSuspendResume(self):
        if self.audioOutput.state() == QAudio.SuspendedState:
            print 'Status: Suspended, resuming'
            self.audioOutput.resume()
            self.suspendResumeButton.setText(SUSPEND_LABEL)
        elif self.audioOutput.state() == QAudio.ActiveState:
            print 'Status: Active, suspending'
            self.audioOutput.suspend()
            self.suspendResumeButton.setText(RESUME_LABEL)
        elif self.audioOutput.state() == QAudio.StoppedState:
            print 'Status: Stopped, resuming'
            self.audioOutput.resume()
            self.suspendResumeButton.setText(SUSPEND_LABEL)
        elif self.audioOutput.state() == QAudio.IdleState:
            print 'Status: Idle'

    def stateChanged(self, state):
        print 'State changed: ', state

    def deviceChanged(self, index):
        self.pullTimer.stop()
        self.generator.stop()
        self.audioOutput.stop()
        self.audioOutput.disconnect(self)
        self.device = self.deviceBox.itemData(index)
        self.createAudioOutput()
コード例 #53
0
class LandmarkTransformationTool(TransformationTool):
    """
	LandmarkTransformationTool
	"""
    updatedLandmarks = Signal(list)

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

        self.fixedPickerType = SurfaceType
        self.movingPickerType = SurfaceType

        self.fixedPicker = self._pickerForType(self.fixedPickerType)
        self.movingPicker = self._pickerForType(self.movingPickerType)

        self.landmarkPointSets = []  # Sets of points
        self.landmarkIndicators = []  # All the landmark indicator objects

        self.originalTransform = None
        self.originalScalingTransform = None

        self.activeIndex = 0
        self.landmarkTransformType = 0  # Rigid, Similarity or Affine

    @overrides(TransformationTool)
    def getParameterWidget(self):
        self.pointsWidget = PointsWidget()

        self.landmarkComboBox = QComboBox()
        self.landmarkComboBox.addItem("Rigid body")
        self.landmarkComboBox.addItem("Similarity")
        self.landmarkComboBox.addItem("Affine")

        layout = QGridLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(QLabel("Transform type:"), 0, 0)
        layout.addWidget(self.landmarkComboBox, 0, 1)
        layout.addWidget(self.pointsWidget, 1, 0, 1, 2)

        self.updatedLandmarks.connect(self.pointsWidget.setPoints)
        self.landmarkComboBox.currentIndexChanged.connect(
            self.landmarkTransformTypeChanged)
        self.pointsWidget.activeLandmarkChanged.connect(self.setActiveLandmark)
        self.pointsWidget.landmarkDeleted.connect(self.deleteLandmark)

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

    @overrides(TransformationTool)
    def setRenderWidgets(self, fixed=None, moving=None, multi=None):
        self.fixedWidget = fixed
        self.movingWidget = moving
        self.multiWidget = multi

        self.fixedPicker.setWidget(self.fixedWidget)
        self.movingPicker.setWidget(self.movingWidget)

        self.fixedPicker.pickedLocation.connect(self.pickedFixedLocation)
        self.movingPicker.pickedLocation.connect(self.pickedMovingLocation)

        # Save the original complete transform
        self.originalTransform = self.multiWidget.transformations.completeTransform(
        )
        self.originalScalingTransform = self.multiWidget.transformations.scalingTransform(
        )

        # Add a new transform on top of the others
        currentProject = ProjectController.Instance().currentProject
        transform = Transformation(vtkTransform(), Transformation.TypeLandmark,
                                   currentProject.movingData)
        self.multiWidget.transformations.append(transform)

        statusWidget = StatusWidget.Instance()
        statusWidget.setText(
            "Place landmarks in both volumes to create a landmark transform. "
            "Available methods for placing landmarks are the surface type and the two-step type."
        )

    def setLandmarkWidgets(self, fixed, moving):
        self.fixedLandmarkWidget = fixed
        self.movingLandmarkWidget = moving

        self.fixedLandmarkWidget.landmarkTypeChanged.connect(
            self.landmarkToolTypeChanged)
        self.movingLandmarkWidget.landmarkTypeChanged.connect(
            self.landmarkToolTypeChanged)

        self.fixedPicker.setPropertiesWidget(self.fixedLandmarkWidget)
        self.movingPicker.setPropertiesWidget(self.movingLandmarkWidget)

    @overrides(TransformationTool)
    def cancelTransform(self):
        del self.multiWidget.transformations[-1]

    @overrides(TransformationTool)
    def applyTransform(self):
        # Add the landmark point sets to the transformation
        transformation = self.multiWidget.transformations[-1]
        transformation.landmarks = self.landmarkPointSets

    @overrides(TransformationTool)
    def cleanUp(self):
        self.fixedPicker.cleanUp()
        self.movingPicker.cleanUp()

        for landmarkIndicator in self.landmarkIndicators:
            landmarkIndicator.cleanUp()

        self.landmarkPointSets = []

        self.fixedWidget.render()
        self.movingWidget.render()
        self.multiWidget.render()

        self.fixedLandmarkWidget.setVisible(False)
        self.movingLandmarkWidget.setVisible(False)

        self.toolFinished.emit()

    @Slot(int)
    def setActiveLandmark(self, index):
        self.activeIndex = index
        self._update()

        if self.activeIndex < len(self.landmarkPointSets):
            landmarkSet = self.landmarkPointSets[self.activeIndex]
            self._focusCamera(self.fixedWidget, landmarkSet[0])
            self._focusCamera(self.movingWidget, landmarkSet[1])

        self.fixedWidget.render()
        self.movingWidget.render()
        self.multiWidget.render()

    @Slot(int)
    def deleteLandmark(self, index):
        if index < len(self.landmarkPointSets):
            del self.landmarkPointSets[index]
        indices = []
        for i in range(len(self.landmarkIndicators)):
            indicator = self.landmarkIndicators[i]
            if indicator.id == index:
                indicator.cleanUp()
                indices.append(i)

        indices.reverse()
        for i in indices:
            del self.landmarkIndicators[i]

        for indicator in self.landmarkIndicators:
            if indicator.id > index:
                indicator.id -= 1

        self.activeIndex = len(self.landmarkPointSets)
        self.pointsWidget.activeIndex = self.activeIndex
        # self.activeIndex = -1
        self._updateTransform()
        self._update()
        self.updatedLandmarks.emit(self.landmarkPointSets)

        self.fixedWidget.render()
        self.movingWidget.render()
        self.multiWidget.render()

    @Slot(int)
    def landmarkTransformTypeChanged(self, value):
        """
		Called when the transformation type is changed
		from the combo box. Rigid, Similarity or Affine.
		"""
        if value == 2 and len(self.landmarkPointSets) < 3:
            self.landmarkComboBox.setCurrentIndex(self.landmarkTransformType)
            # TODO: let the user know that some more landmark point sets are needed...
            # Or: solve in another way by only calculating the affine transform when
            # there are actually 3 or more complete landmark point sets
            return
        self.landmarkTransformType = value
        self._updateTransform()
        self.multiWidget.render()

    @Slot(list)
    def pickedFixedLocation(self, location):
        """
		Place spheres in fixed widget and in multi-widget.
		The input location should be in local data coordinates.
		"""
        self._pickedLocation(location, "fixed")

    @Slot(list)
    def pickedMovingLocation(self, location):
        """
		Place spheres in moving widget and in multi-widget.
		The input location should be in local data coordinates.
		"""
        self._pickedLocation(location, "moving")

    @Slot(object)
    def landmarkToolTypeChanged(self, widget):
        if widget is self.fixedLandmarkWidget:
            self.fixedPickerType = widget.landmarkType
            self.fixedPicker.cleanUp()
            self.fixedPicker.pickedLocation.disconnect()
            self.fixedPicker = self._pickerForType(self.fixedPickerType)
            self.fixedPicker.setWidget(self.fixedWidget)
            self.fixedPicker.pickedLocation.connect(self.pickedFixedLocation)
            self.fixedPicker.setPropertiesWidget(self.fixedLandmarkWidget)
            if type(self.fixedPicker) == TwoStepPicker:
                self.fixedPicker.pickedLocation.connect(
                    self.fixedLandmarkWidget.twoStepWidget.pickedLocation)
            self.fixedWidget.render()
        elif widget is self.movingLandmarkWidget:
            self.movingPickerType = widget.landmarkType
            self.movingPicker.cleanUp()
            self.movingPicker.pickedLocation.disconnect()
            self.movingPicker = self._pickerForType(self.movingPickerType)
            self.movingPicker.setWidget(self.movingWidget)
            self.movingPicker.pickedLocation.connect(self.pickedMovingLocation)
            self.movingPicker.setPropertiesWidget(self.movingLandmarkWidget)
            if type(self.movingPicker) == TwoStepPicker:
                self.movingPicker.pickedLocation.connect(
                    self.movingLandmarkWidget.twoStepWidget.pickedLocation)
            self.movingWidget.render()

    # Private methods

    def _pickerForType(self, pickerType):
        """
		Returns a picker object depending on the given picker type.
		"""
        if pickerType == SurfaceType:
            return SurfacePicker()
        elif pickerType == TwoStepType:
            return TwoStepPicker()

    def _pickedLocation(self, location, landmarkType):
        if self.activeIndex < len(self.landmarkPointSets):
            # Just update the landmark
            landmarks = [
                x for x in self.landmarkIndicators
                if (x.id == self.activeIndex and x.flag == landmarkType)
            ]
            for landmark in landmarks:
                landmark.position = location

            index = 0 if landmarkType == "fixed" else 1
            if not self.landmarkPointSets[self.activeIndex][index]:
                # Add another landmark indicator if there was no landmark
                self._addLandmarkIndicator(location, landmarkType)

            self.landmarkPointSets[self.activeIndex][index] = location
        else:
            # Add the location to the landmark points as a set
            landmarkSet = [location, None] if (
                landmarkType == "fixed") else [None, location]
            self.landmarkPointSets.append(landmarkSet)
            self._addLandmarkIndicator(location, landmarkType)

        self._updateTransform()
        self._update()
        self.updatedLandmarks.emit(self.landmarkPointSets)
        self.multiWidget.render()
        self.movingWidget.render()

    def _updateTransform(self):
        """
		Update the landmark transform
		"""
        if PointsSetsIsEmpty(self.landmarkPointSets):
            return

        numberOfSets = NumberOfSets(self.landmarkPointSets)
        fixedPoints = vtkPoints()
        movingPoints = vtkPoints()
        fixedPoints.SetNumberOfPoints(numberOfSets)
        movingPoints.SetNumberOfPoints(numberOfSets)

        pointsetIndex = 0
        for index in range(len(self.landmarkPointSets)):
            pointset = self.landmarkPointSets[index]
            if pointset[0] and pointset[1]:
                fixedPoint = pointset[0]
                movingPoint = pointset[1]
                # Transform the point from the moving landmark with the original transform
                transPoint = self.originalTransform.TransformPoint(movingPoint)
                fixedPoints.SetPoint(pointsetIndex, fixedPoint)
                movingPoints.SetPoint(pointsetIndex, transPoint)
                pointsetIndex += 1

        landmarkTransform = vtkLandmarkTransform()
        if self.landmarkTransformType == 0:
            landmarkTransform.SetModeToRigidBody()
        elif self.landmarkTransformType == 1:
            landmarkTransform.SetModeToSimilarity()
        elif self.landmarkTransformType == 2:
            landmarkTransform.SetModeToAffine()
        landmarkTransform.SetSourceLandmarks(fixedPoints)
        landmarkTransform.SetTargetLandmarks(movingPoints)
        landmarkTransform.Update()

        transform = TransformWithMatrix(landmarkTransform.GetMatrix())
        transform.Inverse()

        transformation = self.multiWidget.transformations[-1]
        assert transformation.transformType == Transformation.TypeLandmark
        transformation.transform = transform
        self.multiWidget.transformations[-1] = transformation
        self._updateLandmarkTransforms()

    def _update(self):
        for landmark in self.landmarkIndicators:
            landmark.active = landmark.id == self.activeIndex
            landmark.update()
        self._updateLandmarkTransforms()

    def _updateLandmarkTransforms(self):
        # Update the transforms
        for landmarkIndicator in self.landmarkIndicators:
            if landmarkIndicator.flag == "moving" and landmarkIndicator.renderer == self.movingWidget.renderer:
                # landmarkIndicator.transform = self.multiWidget.transformations.scalingTransform()
                # landmarkIndicator.update()
                pass
            elif landmarkIndicator.flag == "moving" and landmarkIndicator.renderer == self.multiWidget.renderer:
                landmarkIndicator.transform = self.multiWidget.transformations.completeTransform(
                )
                landmarkIndicator.update()

    def _addLandmarkIndicator(self, location, landmarkType):
        imageData = self.fixedWidget.imageData if landmarkType == "fixed" else self.movingWidget.imageData
        bounds = imageData.GetBounds()
        sizes = [
            bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]
        ]
        smallest = min(sizes)
        scale = smallest / 30.0

        # Create landmark for the correct widget
        widget = self.fixedWidget if landmarkType == "fixed" else self.movingWidget
        landmark = self._landmarkForWidget(widget, landmarkType)
        landmark.id = self.activeIndex
        landmark.position = location
        landmark.scale = scale

        # Create landmark for multi widget
        landmarkMulti = self._landmarkForWidget(self.multiWidget, landmarkType)
        landmarkMulti.id = self.activeIndex
        landmarkMulti.position = location
        landmarkMulti.scale = scale

        self.landmarkIndicators.append(landmark)
        self.landmarkIndicators.append(landmarkMulti)

    def _focusCamera(self, widget, location):
        if not location:
            return

        transform = TransformWithMatrix(widget.volume.GetMatrix())
        worldPoint = transform.TransformPoint(location)

        camera = widget.renderer.GetActiveCamera()
        camera.SetFocalPoint(worldPoint)

    def _landmarkForWidget(self, widget, landmarkType):
        return Landmark(index=self.activeIndex,
                        renderer=widget.renderer,
                        overlay=widget.rendererOverlay,
                        flag=landmarkType)
コード例 #54
0
class MovementEditor(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setGeometry(QRect(100, 100, 400, 200))
        self.layout = QtGui.QGridLayout(self)
        #lblAssetType
        self.lblAssetType = QLabel("Asset Type")
        self.layout.addWidget(self.lblAssetType, 0, 0)
        #cmdAssetType
        self.cmdAssetType = QComboBox(self)
        self.cmdAssetType.addItems(DaoAsset().getAssetTypes())
        self.layout.addWidget(self.cmdAssetType, 0, 1)
        #lblAssetName
        self.lblAssetName = QLabel("Asset Name")
        self.layout.addWidget(self.lblAssetName, 1, 0)
        #cmdAssetName
        self.cmdAssetName = QComboBox(self)
        self.layout.addWidget(self.cmdAssetName, 1, 1)
        #lblCustody
        self.lblCustody = QLabel("Custody")
        self.layout.addWidget(self.lblCustody, 2, 0)
        #cmbCustody
        self.cmbCustody = QComboBox(self)
        custodyList = DaoCustody().getCustodyList()
        for (row) in custodyList:
            self.cmbCustody.addItem(row[1], row[0])
        self.layout.addWidget(self.cmbCustody, 2, 1)
        #lblBuySell
        self.lblBuySell = QLabel("Buy Sell")
        self.layout.addWidget(self.lblBuySell, 3, 0)
        #cmdBuySell
        self.cmdBuySell = QComboBox(self)
        self.cmdBuySell.addItem("BUY")
        self.cmdBuySell.addItem("SELL")
        self.layout.addWidget(self.cmdBuySell, 3, 1)
        #lblByAmount
        self.lblByAmount = QLabel("By Amount")
        self.layout.addWidget(self.lblByAmount, 4, 0)
        #chkByAmount
        self.chkByAmount = QCheckBox(self)
        self.layout.addWidget(self.chkByAmount, 4, 1)
        #lblGrossAmount
        self.lblGrossAmount = QLabel("Gross Amount")
        self.layout.addWidget(self.lblGrossAmount, 5, 0)
        #txtGrossAmount
        self.txtGrossAmount = QLineEdit(self)
        self.txtGrossAmount.setValidator(QDoubleValidator(
            0, 99999999, 6, self))
        self.layout.addWidget(self.txtGrossAmount, 5, 1)
        #lblAcquisitionDate
        self.lblAcquisitionDate = QLabel("Acquisition Date")
        self.layout.addWidget(self.lblAcquisitionDate, 6, 0)
        #cmdAcquisitionDate
        self.dateAcquisitionDate = QDateEdit(self)
        self.dateAcquisitionDate.setDisplayFormat("dd-MM-yyyy")
        self.dateAcquisitionDate.setDate(datetime.datetime.now())
        self.layout.addWidget(self.dateAcquisitionDate, 6, 1)
        #lblQuantity
        self.lblQuantity = QLabel("Quantity")
        self.layout.addWidget(self.lblQuantity, 7, 0)
        #txtQuantity
        self.txtQuantity = QLineEdit(self)
        self.txtQuantity.setValidator(QIntValidator(0, 1000000000, self))
        self.layout.addWidget(self.txtQuantity, 7, 1)
        #lblPrice
        self.lblPrice = QLabel("Price")
        self.layout.addWidget(self.lblPrice, 8, 0)
        #txtPrice
        self.txtPrice = QLineEdit(self)
        self.txtPrice.setValidator(QDoubleValidator(0, 99999999, 6, self))
        self.layout.addWidget(self.txtPrice, 8, 1)
        #lblRate
        self.lblRate = QLabel("Rate")
        self.layout.addWidget(self.lblRate, 9, 0)
        #txtRate
        self.txtRate = QLineEdit(self)
        self.txtRate.setValidator(QDoubleValidator(0, 99999999, 4, self))
        self.txtRate.setEnabled(0)
        self.layout.addWidget(self.txtRate, 9, 1)
        #lblNetAmount
        self.lblNetAmount = QLabel("Net Amount")
        self.layout.addWidget(self.lblNetAmount, 10, 0)
        #txtNetAmount
        self.txtNetAmount = QLineEdit(self)
        self.txtNetAmount.setEnabled(0)
        self.txtNetAmount.setValidator(QDoubleValidator(0, 99999999, 6, self))
        self.layout.addWidget(self.txtNetAmount, 10, 1)
        #lblCommissionPercentage
        self.lblCommissionPercentage = QLabel("Commission Percentage")
        self.layout.addWidget(self.lblCommissionPercentage, 11, 0)
        #txtCommissionPercentage
        self.txtCommissionPercentage = QLineEdit(self)
        self.txtCommissionPercentage.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionPercentage, 11, 1)
        #lblCommissionAmount
        self.lblCommissionAmount = QLabel("Commission Amount")
        self.layout.addWidget(self.lblCommissionAmount, 12, 0)
        #txtCommissionAmmount
        self.txtCommissionAmount = QLineEdit(self)
        self.txtCommissionAmount.setEnabled(0)
        self.txtCommissionAmount.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionAmount, 12, 1)
        #lblCommissionAmount
        self.lblCommissionVATAmount = QLabel("Commission VAT Amount")
        self.layout.addWidget(self.lblCommissionVATAmount, 13, 0)
        #txtCommissionAmmount
        self.txtCommissionVATAmount = QLineEdit(self)
        self.txtCommissionVATAmount.setEnabled(0)
        self.txtCommissionVATAmount.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionVATAmount, 13, 1)
        #lblTenor
        self.lblTenor = QLabel("Tenor")
        self.layout.addWidget(self.lblTenor, 14, 0)
        #txtTenor
        self.txtTenor = QLineEdit(self)
        self.txtTenor.setEnabled(0)
        self.txtTenor.setValidator(QDoubleValidator(0, 9999999, 0, self))
        self.layout.addWidget(self.txtTenor, 14, 1)
        #btnAdd
        self.btnAdd = QPushButton("Add", self)
        self.layout.addWidget(self.btnAdd)
        #btnClear
        self.btnClear = QPushButton("Clear", self)
        self.layout.addWidget(self.btnClear)
        #clearEditor
        self.clearEditor()
        self.initListener()

    def initListener(self):
        self.cmdBuySell.connect(
            self.cmdBuySell,
            QtCore.SIGNAL("currentIndexChanged(const QString&)"),
            self.calculateNetAmount)
        self.chkByAmount.connect(self.chkByAmount,
                                 QtCore.SIGNAL("stateChanged(int)"),
                                 self.configEditorByAmount)
        self.txtGrossAmount.connect(self.txtGrossAmount,
                                    SIGNAL("editingFinished()"),
                                    self.calculatePrice)
        self.cmdAssetType.connect(
            self.cmdAssetType,
            QtCore.SIGNAL("currentIndexChanged(const QString&)"),
            self.configEditorByAssetType)
        self.txtQuantity.connect(self.txtQuantity,
                                 SIGNAL("textChanged(QString)"),
                                 self.calculateGrossAmount)
        self.txtQuantity.connect(self.txtQuantity,
                                 SIGNAL("textChanged(QString)"),
                                 self.calculatePrice)
        self.txtPrice.connect(self.txtPrice, SIGNAL("textChanged(QString)"),
                              self.calculateGrossAmount)
        self.cmdAssetName.connect(
            self.cmdAssetName, SIGNAL("currentIndexChanged(const QString&)"),
            self.setDefaultCustody)
        self.txtCommissionPercentage.connect(self.txtCommissionPercentage,
                                             SIGNAL("textChanged(QString)"),
                                             self.calculateCommission)
        self.btnAdd.clicked.connect(self.addMovement)
        self.btnClear.clicked.connect(self.clearEditor)

    def addMovement(self):
        buySell = self.cmdBuySell.currentText()
        assetOID = self.cmdAssetName.itemData(self.cmdAssetName.currentIndex())
        custodyOID = self.cmbCustody.itemData(self.cmbCustody.currentIndex())
        acquisitionDate = self.dateAcquisitionDate.date()
        quantity = self.txtQuantity.text()
        if self.cmdAssetType.currentText() == 'BOND':
            rate = self.txtRate.text()
            if self.txtTenor.text() == '':
                tenor = None
            else:
                tenor = self.txtTenor.text()
            maturityDate = acquisitionDate.toPython() + datetime.timedelta(
                days=int(tenor))
        else:
            rate = None
            maturityDate = None
            tenor = None
        price = self.txtPrice.text()
        grossAmount = self.txtGrossAmount.text()
        netAmount = self.txtNetAmount.text()
        commissionPercentage = self.txtCommissionPercentage.text()
        commissionAmount = self.txtCommissionAmount.text()
        commissionVATAmount = self.txtCommissionVATAmount.text()

        movement = Movement(None)
        movement.setAttr(None, assetOID, buySell, (acquisitionDate).toPython(),
                         quantity, price, rate, grossAmount, netAmount,
                         commissionPercentage, commissionAmount,
                         commissionVATAmount, tenor, custodyOID, maturityDate,
                         None, None)
        DaoMovement.insertMovement(movement)
        self.clearEditor()

    def clearEditor(self):
        #self.cmdAssetType.set
        self.txtQuantity.setText(None)
        self.txtPrice.setText(None)
        self.txtGrossAmount.setText("0")
        self.txtNetAmount.setText("0")
        self.txtRate.setText("0")
        #configDefaultCommission
        if self.cmdAssetType.currentText() == 'EQUITY':
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_EQUITY_COMMISSION_PERCENTAGE))
        else:
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_OTHER_COMMISSION_PERCENTAGE))
        self.txtTenor.setText("")
        self.dateAcquisitionDate.setDate(datetime.datetime.now())
        self.configEditorByAmount()
        self.configEditorByAssetType()

    def setDefaultCustody(self):
        defaultCustodyID = DaoCustody().getDefaultCustody(
            self.cmdAssetName.currentText())
        for (row) in defaultCustodyID:
            self.cmbCustody.setCurrentIndex(self.cmbCustody.findData(row[0]))

    def configEditorByAssetType(self):
        self.cmdAssetName.clear()
        #loadAssetNames
        assetNameList = DaoAsset().getAssetNames(
            self.cmdAssetType.currentText())
        for (assetName) in assetNameList:
            self.cmdAssetName.addItem(assetName[1], assetName[0])
        #setPriceOrRate
        if self.cmdAssetType.currentText(
        ) == 'EQUITY' or self.cmdAssetType.currentText() == 'FUND':
            self.txtPrice.setEnabled(1)
            self.txtRate.setEnabled(0)
            self.txtRate.setText("0")
            self.txtTenor.setEnabled(0)
            self.txtTenor.setText(None)
        else:
            self.txtPrice.setEnabled(0)
            self.txtRate.setEnabled(1)
            self.txtPrice.setText("0")
            self.txtTenor.setEnabled(1)
            self.txtTenor.setText(None)
        #configDefaultCommission
        if self.cmdAssetType.currentText() == 'EQUITY':
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_EQUITY_COMMISSION_PERCENTAGE))
        else:
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_OTHER_COMMISSION_PERCENTAGE))

    def configEditorByAmount(self):
        if self.chkByAmount.isChecked():
            self.txtPrice.setEnabled(0)
            self.txtGrossAmount.setEnabled(1)
        else:
            self.txtPrice.setEnabled(1)
            self.txtGrossAmount.setEnabled(0)

    def calculateCommission(self):
        commissionPercentage = self.txtCommissionPercentage.text()
        grossAmount = self.txtGrossAmount.text()
        if commissionPercentage >= 0:
            commissionAmount = float(grossAmount) * float(commissionPercentage)
            self.txtCommissionAmount.setText(
                str('{0:.6f}'.format(commissionAmount)))
            commissionVATAmount = commissionAmount * Constant.CONST_IVA_PERCENTAGE
            self.txtCommissionVATAmount.setText(
                str('{0:.6f}'.format(commissionVATAmount)))
            self.calculateNetAmount()

    def calculatePrice(self):
        quantity = self.txtQuantity.text()
        amount = self.txtGrossAmount.text()
        if (quantity is not u"" or None) and (amount is not u"" or None):
            self.txtPrice.setText(
                str('{0:.6f}'.format(float(amount) / float(quantity))))

    def calculateNetAmount(self):
        buySell = self.cmdBuySell.currentText()
        grossAmount = float(self.txtGrossAmount.text())
        commissionAmount = float(self.txtCommissionAmount.text())
        commissionVATAmount = float(self.txtCommissionVATAmount.text())
        if buySell == 'BUY':
            netAmount = grossAmount + commissionVATAmount + commissionAmount
        else:
            netAmount = grossAmount - commissionVATAmount - commissionAmount
        self.txtNetAmount.setText(str(netAmount))

    def calculateGrossAmount(self):
        quantity = self.txtQuantity.text()
        price = self.txtPrice.text()
        if (not self.chkByAmount.isChecked()) and (
                quantity is not u"" or None) and (price is not u"" or None):
            self.txtGrossAmount.setText(
                str('{0:.6f}'.format(float(quantity) * float(price))))
        self.calculateCommission()
コード例 #55
0
    def __init__(self, *args, **kwargs):

        QMainWindow.__init__(self, *args, **kwargs)
        self.installEventFilter(self)
        self.setWindowTitle(Window_global.title)

        mainWidget = QWidget()
        self.setCentralWidget(mainWidget)

        vLayout = QVBoxLayout(mainWidget)

        hLayoutListWidget = QHBoxLayout()
        widgetPutList = UI_objectList()
        widgetBaseList = UI_objectList()
        widgetPutList.label.setText('Put Object List')
        widgetBaseList.label.setText('Ground Object List')
        buttonPut = QPushButton('Put Object')
        widgetPutList.listWidget.setObjectName(Window_global.listWidgetPutName)
        widgetBaseList.listWidget.setObjectName(
            Window_global.listWidgetGroundName)

        widgetGroupList = UI_objectList()
        widgetGroupList.label.setText('Duplicate Group List')
        widgetGroupList.listWidget.setObjectName(Window_global.duGroupListName)
        widgetGroupList.listWidget.setSelectionMode(
            QAbstractItemView.SingleSelection)

        hLayoutListWidget.addWidget(widgetPutList)
        hLayoutListWidget.addWidget(widgetBaseList)

        randomGroupBox = QGroupBox('Random')
        vLayoutRandom = QVBoxLayout(randomGroupBox)

        rotateValidator = QDoubleValidator(-1000000, 1000000, 2, self)
        scaleValidator = QDoubleValidator(0.0, 100, 2, self)

        randomOptionR = UI_randomOption2('Rotate', rotateValidator, -45, 45)
        randomOptionS = UI_randomOption2('Scale', scaleValidator, 0.8, 1.2)
        randomOptionRA = UI_randomOption('Rotate All', rotateValidator, -45,
                                         45)
        randomOptionSA = UI_randomOption('Scale All', scaleValidator, 0.8, 1.2)
        randomOptionR.setObjectName(Window_global.randomOptionRotName)
        randomOptionS.setObjectName(Window_global.randomOptionScaleName)
        randomOptionRA.setObjectName(Window_global.randomOptionRotAName)
        randomOptionSA.setObjectName(Window_global.randomOptionScaleAName)

        vLayoutRandom.addWidget(randomOptionR)
        vLayoutRandom.addWidget(randomOptionS)
        vLayoutRandom.addWidget(randomOptionRA)
        vLayoutRandom.addWidget(randomOptionSA)

        offsetGroupBox = QGroupBox('Offset')
        vLayoutOffset = QVBoxLayout(offsetGroupBox)

        componentCheck = QCheckBox("Component check")
        offsetSlider1 = UI_OffsetSlider("Offset By Object", -1, 1, 0)
        offsetSlider2 = UI_OffsetSlider("Offset By Ground", -100, 100, 0)
        componentCheck.setObjectName(Window_global.componentCheckName)
        offsetSlider1.setObjectName(Window_global.offsetByObjectName)
        offsetSlider2.setObjectName(Window_global.offsetByGroundName)

        vLayoutOffset.addWidget(componentCheck)
        vLayoutOffset.addWidget(offsetSlider1)
        vLayoutOffset.addWidget(offsetSlider2)

        orientGroupBox = QGroupBox('Orient Option')
        vLayoutOrient = QVBoxLayout(orientGroupBox)
        orientNormalCheck = QCheckBox("Ground Normal Affects")
        hLayoutCombobox = QHBoxLayout()
        orientTypeText = QLabel('Orient Edit Type : ')
        orientTypeComboBox = QComboBox()
        orientTypeComboBox.addItem('All')
        orientTypeComboBox.addItem('Only Y')
        hLayoutCombobox.addWidget(orientTypeText)
        hLayoutCombobox.addWidget(orientTypeComboBox)
        vLayoutOrient.addWidget(orientNormalCheck)
        vLayoutOrient.addLayout(hLayoutCombobox)
        orientNormalCheck.setObjectName(Window_global.checkNormalOrientName)
        orientTypeComboBox.setObjectName(Window_global.orientEditModeName)

        vLayout.addLayout(hLayoutListWidget)
        vLayout.addWidget(widgetGroupList)
        vLayout.addWidget(randomGroupBox)
        vLayout.addWidget(offsetGroupBox)
        vLayout.addWidget(orientGroupBox)
        vLayout.addWidget(buttonPut)
        Window_global.loadInfo()

        QtCore.QObject.connect(buttonPut, QtCore.SIGNAL('clicked()'),
                               Window_cmd.setTool_putObjectOnGround)
コード例 #56
0
ファイル: rivalctl-qt.py プロジェクト: tomko222/rivalctl
app = QApplication(sys.argv)
layout = QGridLayout()

# wheel_color
wheel_color_label = QLabel("Wheel color:")
layout.addWidget(wheel_color_label, 0, 0)
wheel_color_area = ColorArea()
layout.addWidget(wheel_color_area, 0, 1)
wheel_color_area.clicked.connect(wheel_color_area.choose_color)

# wheel_style
wheel_style_label = QLabel("Wheel style:")
layout.addWidget(wheel_style_label, 0, 2)
wheel_style_combo_box = QComboBox()
wheel_style_combo_box.addItem("Steady")
wheel_style_combo_box.addItem("Slow breath")
wheel_style_combo_box.addItem("Middle breath")
wheel_style_combo_box.addItem("Fast breath")
layout.addWidget(wheel_style_combo_box, 0, 3)

# logo_color
logo_color_label = QLabel("Logo color:")
layout.addWidget(logo_color_label, 1, 0)
logo_color_area = ColorArea()
layout.addWidget(logo_color_area, 1, 1)
logo_color_area.clicked.connect(logo_color_area.choose_color)

# logo_style
logo_style_label = QLabel("Logo style:")
layout.addWidget(logo_style_label, 1, 2)