コード例 #1
0
ファイル: bug_860.py プロジェクト: BadSingleton/pyside2
    def testSignalMapper(self):
        checkboxMapper = QSignalMapper()
        box = QCheckBox('check me')
        box.stateChanged.connect(checkboxMapper.map)

        checkboxMapper.setMapping(box, box.text())
        checkboxMapper.mapped[str].connect(self.cb_changed)
        self._changed = False
        box.setChecked(True)
        self.assert_(self._changed)
コード例 #2
0
ファイル: findtoolbar.py プロジェクト: amirkogit/QtTestGround
    def __init__(self):
        super(FindToolBar, self).__init__()
        self._line_edit = QLineEdit()
        self._line_edit.setClearButtonEnabled(True)
        self._line_edit.setPlaceholderText("Find...")
        self._line_edit.setMaximumWidth(300)
        self._line_edit.returnPressed.connect(self._find_next)
        self.addWidget(self._line_edit)

        self._previous_button = QToolButton()
        self._previous_button.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/up-32.png'))
        self._previous_button.clicked.connect(self._find_previous)
        self.addWidget(self._previous_button)

        self._next_button = QToolButton()
        self._next_button.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/down-32.png'))
        self._next_button.clicked.connect(self._find_next)
        self.addWidget(self._next_button)

        self._case_sensitive_checkbox = QCheckBox('Case Sensitive')
        self.addWidget(self._case_sensitive_checkbox)

        self._hideButton = QToolButton()
        self._hideButton.setShortcut(QKeySequence(Qt.Key_Escape))
        self._hideButton.setIcon(QIcon(':/qt-project.org/styles/macstyle/images/closedock-16.png'))
        self._hideButton.clicked.connect(self.hide)
        self.addWidget(self._hideButton)
コード例 #3
0
ファイル: bug_416.py プロジェクト: BadSingleton/pyside2
    def testCase(self):
        check = QCheckBox()
        check.setTristate(True)

        s1 = QState()
        s2 = QState()

        t1 = CheckedTransition(check)
        t1.setTargetState(s2)
        s1.addTransition(t1)

        machine = QStateMachine()
        machine.addState(s1)
        machine.addState(s2)
        machine.setInitialState(s1)
        machine.start()

        check.stateChanged[int].emit(1)
        check.show()
        self.app.exec_()
        self.assert_(t1.eventTested)
コード例 #4
0
ファイル: findtoolbar.py プロジェクト: amirkogit/QtTestGround
class FindToolBar(QToolBar):

    find = QtCore.Signal(str, QWebEnginePage.FindFlags)

    def __init__(self):
        super(FindToolBar, self).__init__()
        self._line_edit = QLineEdit()
        self._line_edit.setClearButtonEnabled(True)
        self._line_edit.setPlaceholderText("Find...")
        self._line_edit.setMaximumWidth(300)
        self._line_edit.returnPressed.connect(self._find_next)
        self.addWidget(self._line_edit)

        self._previous_button = QToolButton()
        self._previous_button.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/up-32.png'))
        self._previous_button.clicked.connect(self._find_previous)
        self.addWidget(self._previous_button)

        self._next_button = QToolButton()
        self._next_button.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/down-32.png'))
        self._next_button.clicked.connect(self._find_next)
        self.addWidget(self._next_button)

        self._case_sensitive_checkbox = QCheckBox('Case Sensitive')
        self.addWidget(self._case_sensitive_checkbox)

        self._hideButton = QToolButton()
        self._hideButton.setShortcut(QKeySequence(Qt.Key_Escape))
        self._hideButton.setIcon(QIcon(':/qt-project.org/styles/macstyle/images/closedock-16.png'))
        self._hideButton.clicked.connect(self.hide)
        self.addWidget(self._hideButton)

    def focus_find(self):
        self._line_edit.setFocus()

    def _emit_find(self, backward):
        needle =  self._line_edit.text().strip()
        if needle:
            flags = QWebEnginePage.FindFlags()
            if self._case_sensitive_checkbox.isChecked():
                flags |= QWebEnginePage.FindCaseSensitively
            if backward:
                flags |= QWebEnginePage.FindBackward
            self.find.emit(needle, flags)

    def _find_next(self):
        self._emit_find(False)

    def _find_previous(self):
        self._emit_find(True)
コード例 #5
0
    def _setupUI(self):
        self.setWindowTitle("Export Attributes to USD")
        layout = QVBoxLayout()

        # This section contains the attributes tagged for export.
        label = QLabel()
        label.setText('Exported Attributes:')
        layout.addWidget(label)

        self.exportedAttrsModel = ExportedAttributesModel()
        self.exportedAttrsView = ExportedAttributesView()
        self.exportedAttrsView.verticalHeader().hide()
        self.exportedAttrsView.setModel(self.exportedAttrsModel)
        selectionModel = self.exportedAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(self._onExportedAttrsSelectionChanged)
        self.exportedAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.exportedAttrsView)

        self.removeExportedAttrButton = QPushButton("Remove Exported Attribute")
        self.removeExportedAttrButton.clicked.connect(self._onRemoveExportedAttrPressed)
        self.removeExportedAttrButton.setEnabled(False)
        layout.addWidget(self.removeExportedAttrButton)

        # This section contains the attributes available for export.
        label = QLabel()
        label.setText('Available Attributes:')
        layout.addWidget(label)

        self.userDefinedCheckBox = QCheckBox('User Defined')
        self.userDefinedCheckBox.setToolTip('Show only user-defined (dynamic) attributes')
        self.userDefinedCheckBox.setChecked(True)
        self.userDefinedCheckBox.stateChanged.connect(self._syncUI)
        layout.addWidget(self.userDefinedCheckBox)

        self.addAttrsModel = AddAttributesModel()
        self.addAttrsView = AddAttributesView()
        self.addAttrsView.setModel(self.addAttrsModel)
        selectionModel = self.addAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(self._onAddAttrsSelectionChanged)
        self.addAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.addAttrsView)

        self.addExportedAttrButton = QPushButton("Add Exported Attribute")
        self.addExportedAttrButton.clicked.connect(self._onAddExportedAttrPressed)
        self.addExportedAttrButton.setEnabled(False)
        layout.addWidget(self.addExportedAttrButton)

        self.setLayout(layout)
コード例 #6
0
ファイル: folder.py プロジェクト: strohne/Facepager
    def __init__(self,*args,**kwargs):
        super(SelectFolderDialog,self).__init__(*args,**kwargs)
        self.setOption(QFileDialog.DontUseNativeDialog)
        self.setFileMode(QFileDialog.Directory)


        #QFileDialog.getExistingDirectory(self, 'Select Download Folder', datadir)) #, QFileDialog.ShowDirsOnly
        #self.mainWindow = self.parent()

        self.optionNodes = QCheckBox("Add selected files as nodes",self)
        self.optionNodes.clicked.connect(self.optionNodesClick)
        #self.optionNodes.setCheckState(Qt.CheckState.Checked)

        layout = self.layout()
        row = layout.rowCount()
        layout.addWidget(QLabel('Options'),row,0)

        options = QHBoxLayout()
        options.addWidget(self.optionNodes)
        options.addStretch(1)
        layout.addLayout(options,row,1,1,2)
        self.setLayout(layout)
コード例 #7
0
ファイル: folder.py プロジェクト: strohne/Facepager
class SelectFolderDialog(QFileDialog):
    """
    Create a custom Folder Dialog with an option to import files as nodes
    """

    def __init__(self,*args,**kwargs):
        super(SelectFolderDialog,self).__init__(*args,**kwargs)
        self.setOption(QFileDialog.DontUseNativeDialog)
        self.setFileMode(QFileDialog.Directory)


        #QFileDialog.getExistingDirectory(self, 'Select Download Folder', datadir)) #, QFileDialog.ShowDirsOnly
        #self.mainWindow = self.parent()

        self.optionNodes = QCheckBox("Add selected files as nodes",self)
        self.optionNodes.clicked.connect(self.optionNodesClick)
        #self.optionNodes.setCheckState(Qt.CheckState.Checked)

        layout = self.layout()
        row = layout.rowCount()
        layout.addWidget(QLabel('Options'),row,0)

        options = QHBoxLayout()
        options.addWidget(self.optionNodes)
        options.addStretch(1)
        layout.addLayout(options,row,1,1,2)
        self.setLayout(layout)

        #if self.exec_():
            #if os.path.isfile(self.selectedFiles()[0]):
            
    def optionNodesClick(self):
        if self.optionNodes.isChecked():
            self.setFileMode(QFileDialog.ExistingFiles)
        else:
            self.setFileMode(QFileDialog.Directory)
コード例 #8
0
ファイル: MainWindow.py プロジェクト: goph-R/TilePad
class MainWindow(QMainWindow):

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

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

        self.setMinimumWidth(540)

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

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

        # widgets
        self.showPixmapWidget = None

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

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

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

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

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

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

        self.reorderTilesCheckBox = QCheckBox("Reorder tiles")

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

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

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

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

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

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

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

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

        self.setTitle()

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

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

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

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

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

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

    def generateAndExportClicked(self):

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

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

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

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

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

        super(MainWindow, self).closeEvent(event)
コード例 #9
0
    def paint(self, painter, option, index):
        checked = bool(index.data())
        checkbox = QCheckBox()

        if (index.flags() & Qt.ItemIsEditable) > 0:
            checkbox.setEnabled(True)
        else:
            checkbox.setEnabled(False)

        if checked:
            checkbox.setCheckState(Qt.Checked)
        else:
            checkbox.setCheckState(Qt.Unchecked)

        checkbox.rect = self.getCheckBoxRect(option)

        #checkbox.setCheckState(QStyle.State_Enabled)

        style = '''QCheckBox, QRadioButton {
                color: #546E7A;
            }

            QCheckBox::indicator::unchecked  {
                background-color: #FFFFFF;
                border: 1px solid #536D79;
            }

            QCheckBox::indicator::checked, QTreeView::indicator::checked {
                background-color: qradialgradient(cx:0.5, cy:0.5, fx:0.25, fy:0.15, radius:0.3, stop:0 #80CBC4, stop:1 #FFFFFF);
                border: 1px solid #536D79;
            }


            QCheckBox::indicator:disabled, QRadioButton::indicator:disabled, QTreeView::indicator:disabled {
                background-color: #444444;			/* Not sure what this looks like */
            }

            QCheckBox::indicator::checked:disabled, QRadioButton::indicator::checked:disabled, QTreeView::indicator::checked:disabled {  
                background-color: qradialgradient(cx:0.5, cy:0.5, fx:0.25, fy:0.15, radius:0.3, stop:0 #BBBBBB, stop:1 #444444); /* Not sure what this looks like */
            }

            '''
        checkbox.setStyleSheet(style)

        painter.save()
        painter.translate(option.rect.topLeft())
        checkbox.render(painter, QPoint(0, 0))
        painter.restore()
コード例 #10
0
    def __init__(self, parent):
        """
        Groupbox for to serve as example for creation of custom groups.
        Don't forget to add this class to the relevant handling functions at the
        parent, e.g. add_group()
        """
        super().__init__()
        self.setTitle('CustomName')
        self.parent = parent
        self.group_type = 'CustomName'

        # Name: it has a special treatment, since it need to be unique we test
        # if the parent contain other objects of the same type
        self.lbl_name = QLabel('name<span style="color:' +
                               required_asterisk_color + ';">*</span>:')
        self.form_name = QLineEdit('CustomName')
        self.form_name.setToolTip("The unique name of this group.")
        nInstances = 0
        for grp in self.parent.groups_list:
            if isinstance(grp, GroupCustomExample):
                nInstances += 1
        if nInstances > 0:
            self.form_name.setText('CustomName' + str(nInstances))

        # Mandatory field: we fill it with default values
        self.lbl_mandatory = QLabel('mandatory<span style="color:' +
                                    required_asterisk_color + ';">*</span>:')
        self.form_mandatory = QLineEdit('ABC123')
        self.form_mandatory.setToolTip("This is a mandatory field.")

        # Optional field: we leave a placeholder text as example
        self.lbl_optional = QLabel('optional:')
        self.form_optional = QLineEdit('')
        self.form_optional.setPlaceholderText("example")
        self.form_optional.setToolTip("This is an optional field.")

        # Field with link to other objects. This type of field needs to be
        # updated with self.refresh_objects_references()
        self.lbl_link = QLabel('link:')
        self.combo_link = CustomComboBox()
        self.combo_link.setToolTip("This field links to existing objects.")

        # Field that should be handled by conversion script
        self.lbl_script = QLabel('script:')
        self.chk_script = QCheckBox("Get from source file")
        self.chk_script.setChecked(False)
        self.chk_script.setToolTip(
            "This field will be handled by conversion script.\n"
            "Check box if this data will be retrieved from source file.\n"
            "Uncheck box to ignore it.")

        self.grid = QGridLayout()
        self.grid.setColumnStretch(2, 1)
        self.grid.addWidget(self.lbl_name, 0, 0, 1, 2)
        self.grid.addWidget(self.form_name, 0, 2, 1, 4)
        self.grid.addWidget(self.lbl_mandatory, 1, 0, 1, 2)
        self.grid.addWidget(self.form_mandatory, 1, 2, 1, 4)
        self.grid.addWidget(self.lbl_optional, 2, 0, 1, 2)
        self.grid.addWidget(self.form_optional, 2, 2, 1, 4)
        self.grid.addWidget(self.lbl_link, 3, 0, 1, 2)
        self.grid.addWidget(self.combo_link, 3, 2, 1, 4)
        self.grid.addWidget(self.lbl_script, 4, 0, 1, 2)
        self.grid.addWidget(self.chk_script, 4, 2, 1, 2)
        self.setLayout(self.grid)
コード例 #11
0
ファイル: export.py プロジェクト: strohne/Facepager
class ExportFileDialog(QFileDialog):
    """
    Create a custom Export-File Dialog with options like BOM etc.
    """

    def __init__(self,*args,**kwargs):
        super(ExportFileDialog,self).__init__(*args,**kwargs)

        self.mainWindow = self.parent()
        self.setWindowTitle("Export nodes to CSV")
        self.setAcceptMode(QFileDialog.AcceptSave)
        self.setOption(QFileDialog.DontUseNativeDialog)
        #self.setFilter("CSV Files (*.csv)")
        self.setDefaultSuffix("csv")

        self.optionBOM = QCheckBox("Use a BOM",self)
        self.optionBOM.setCheckState(Qt.CheckState.Checked)

        self.optionLinebreaks = QCheckBox("Remove line breaks",self)
        self.optionLinebreaks.setCheckState(Qt.CheckState.Checked)

        self.optionSeparator = QComboBox(self)
        self.optionSeparator.insertItems(0, [";","\\t",","])
        self.optionSeparator.setEditable(True)

        #self.optionLinebreaks.setCheckState(Qt.CheckState.Checked)

        self.optionWide = QCheckBox("Convert to wide format (experimental feature)",self)
        self.optionWide.setCheckState(Qt.CheckState.Unchecked)

        # if none or all are selected, export all
        # if one or more are selected, export selective
        self.optionAll = QComboBox(self)
        self.optionAll.insertItems(0, ['All nodes (faster for large datasets, ordered by internal ID)','Selected nodes (ordered like shown in nodes view)'])
        if self.mainWindow.tree.noneOrAllSelected():
            self.optionAll.setCurrentIndex(0)
        else:
            self.optionAll.setCurrentIndex(1)

        layout = self.layout()
        row = layout.rowCount()
        layout.addWidget(QLabel('Options'),row,0)

        options = QHBoxLayout()
        options.addWidget(self.optionBOM)
        options.addWidget(self.optionLinebreaks)
        options.addWidget(QLabel('Separator'))
        options.addWidget(self.optionSeparator)
        options.addStretch(1)

        layout.addLayout(options,row,1,1,2)

        layout.addWidget(QLabel('Post processing'),row+1,0)
        layout.addWidget(self.optionWide,row+1,1,1,2)

        layout.addWidget(QLabel('Export mode'),row+2,0)
        layout.addWidget(self.optionAll,row+2,1,1,2)
        self.setLayout(layout)

        if self.exec_():

            if os.path.isfile(self.selectedFiles()[0]):
                os.remove(self.selectedFiles()[0])
            output = open(self.selectedFiles()[0], 'w', newline='', encoding='utf8')
            if self.optionBOM.isChecked() and not self.optionWide.isChecked():
                output.write('\ufeff')

            try:
                if self.optionAll.currentIndex() == 0:
                    self.exportAllNodes(output)
                else:
                    self.exportSelectedNodes(output)
            finally:
                output.close()

            if self.optionWide.isChecked():
                self.convertToWideFormat(self.selectedFiles()[0])


    def exportSelectedNodes(self,output):
        progress = ProgressBar("Exporting data...", self.mainWindow)

        #indexes = self.mainWindow.tree.selectionModel().selectedRows()
        #if child nodes should be exported as well, uncomment this line an comment the previous one
        indexes = self.mainWindow.tree.selectedIndexesAndChildren()
        progress.setMaximum(len(indexes))

        try:
            delimiter = self.optionSeparator.currentText()
            delimiter = delimiter.encode('utf-8').decode('unicode_escape')
            writer = csv.writer(output, delimiter=delimiter, quotechar='"', quoting=csv.QUOTE_ALL, doublequote=True,
                                lineterminator='\r\n')


            #headers
            row = [str(val) for val in self.mainWindow.tree.treemodel.getRowHeader()]
            if self.optionLinebreaks.isChecked():
                row = [val.replace('\n', ' ').replace('\r',' ') for val in row]

            writer.writerow(row)

            #rows
            for no in range(len(indexes)):
                if progress.wasCanceled:
                    break

                row = [str(val) for val in self.mainWindow.tree.treemodel.getRowData(indexes[no])]
                if self.optionLinebreaks.isChecked():
                    row = [val.replace('\n', ' ').replace('\r',' ') for val in row]

                writer.writerow(row)

                progress.step()

        finally:
            progress.close()


    def exportAllNodes(self,output):
        progress = ProgressBar("Exporting data...", self.mainWindow)
        progress.setMaximum(Node.query.count())


        try:
            delimiter = self.optionSeparator.currentText()
            delimiter = delimiter.encode('utf-8').decode('unicode_escape')
            writer = csv.writer(output, delimiter=delimiter, quotechar='"', quoting=csv.QUOTE_ALL, doublequote=True,
                                lineterminator='\r\n')

            #headers
            row = ["level", "id", "parent_id", "object_id", "object_type", "query_status", "query_time",
                   "query_type"]
            for key in self.mainWindow.tree.treemodel.customcolumns:
                row.append(key)
            if self.optionLinebreaks.isChecked():
                row = [val.replace('\n', ' ').replace('\r',' ') for val in row]

            writer.writerow(row)

            #rows
            page = 0

            while True:
                allnodes = Node.query.offset(page * 5000).limit(5000)
                if allnodes.count() == 0:
                    break
                for node in allnodes:
                    if progress.wasCanceled:
                        break
                    row = [node.level, node.id, node.parent_id, node.objectid, node.objecttype,
                           node.querystatus, node.querytime, node.querytype]
                    for key in self.mainWindow.tree.treemodel.customcolumns:
                        row.append(node.getResponseValue(key))

                    if self.optionLinebreaks.isChecked():
                        row = [str(val).replace('\n', ' ').replace('\r',' ') for val in row]

                    writer.writerow(row)
                    # step the Bar
                    progress.step()
                if progress.wasCanceled:
                    break
                else:
                    page += 1

        finally:
            progress.close()

    def convertToWideFormat(self,filename):
        progress = ProgressBar("Converting data...", self.mainWindow)
        try:
            #Separate levels
            def flattenTable(fulltable,levelcol,idcol,parentidcol,countchildren,removeempty):
                fulltable[[levelcol]] = fulltable[[levelcol]].astype(int)

                levels = dict(list(fulltable.groupby(levelcol)))
                minlevel = fulltable.level.min()
                for level, data in sorted(levels.items()):
                    #First level is the starting point for the following merges
                    if level == minlevel:
                        #data = data[[idcol,'object_id','object_type']]
                        data = data.add_prefix('level_{}-'.format(level))
                        flattable = data
                    else:
                        #Aggregate object types and join them
                        for col_countchildren in countchildren:
                            children = data[parentidcol].groupby([data[parentidcol],data[col_countchildren]]).count()
                            children = children.unstack(col_countchildren)
                            children['total'] = children.sum(axis=1)
                            children = children.add_prefix('level_{}-children-{}-'.format(level-1,col_countchildren))

                            leftkey = 'level_{}-id'.format(level-1)
                            flattable = merge(flattable,children,how='left',left_on=leftkey,right_index=True)
                            flattable[children.columns.values.tolist()] = flattable[children.columns.values.tolist()].fillna(0).astype(int)

                        #Join data
                        data['childnumber'] = data.groupby(parentidcol).cumcount()
                        leftkey = 'level_{}-{}'.format(level-1,idcol)
                        rightkey = 'level_{}-{}'.format(level,parentidcol)
                        data = data.drop([levelcol],axis=1)
                        data = data.add_prefix('level_{}-'.format(level))
                        flattable = merge(flattable,data,how="outer",left_on=leftkey,right_on=rightkey)

                if removeempty:
                    flattable = flattable.dropna(axis=1,how='all')
                return flattable

            try:
                #delimiter
                delimiter = self.optionSeparator.currentText()
                delimiter = delimiter.encode('utf-8').decode('unicode_escape')

                #open
                data = read_csv(filename, sep=delimiter,encoding='utf-8',dtype=str)

                #convert
                newdata = flattenTable(data,'level','id','parent_id',['object_type','query_status','query_type'],False)


                #save
                outfile = open(filename, 'w',newline='',encoding='utf8')
                try:
                    if self.optionBOM.isChecked():
                        outfile.write('\ufeff') #UTF8 BOM
                    newdata.to_csv(outfile,sep=delimiter,index=False,encoding="utf-8")
                finally:
                    outfile.close()
            except Exception as e:
                self.mainWindow.logmessage(e)
        finally:
            progress.close()
コード例 #12
0
    def createEditor(self, parent, option, index):
        check = QCheckBox(parent)

        check.toggled.connect(self.statusChanged)

        return check
コード例 #13
0
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(787, 415)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.base = QFrame(self.centralwidget)
        self.base.setObjectName(u"base")
        self.base.setStyleSheet(u"QFrame{\n"
                                "\n"
                                "	\n"
                                "	background-color: rgb(97, 101, 157);\n"
                                "}")
        self.base.setFrameShape(QFrame.StyledPanel)
        self.base.setFrameShadow(QFrame.Raised)
        self.horizontalLayout = QHBoxLayout(self.base)
        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.frame_for_widgets = QFrame(self.base)
        self.frame_for_widgets.setObjectName(u"frame_for_widgets")
        self.frame_for_widgets.setStyleSheet(
            u"QFrame{\n"
            "\n"
            "border-radius:25px;\n"
            "\n"
            "\n"
            "\n"
            "background-color: rgb(24, 25, 39);\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "}")
        self.frame_for_widgets.setFrameShape(QFrame.NoFrame)
        self.frame_for_widgets.setFrameShadow(QFrame.Raised)
        self.verticalLayout_4 = QVBoxLayout(self.frame_for_widgets)
        self.verticalLayout_4.setSpacing(0)
        self.verticalLayout_4.setObjectName(u"verticalLayout_4")
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.frame = QFrame(self.frame_for_widgets)
        self.frame.setObjectName(u"frame")
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_2 = QHBoxLayout(self.frame)
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.select_zip_button = QPushButton(self.frame)
        self.select_zip_button.setObjectName(u"select_zip_button")
        self.select_zip_button.setMinimumSize(QSize(75, 75))
        self.select_zip_button.setMaximumSize(QSize(75, 75))
        font = QFont()
        font.setFamily(u"Segoe UI Light")
        font.setPointSize(24)
        self.select_zip_button.setFont(font)
        self.select_zip_button.setStyleSheet(
            u"QPushButton{\n"
            "	color:rgb(30, 149, 198);\n"
            "	 border: 2px solid black;\n"
            "\n"
            "	border-color:rgb(240, 123, 255);\n"
            "	\n"
            "	background-color: rgb(42, 44, 68);\n"
            "	\n"
            "	border-radius:10px;\n"
            "}\n"
            "QPushButton:hover{\n"
            "\n"
            "\n"
            "border-color:rgb(255, 37, 255);\n"
            "\n"
            "\n"
            "}")

        self.horizontalLayout_2.addWidget(self.select_zip_button)

        self.horizontalSpacer = QSpacerItem(331, 20, QSizePolicy.Expanding,
                                            QSizePolicy.Minimum)

        self.horizontalLayout_2.addItem(self.horizontalSpacer)

        self.verticalLayout_4.addWidget(self.frame)

        self.frame_left_middle = QFrame(self.frame_for_widgets)
        self.frame_left_middle.setObjectName(u"frame_left_middle")
        self.frame_left_middle.setFrameShape(QFrame.StyledPanel)
        self.frame_left_middle.setFrameShadow(QFrame.Raised)
        self.verticalLayout_5 = QVBoxLayout(self.frame_left_middle)
        self.verticalLayout_5.setSpacing(0)
        self.verticalLayout_5.setObjectName(u"verticalLayout_5")
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.frame_left_middle_up = QFrame(self.frame_left_middle)
        self.frame_left_middle_up.setObjectName(u"frame_left_middle_up")
        self.frame_left_middle_up.setFrameShape(QFrame.StyledPanel)
        self.frame_left_middle_up.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_4 = QHBoxLayout(self.frame_left_middle_up)
        self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
        self.label = QLabel(self.frame_left_middle_up)
        self.label.setObjectName(u"label")
        font1 = QFont()
        font1.setFamily(u"Arial Rounded MT Bold")
        font1.setPointSize(11)
        self.label.setFont(font1)
        self.label.setStyleSheet(u"QLabel{\n"
                                 " color:rgb(30, 149, 198);\n"
                                 "\n"
                                 "	\n"
                                 "\n"
                                 "	}")
        self.label.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_3.addWidget(self.label)

        self.lineEdit = QLineEdit(self.frame_left_middle_up)
        self.lineEdit.setObjectName(u"lineEdit")
        self.lineEdit.setStyleSheet(u"QLineEdit{\n"
                                    "color:rgb(30, 149, 198);\n"
                                    "	background-color: rgb(65, 69, 106);\n"
                                    "\n"
                                    "border:2px solid black;\n"
                                    "\n"
                                    "border-radius:3px;\n"
                                    "border-color:rgb(240, 123, 255);\n"
                                    "\n"
                                    "}")

        self.horizontalLayout_3.addWidget(self.lineEdit)

        self.same_as_zip_name_checkbox = QCheckBox(self.frame_left_middle_up)
        self.same_as_zip_name_checkbox.setObjectName(
            u"same_as_zip_name_checkbox")
        font2 = QFont()
        font2.setFamily(u"Arial Rounded MT Bold")
        font2.setPointSize(10)
        self.same_as_zip_name_checkbox.setFont(font2)
        self.same_as_zip_name_checkbox.setStyleSheet(
            u"QCheckBox{\n"
            "color:rgb(30, 149, 198);\n"
            "\n"
            "}\n"
            "QCheckBox:unchecked {\n"
            "   \n"
            "	 color:rgb(30, 149, 198);\n"
            "}\n"
            "QCheckBox::indicator {\n"
            "    width: 13px;\n"
            "    height: 13px;\n"
            "	\n"
            "	color: rgb(30, 149, 198);\n"
            "	background-color: rgb(42, 44, 68);\n"
            "}\n"
            "QCheckBox::indicator:checked {\n"
            "   \n"
            "	\n"
            "	background-color: rgb(192, 98, 204);\n"
            "}\n"
            "QCheckBox:checked {\n"
            "\n"
            "color: rgb(38, 194, 255);\n"
            " \n"
            "}\n"
            "\n"
            "QCheckBox::indicator:checked {\n"
            "color: rgb(253, 111, 54);\n"
            "    \n"
            "}\n"
            "")

        self.horizontalLayout_3.addWidget(self.same_as_zip_name_checkbox)

        self.horizontalLayout_4.addLayout(self.horizontalLayout_3)

        self.horizontalSpacer_2 = QSpacerItem(85, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_4.addItem(self.horizontalSpacer_2)

        self.verticalLayout_5.addWidget(self.frame_left_middle_up)

        self.frame_3 = QFrame(self.frame_left_middle)
        self.frame_3.setObjectName(u"frame_3")
        self.frame_3.setFrameShape(QFrame.StyledPanel)
        self.frame_3.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_6 = QHBoxLayout(self.frame_3)
        self.horizontalLayout_6.setObjectName(u"horizontalLayout_6")
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
        self.label_2 = QLabel(self.frame_3)
        self.label_2.setObjectName(u"label_2")
        self.label_2.setMinimumSize(QSize(100, 0))
        font3 = QFont()
        font3.setFamily(u"Segoe UI")
        font3.setPointSize(12)
        self.label_2.setFont(font3)
        self.label_2.setStyleSheet(u"QLabel{\n"
                                   "\n"
                                   "	\n"
                                   "	\n"
                                   " color:rgb(30, 149, 198);\n"
                                   "\n"
                                   "	\n"
                                   "\n"
                                   "	}")
        self.label_2.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_5.addWidget(self.label_2)

        self.algorithm_combobox = QComboBox(self.frame_3)
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.setObjectName(u"algorithm_combobox")
        self.algorithm_combobox.setMinimumSize(QSize(150, 0))
        font4 = QFont()
        font4.setFamily(u"Segoe UI")
        font4.setPointSize(10)
        font4.setBold(True)
        font4.setWeight(75)
        self.algorithm_combobox.setFont(font4)
        self.algorithm_combobox.setStyleSheet(
            u"QComboBox{\n"
            "\n"
            "	\n"
            "	color:rgb(30, 149, 198);\n"
            "\n"
            "	border:2px solid black;\n"
            "	border-color:rgb(240, 123, 255);\n"
            "	background-color: rgb(42, 44, 68);\n"
            "	\n"
            "\n"
            "}\n"
            "QComboBox::down-arrow {\n"
            "  border:1px solid black;\n"
            "border-color:rgb(30, 149, 198);\n"
            "}\n"
            "\n"
            "ComboBox::drop-down {\n"
            "   \n"
            "	color: rgb(30, 149, 198);\n"
            "	background-color: rgb(56, 58, 91);\n"
            "}\n"
            "\n"
            "\n"
            "QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
            "    top: 1px;\n"
            "    left: 1px;\n"
            "}\n"
            "")

        self.horizontalLayout_5.addWidget(self.algorithm_combobox)

        self.horizontalLayout_6.addLayout(self.horizontalLayout_5)

        self.horizontalSpacer_3 = QSpacerItem(146, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_6.addItem(self.horizontalSpacer_3)

        self.verticalLayout_5.addWidget(self.frame_3)

        self.verticalLayout_4.addWidget(self.frame_left_middle)

        self.frame_left_bottom = QFrame(self.frame_for_widgets)
        self.frame_left_bottom.setObjectName(u"frame_left_bottom")
        self.frame_left_bottom.setFrameShape(QFrame.StyledPanel)
        self.frame_left_bottom.setFrameShadow(QFrame.Raised)
        self.verticalLayout_6 = QVBoxLayout(self.frame_left_bottom)
        self.verticalLayout_6.setSpacing(0)
        self.verticalLayout_6.setObjectName(u"verticalLayout_6")
        self.verticalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.frame_for_start_button = QFrame(self.frame_left_bottom)
        self.frame_for_start_button.setObjectName(u"frame_for_start_button")
        self.frame_for_start_button.setFrameShape(QFrame.StyledPanel)
        self.frame_for_start_button.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_8 = QHBoxLayout(self.frame_for_start_button)
        self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
        self.horizontalLayout_7 = QHBoxLayout()
        self.horizontalLayout_7.setObjectName(u"horizontalLayout_7")
        self.label_3 = QLabel(self.frame_for_start_button)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setMinimumSize(QSize(100, 0))
        self.label_3.setFont(font2)
        self.label_3.setStyleSheet(u"QLabel{\n"
                                   "\n"
                                   "	\n"
                                   " color:rgb(30, 149, 198);\n"
                                   "\n"
                                   "	\n"
                                   "\n"
                                   "	}")
        self.label_3.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_7.addWidget(self.label_3)

        self.toolButton = QToolButton(self.frame_for_start_button)
        self.toolButton.setObjectName(u"toolButton")
        self.toolButton.setStyleSheet(u"QToolButton{\n"
                                      "	color:rgb(30, 149, 198);\n"
                                      "	 border: 2px solid black;\n"
                                      "\n"
                                      "	border-color:rgb(240, 123, 255);\n"
                                      "	\n"
                                      "	background-color: rgb(42, 44, 68);\n"
                                      "	\n"
                                      "	border-radius:1px;\n"
                                      "}\n"
                                      "QToolButton:hover{\n"
                                      "\n"
                                      "\n"
                                      "border-color:rgb(255, 37, 255);\n"
                                      "\n"
                                      "\n"
                                      "}")

        self.horizontalLayout_7.addWidget(self.toolButton)

        self.horizontalLayout_8.addLayout(self.horizontalLayout_7)

        self.horizontalSpacer_4 = QSpacerItem(190, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_8.addItem(self.horizontalSpacer_4)

        self.start_button = QPushButton(self.frame_for_start_button)
        self.start_button.setObjectName(u"start_button")
        self.start_button.setMinimumSize(QSize(75, 75))
        font5 = QFont()
        font5.setFamily(u"Segoe UI Light")
        font5.setPointSize(28)
        self.start_button.setFont(font5)
        self.start_button.setStyleSheet(u"QPushButton{\n"
                                        "	color:rgb(30, 149, 198);\n"
                                        "	 border: 2px solid black;\n"
                                        "\n"
                                        "	border-color:rgb(240, 123, 255);\n"
                                        "	\n"
                                        "	background-color: rgb(42, 44, 68);\n"
                                        "	\n"
                                        "	border-radius:10px;\n"
                                        "}\n"
                                        "QPushButton:hover{\n"
                                        "\n"
                                        "\n"
                                        "border-color:rgb(255, 37, 255);\n"
                                        "\n"
                                        "\n"
                                        "}")

        self.horizontalLayout_8.addWidget(self.start_button)

        self.verticalLayout_6.addWidget(self.frame_for_start_button)

        self.frame_for_progressbar = QFrame(self.frame_left_bottom)
        self.frame_for_progressbar.setObjectName(u"frame_for_progressbar")
        self.frame_for_progressbar.setFrameShape(QFrame.StyledPanel)
        self.frame_for_progressbar.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_10 = QHBoxLayout(self.frame_for_progressbar)
        self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
        self.horizontalSpacer_5 = QSpacerItem(13, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_10.addItem(self.horizontalSpacer_5)

        self.horizontalLayout_9 = QHBoxLayout()
        self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")
        self.label_progress = QLabel(self.frame_for_progressbar)
        self.label_progress.setObjectName(u"label_progress")
        self.label_progress.setFont(font2)
        self.label_progress.setStyleSheet(u"QLabel{\n"
                                          "\n"
                                          " color:rgb(30, 149, 198);\n"
                                          "	\n"
                                          "\n"
                                          "	}")
        self.label_progress.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_9.addWidget(self.label_progress)

        self.progressBar = QProgressBar(self.frame_for_progressbar)
        self.progressBar.setObjectName(u"progressBar")
        self.progressBar.setMinimumSize(QSize(350, 20))
        self.progressBar.setMaximumSize(QSize(450, 20))
        font6 = QFont()
        font6.setFamily(u"Segoe UI")
        font6.setPointSize(9)
        self.progressBar.setFont(font6)
        self.progressBar.setStyleSheet(u"QProgressBar{\n"
                                       "\n"
                                       "	\n"
                                       "	color:rgb(30, 149, 198);\n"
                                       "\n"
                                       "	 border: 1px solid black;\n"
                                       "\n"
                                       "	border-color:rgb(240, 123, 255);\n"
                                       "	\n"
                                       "	background-color: rgb(42, 44, 68);\n"
                                       "	\n"
                                       "	border-radius:2px;\n"
                                       "}\n"
                                       "QProgressBar::chunk{\n"
                                       "\n"
                                       "border-radius:2px;\n"
                                       "\n"
                                       "	background-color:rgb(30, 149, 198);\n"
                                       "}\n"
                                       "QProgressBar:hover{\n"
                                       "border-color:rgb(255, 37, 255);\n"
                                       "}")
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(56)
        self.progressBar.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                      | Qt.AlignVCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setInvertedAppearance(False)

        self.horizontalLayout_9.addWidget(self.progressBar)

        self.horizontalLayout_10.addLayout(self.horizontalLayout_9)

        self.verticalLayout_6.addWidget(self.frame_for_progressbar)

        self.verticalLayout_4.addWidget(self.frame_left_bottom)

        self.horizontalLayout.addWidget(self.frame_for_widgets)

        self.frame_for_textedit = QFrame(self.base)
        self.frame_for_textedit.setObjectName(u"frame_for_textedit")
        sizePolicy1 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy1.setHorizontalStretch(0)
        sizePolicy1.setVerticalStretch(0)
        sizePolicy1.setHeightForWidth(
            self.frame_for_textedit.sizePolicy().hasHeightForWidth())
        self.frame_for_textedit.setSizePolicy(sizePolicy1)
        self.frame_for_textedit.setMinimumSize(QSize(30, 0))
        self.frame_for_textedit.setMaximumSize(QSize(350, 16777215))
        self.frame_for_textedit.setFrameShape(QFrame.StyledPanel)
        self.frame_for_textedit.setFrameShadow(QFrame.Raised)
        self.verticalLayout_2 = QVBoxLayout(self.frame_for_textedit)
        self.verticalLayout_2.setSpacing(0)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.verticalLayout_2.setContentsMargins(-1, 0, 0, 0)
        self.terminal_output = QTextEdit(self.frame_for_textedit)
        self.terminal_output.setObjectName(u"terminal_output")
        self.terminal_output.setFont(font2)
        self.terminal_output.setStyleSheet(
            u"\n"
            "QTextEdit, QListView {\n"
            "   color:rgb(255, 37, 255);\n"
            "    background-color:rgb(40, 41, 65);\n"
            "	border:3px solid black;\n"
            "	border-radius:10px;\n"
            "	border-color:rgb(30, 149, 198);\n"
            "    background-attachment: scroll;\n"
            "}")

        self.verticalLayout_2.addWidget(self.terminal_output)

        self.horizontalLayout.addWidget(self.frame_for_textedit)

        self.verticalLayout.addWidget(self.base)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)

        QMetaObject.connectSlotsByName(MainWindow)
コード例 #14
0
class ShowValHist_NodeInstance_MainWidget(QWidget):
    def __init__(self, parent_node_instance):
        super(ShowValHist_NodeInstance_MainWidget, self).__init__()

        # leave these lines ------------------------------
        self.parent_node_instance = parent_node_instance
        # ------------------------------------------------

        self.setStyleSheet('''
            background-color: #333333;
        ''')

        self.setLayout(QVBoxLayout())
        # settings widget
        settings_widget = QWidget()
        settings_widget.setLayout(QHBoxLayout())
        self.connect_lines_check_box = QCheckBox('connect lines linear')
        settings_widget.layout().addWidget(self.connect_lines_check_box)
        self.layout().addWidget(settings_widget)
        # points area
        self.label = QLabel()
        pix = QPixmap(300, 200)
        self.label.setPixmap(pix)
        self.layout().addWidget(self.label)

        self.resize(300, 200)

        self.values = []

    def update(self, new_vals):
        self.values = new_vals
        if len(self.values) == 0:
            return

        painter = QPainter(self.label.pixmap())
        painter.setRenderHint(QPainter.Antialiasing)

        painter.setPen(QPen('#333333'))
        painter.setBrush(QColor('#333333'))
        painter.drawRect(self.label.rect())

        pen = QPen(QColor(255, 255, 255))
        pen.setWidth(1)
        painter.setPen(pen)
        painter.setBrush(QBrush(Qt.white))

        x_old = -1
        y_old = -1

        div = max(self.values)

        for i in range(len(self.values)):
            v = self.values[i]
            x = i * (self.label.width() / len(self.values))
            y = self.label.height() - self.label.height() * v / div

            if self.connect_lines_check_box.isChecked() and i > 0:
                painter.drawLine(x_old, y_old, x, y)
            else:

                painter.drawEllipse(x - 1, y - 1, 2, 2)

            x_old = x
            y_old = y

        self.repaint()

    def get_data(self):
        return {
            'connect lines linear': self.connect_lines_check_box.isChecked()
        }

    def set_data(self, data):
        self.connect_lines_check_box.setChecked(data['connect lines linear'])

    def remove_event(self):
        pass
コード例 #15
0
    def __init__(self, game: Game) -> None:
        super().__init__("Pilots and Squadrons")
        self.game = game

        layout = QGridLayout()
        self.setLayout(layout)

        self.ai_pilot_levelling = QCheckBox()
        self.ai_pilot_levelling.setChecked(self.game.settings.ai_pilot_levelling)
        self.ai_pilot_levelling.toggled.connect(self.set_ai_pilot_leveling)

        ai_pilot_levelling_info = (
            "Set whether or not AI pilots will level up after completing a number of"
            " sorties. Since pilot level affects the AI skill, you may wish to disable"
            " this, lest you face an Ace!"
        )

        self.ai_pilot_levelling.setToolTip(ai_pilot_levelling_info)
        ai_pilot_levelling_label = QLabel("Allow AI pilot levelling")
        ai_pilot_levelling_label.setToolTip(ai_pilot_levelling_info)

        layout.addWidget(ai_pilot_levelling_label, 0, 0)
        layout.addWidget(self.ai_pilot_levelling, 0, 1, Qt.AlignRight)

        enable_squadron_pilot_limits_info = (
            "If set, squadrons will be limited to a maximum number of pilots and dead "
            "pilots will replenish at a fixed rate, each defined with the settings"
            "below. Auto-purchase may buy aircraft for which there are no pilots"
            "available, so this feature is still a work-in-progress."
        )

        enable_squadron_pilot_limits_label = QLabel(
            "Enable per-squadron pilot limtits (WIP)"
        )
        enable_squadron_pilot_limits_label.setToolTip(enable_squadron_pilot_limits_info)
        enable_squadron_pilot_limits = QCheckBox()
        enable_squadron_pilot_limits.setToolTip(enable_squadron_pilot_limits_info)
        enable_squadron_pilot_limits.setChecked(
            self.game.settings.enable_squadron_pilot_limits
        )
        enable_squadron_pilot_limits.toggled.connect(
            self.set_enable_squadron_pilot_limits
        )

        layout.addWidget(enable_squadron_pilot_limits_label, 1, 0)
        layout.addWidget(enable_squadron_pilot_limits, 1, 1, Qt.AlignRight)

        self.pilot_limit = QSpinBox()
        self.pilot_limit.setMinimum(12)
        self.pilot_limit.setMaximum(72)
        self.pilot_limit.setValue(self.game.settings.squadron_pilot_limit)
        self.pilot_limit.setEnabled(self.game.settings.enable_squadron_pilot_limits)
        self.pilot_limit.valueChanged.connect(self.set_squadron_pilot_limit)

        pilot_limit_info = (
            "Sets the maximum number of pilots a squadron may have active. "
            "Changing this value will not have an immediate effect, but will alter "
            "replenishment for future turns."
        )

        self.pilot_limit.setToolTip(pilot_limit_info)
        pilot_limit_label = QLabel("Maximum number of pilots per squadron")
        pilot_limit_label.setToolTip(pilot_limit_info)

        layout.addWidget(pilot_limit_label, 2, 0)
        layout.addWidget(self.pilot_limit, 2, 1, Qt.AlignRight)

        self.squadron_replenishment_rate = QSpinBox()
        self.squadron_replenishment_rate.setMinimum(1)
        self.squadron_replenishment_rate.setMaximum(20)
        self.squadron_replenishment_rate.setValue(
            self.game.settings.squadron_replenishment_rate
        )
        self.squadron_replenishment_rate.setEnabled(
            self.game.settings.enable_squadron_pilot_limits
        )
        self.squadron_replenishment_rate.valueChanged.connect(
            self.set_squadron_replenishment_rate
        )

        squadron_replenishment_rate_info = (
            "Sets the maximum number of pilots that will be recruited to each squadron "
            "at the end of each turn. Squadrons will not recruit new pilots beyond the "
            "pilot limit, but each squadron with room for more pilots will recruit "
            "this many pilots each turn up to the limit."
        )

        self.squadron_replenishment_rate.setToolTip(squadron_replenishment_rate_info)
        squadron_replenishment_rate_label = QLabel("Squadron pilot replenishment rate")
        squadron_replenishment_rate_label.setToolTip(squadron_replenishment_rate_info)

        layout.addWidget(squadron_replenishment_rate_label, 3, 0)
        layout.addWidget(self.squadron_replenishment_rate, 3, 1, Qt.AlignRight)
コード例 #16
0
 def initUI(self):
     cbox = QCheckBox('チェックボックス', self)
     cbox.move(20, 20)
     cbox.toggle()
     cbox.stateChanged.connect(self.checkboxChanged)
コード例 #17
0
    def init_meta_tab(self):
        # Center panels -------------------------------------------------------
        self.groups_list = []

        # Left-side panel: forms
        self.btn_load_meta = QPushButton('Load metafile')
        self.btn_load_meta.setIcon(self.style().standardIcon(QStyle.SP_ArrowDown))
        self.btn_load_meta.clicked.connect(lambda: self.load_meta_file(filename=None))
        self.btn_load_meta.setToolTip("The YAML file with metadata for this conversion.\n"
                                      "You can customize the metadata in the forms below.")
        self.btn_save_meta = QPushButton('Save metafile')
        self.btn_save_meta.setIcon(self.style().standardIcon(QStyle.SP_DriveFDIcon))
        self.btn_save_meta.clicked.connect(self.save_meta_file)
        self.btn_run_conversion = QPushButton('Run conversion')
        self.btn_run_conversion.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.btn_run_conversion.clicked.connect(self.run_conversion)
        self.btn_form_editor = QPushButton('Form -> Editor')
        self.btn_form_editor.clicked.connect(self.form_to_editor)

        self.lbl_nwb_file = QLabel('Output nwb file:')
        self.lbl_nwb_file.setToolTip("Path to the NWB file that will be created.")
        self.lin_nwb_file = QLineEdit('')
        if self.nwbfile_loc is not None:
            self.lin_nwb_file = QLineEdit(self.nwbfile_loc)
        self.btn_nwb_file = QPushButton()
        self.btn_nwb_file.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))
        self.btn_nwb_file.clicked.connect(self.load_nwb_file)

        l_grid1 = QGridLayout()
        l_grid1.setColumnStretch(3, 1)
        l_grid1.addWidget(self.btn_load_meta, 0, 0, 1, 1)
        l_grid1.addWidget(self.btn_save_meta, 0, 1, 1, 1)
        l_grid1.addWidget(self.btn_run_conversion, 0, 2, 1, 1)
        l_grid1.addWidget(QLabel(), 0, 3, 1, 1)
        l_grid1.addWidget(self.btn_form_editor, 0, 4, 1, 2)
        l_grid1.addWidget(self.lbl_nwb_file, 1, 0, 1, 1)
        l_grid1.addWidget(self.lin_nwb_file, 1, 1, 1, 3)
        l_grid1.addWidget(self.btn_nwb_file, 1, 4, 1, 1)

        # Adds custom files/dir paths fields
        if self.source_paths is None:
            self.lbl_source_file = QLabel('source files:')
            self.lin_source_file = QLineEdit('')
            self.btn_source_file = QPushButton()
            self.btn_source_file.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))
            self.btn_source_file.clicked.connect(self.load_source_files)
            l_grid1.addWidget(self.lbl_source_file, 3, 0, 1, 1)
            l_grid1.addWidget(self.lin_source_file, 3, 1, 1, 3)
            l_grid1.addWidget(self.btn_source_file, 3, 4, 1, 1)
        else:
            self.group_source_paths = QGroupBox('Source paths')
            self.grid_source = QGridLayout()
            self.grid_source.setColumnStretch(3, 1)
            ii = -1
            for k, v in self.source_paths.items():
                ii += 1
                lbl_src = QLabel(k + ':')
                setattr(self, 'lbl_src_' + str(ii), lbl_src)
                lin_src = QLineEdit(v['path'])
                setattr(self, 'lin_src_' + str(ii), lin_src)
                btn_src = QPushButton()
                btn_src.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton))
                setattr(self, 'btn_src_' + str(ii), btn_src)
                if v['type'] == 'file':
                    btn_src.clicked.connect((lambda x: lambda: self.load_source_files(x[0], x[1]))([ii, k]))
                else:
                    btn_src.clicked.connect((lambda x: lambda: self.load_source_dir(x[0], x[1]))([ii, k]))
                self.grid_source.addWidget(lbl_src, ii, 0, 1, 1)
                self.grid_source.addWidget(lin_src, ii, 1, 1, 3)
                self.grid_source.addWidget(btn_src, ii, 4, 1, 1)
            self.group_source_paths.setLayout(self.grid_source)
            l_grid1.addWidget(self.group_source_paths, 3, 0, 1, 6)

        # Adds custom kwargs checkboxes
        if self.kwargs_fields:
            self.group_kwargs = QGroupBox('KWARGS')
            self.grid_kwargs = QGridLayout()
            self.grid_kwargs.setColumnStretch(4, 1)
            ii = -1
            for k, v in self.kwargs_fields.items():
                ii += 1
                chk_kwargs = QCheckBox(k)
                chk_kwargs.setChecked(v)
                chk_kwargs.clicked.connect((lambda x: lambda: self.update_kwargs(x[0], x[1]))([ii, k]))
                setattr(self, 'chk_kwargs_' + str(ii), chk_kwargs)
                self.grid_kwargs.addWidget(chk_kwargs, ii // 4, ii % 4, 1, 1)
            self.group_kwargs.setLayout(self.grid_kwargs)
            l_grid1.addWidget(self.group_kwargs, 4, 0, 1, 6)

        self.l_vbox1 = QVBoxLayout()
        self.l_vbox1.addStretch()
        scroll_aux = QWidget()
        scroll_aux.setLayout(self.l_vbox1)
        l_scroll = QScrollArea()
        l_scroll.setWidget(scroll_aux)
        l_scroll.setWidgetResizable(True)

        self.l_vbox2 = QVBoxLayout()
        self.l_vbox2.addLayout(l_grid1)
        self.l_vbox2.addWidget(l_scroll)

        # Right-side panel
        # Metadata text
        editor_label = QLabel('Metafile preview:')
        r_grid1 = QGridLayout()
        r_grid1.setColumnStretch(1, 1)
        r_grid1.addWidget(editor_label, 0, 0, 1, 1)
        r_grid1.addWidget(QLabel(), 0, 1, 1, 1)
        self.editor = QTextEdit()
        r_vbox1 = QVBoxLayout()
        r_vbox1.addLayout(r_grid1)
        r_vbox1.addWidget(self.editor)

        # Logger
        log_label = QLabel('Log:')
        r_grid2 = QGridLayout()
        r_grid2.setColumnStretch(1, 1)
        r_grid2.addWidget(log_label, 0, 0, 1, 1)
        r_grid2.addWidget(QLabel(), 0, 1, 1, 1)
        self.logger = QTextEdit()
        self.logger.setReadOnly(True)
        r_vbox2 = QVBoxLayout()
        r_vbox2.addLayout(r_grid2)
        r_vbox2.addWidget(self.logger)

        r_vsplitter = QSplitter(QtCore.Qt.Vertical)
        ru_w = QWidget()
        ru_w.setLayout(r_vbox1)
        rb_w = QWidget()
        rb_w.setLayout(r_vbox2)
        r_vsplitter.addWidget(ru_w)
        r_vsplitter.addWidget(rb_w)

        # Metadata/conversion tab Layout
        self.left_w = QWidget()
        self.left_w.setLayout(self.l_vbox2)
        self.splitter = QSplitter(QtCore.Qt.Horizontal)
        self.splitter.addWidget(self.left_w)
        self.splitter.addWidget(r_vsplitter)

        self.metadata_layout = QVBoxLayout()
        self.metadata_layout.addWidget(self.splitter)
        self.tab_metadata = QWidget()
        self.tab_metadata.setLayout(self.metadata_layout)
        self.tabs.addTab(self.tab_metadata, 'Metadata/Conversion')

        # Background color
        p = self.palette()
        p.setColor(self.backgroundRole(), QtCore.Qt.white)
        self.setPalette(p)
コード例 #18
0
class FilterDock(QDockWidget):

    def __init__(self, platforms, regions, genres, years):
        super(FilterDock, self).__init__()

        # QDockWidget settings
        self.setAllowedAreas(Qt.BottomDockWidgetArea)
        self.setFeatures(QDockWidget.DockWidgetClosable)
        self.setFixedHeight(150)
        self.setVisible(False)
        self.setWindowTitle("Filter options")

        # The selected items for each widget are saved in a set-dictionary
        self._selections = defaultdict(set)

        #  Widget settings
        # Platform widgets
        self._platformLabel = QLabel("Platform")
        self._platforms = QListWidget()
        self._platforms.addItems(platforms)
        self._platforms.setSelectionMode(QAbstractItemView.MultiSelection)
        self._platforms.setMaximumWidth(200)
        self._platformVBox = QVBoxLayout()
        self._platformVBox.addWidget(self._platformLabel, 0)
        self._platformVBox.addWidget(self._platforms, 1)

        # Region widgets
        self._regionLabel = QLabel("Region")
        self._regions = QListWidget()
        self._regions.addItems(regions)
        self._regions.setSelectionMode(QAbstractItemView.MultiSelection)
        self._regions.setMaximumWidth(200)
        self._regionVBox = QVBoxLayout()
        self._regionVBox.addWidget(self._regionLabel, 0)
        self._regionVBox.addWidget(self._regions, 1)

        # Genre widgets
        self._genreLabel = QLabel("Genre")
        self._genres = QListWidget()
        self._genres.addItems(genres)
        self._genres.setSelectionMode(QAbstractItemView.MultiSelection)
        self._genres.setMaximumWidth(300)
        self._genreVBox = QVBoxLayout()
        self._genreVBox.addWidget(self._genreLabel, 0)
        self._genreVBox.addWidget(self._genres, 1)

        # Year widgets
        self._yearLabel = QLabel("Year")
        self._years = QListWidget()
        self._years.addItems(years)
        self._years.setSelectionMode(QAbstractItemView.MultiSelection)
        self._years.setMaximumWidth(75)
        self._yearsVbox = QVBoxLayout()
        self._yearsVbox.addWidget(self._yearLabel, 0)
        self._yearsVbox.addWidget(self._years, 1)

        # Inventory widgets
        self._itemType = {1: "Game", 2: "Console", 3: "Accessory"}
        self._item = QCheckBox(self._itemType[1])
        self._item.setTristate(True)
        self._item.setCheckState(Qt.PartiallyChecked)
        self._manual = QCheckBox("Manual")
        self._manual.setTristate(True)
        self._manual.setCheckState(Qt.PartiallyChecked)
        self._box = QCheckBox("Box")
        self._box.setTristate(True)
        self._box.setCheckState(Qt.PartiallyChecked)
        self._inventoryLabelsVBox = QVBoxLayout()
        self._inventorySelectionsVBox = QVBoxLayout()
        self._inventorySelectionsVBox.addStretch(3)
        self._inventorySelectionsVBox.addWidget(self._item, 0)
        self._inventorySelectionsVBox.addWidget(self._box, 1)
        self._inventorySelectionsVBox.addWidget(self._manual, 2)
        self._inventorySelectionsVBox.setAlignment(Qt.AlignLeft)
        self._haveHBox = QHBoxLayout()
        self._haveHBox.addLayout(self._inventoryLabelsVBox, 0)
        self._haveHBox.addLayout(self._inventorySelectionsVBox, 1)
        self._inventoryGroup = QGroupBox("Inventory")
        self._inventoryGroup.setMaximumWidth(120)
        self._inventoryGroup.setLayout(self._haveHBox)

        # Clear and Apply button widgets
        self._clearBtn = QPushButton("Clear selection")
        self._clearBtn.setMaximumSize(self._clearBtn.sizeHint())
        self._clearBtn.clicked.connect(self._clearFilters)
        self._btnHBox = QHBoxLayout()
        self._btnHBox.setAlignment(Qt.AlignBottom | Qt.AlignRight)
        self._btnHBox.addWidget(self._clearBtn, 0)

        # General layout
        mainHBox = QHBoxLayout()
        mainHBox.setAlignment(Qt.AlignLeft)
        mainHBox.addLayout(self._platformVBox, 0)
        mainHBox.addLayout(self._regionVBox, 0)
        mainHBox.addLayout(self._genreVBox, 0)
        mainHBox.addLayout(self._yearsVbox, 0)
        mainHBox.addWidget(self._inventoryGroup, 0)
        mainHBox.addLayout(self._btnHBox, 0)
        mainWidget = QWidget()
        mainWidget.setLayout(mainHBox)
        self.setWidget(mainWidget)

    def _clearFilters(self):
        self._platforms.clearSelection()
        self._regions.clearSelection()
        self._genres.clearSelection()
        self._years.clearSelection()
        self._item.setCheckState(Qt.PartiallyChecked)
        self._box.setCheckState(Qt.PartiallyChecked)
        self._manual.setCheckState(Qt.PartiallyChecked)
        logger.info("Cleared all filters.")

    def getSelections(self):
        self._selections = defaultdict(set)  # Reset selections
        if len(self._platforms.selectedItems()) > 0:
            platforms = [x.text() for x in self._platforms.selectedItems()]
            for platform in platforms:
                self._selections["Platform"].add(platform)
        if len(self._regions.selectedItems()) > 0:
            regions = [x.text() for x in self._regions.selectedItems()]
            for region in regions:
                self._selections["Region"].add(region)
        if len(self._genres.selectedItems()) > 0:
            genres = [x.text() for x in self._genres.selectedItems()]
            for genre in genres:
                self._selections["Genre"].add(genre)
        if len(self._years.selectedItems()) > 0:
            years = [x.text() for x in self._years.selectedItems()]
            for year in years:
                self._selections["Year"].add(year)
        if self._item.checkState() is not Qt.PartiallyChecked:
            self._selections[self._item.text()].add("Yes" if self._item.isChecked() else "No")
        if self._manual.checkState() is not Qt.PartiallyChecked:
            self._selections["Manual"].add("Yes" if self._manual.isChecked() else "No")
        if self._box.checkState() is not Qt.PartiallyChecked:
            self._selections["Box"].add("Yes" if self._box.isChecked() else "No")

        return self._selections

    def setItemType(self, itemType: int):
        if 0 < itemType < 4:
            if self._item.text() in self._selections:
                # Delete previous item entry so we don't search for the wrong type in the wrong table
                del self._selections[self._item.text()]
            self._item.setText(self._itemType[itemType])

    def toggleVisibility(self):
        self.setVisible(False if self.isVisible() else True)

    def updatePlatforms(self, platforms):
        self._platforms.clear()
        self._platforms.addItems(platforms)
        logger.info("Updated platforms list.")

    def updateRegions(self, regions):
        self._regions.clear()
        self._regions.addItems(regions)
        logger.info("Updated regions list.")

    def updateGenres(self, genres):
        self._genres.clear()
        self._genres.addItems(genres)
        logger.info("Updated genres list.")

    def updateYears(self, years):
        self._years.clear()
        self._years.addItems(years)
        logger.info("Updated years list.")
コード例 #19
0
    def __init__(self, platforms, regions, genres, years):
        super(FilterDock, self).__init__()

        # QDockWidget settings
        self.setAllowedAreas(Qt.BottomDockWidgetArea)
        self.setFeatures(QDockWidget.DockWidgetClosable)
        self.setFixedHeight(150)
        self.setVisible(False)
        self.setWindowTitle("Filter options")

        # The selected items for each widget are saved in a set-dictionary
        self._selections = defaultdict(set)

        #  Widget settings
        # Platform widgets
        self._platformLabel = QLabel("Platform")
        self._platforms = QListWidget()
        self._platforms.addItems(platforms)
        self._platforms.setSelectionMode(QAbstractItemView.MultiSelection)
        self._platforms.setMaximumWidth(200)
        self._platformVBox = QVBoxLayout()
        self._platformVBox.addWidget(self._platformLabel, 0)
        self._platformVBox.addWidget(self._platforms, 1)

        # Region widgets
        self._regionLabel = QLabel("Region")
        self._regions = QListWidget()
        self._regions.addItems(regions)
        self._regions.setSelectionMode(QAbstractItemView.MultiSelection)
        self._regions.setMaximumWidth(200)
        self._regionVBox = QVBoxLayout()
        self._regionVBox.addWidget(self._regionLabel, 0)
        self._regionVBox.addWidget(self._regions, 1)

        # Genre widgets
        self._genreLabel = QLabel("Genre")
        self._genres = QListWidget()
        self._genres.addItems(genres)
        self._genres.setSelectionMode(QAbstractItemView.MultiSelection)
        self._genres.setMaximumWidth(300)
        self._genreVBox = QVBoxLayout()
        self._genreVBox.addWidget(self._genreLabel, 0)
        self._genreVBox.addWidget(self._genres, 1)

        # Year widgets
        self._yearLabel = QLabel("Year")
        self._years = QListWidget()
        self._years.addItems(years)
        self._years.setSelectionMode(QAbstractItemView.MultiSelection)
        self._years.setMaximumWidth(75)
        self._yearsVbox = QVBoxLayout()
        self._yearsVbox.addWidget(self._yearLabel, 0)
        self._yearsVbox.addWidget(self._years, 1)

        # Inventory widgets
        self._itemType = {1: "Game", 2: "Console", 3: "Accessory"}
        self._item = QCheckBox(self._itemType[1])
        self._item.setTristate(True)
        self._item.setCheckState(Qt.PartiallyChecked)
        self._manual = QCheckBox("Manual")
        self._manual.setTristate(True)
        self._manual.setCheckState(Qt.PartiallyChecked)
        self._box = QCheckBox("Box")
        self._box.setTristate(True)
        self._box.setCheckState(Qt.PartiallyChecked)
        self._inventoryLabelsVBox = QVBoxLayout()
        self._inventorySelectionsVBox = QVBoxLayout()
        self._inventorySelectionsVBox.addStretch(3)
        self._inventorySelectionsVBox.addWidget(self._item, 0)
        self._inventorySelectionsVBox.addWidget(self._box, 1)
        self._inventorySelectionsVBox.addWidget(self._manual, 2)
        self._inventorySelectionsVBox.setAlignment(Qt.AlignLeft)
        self._haveHBox = QHBoxLayout()
        self._haveHBox.addLayout(self._inventoryLabelsVBox, 0)
        self._haveHBox.addLayout(self._inventorySelectionsVBox, 1)
        self._inventoryGroup = QGroupBox("Inventory")
        self._inventoryGroup.setMaximumWidth(120)
        self._inventoryGroup.setLayout(self._haveHBox)

        # Clear and Apply button widgets
        self._clearBtn = QPushButton("Clear selection")
        self._clearBtn.setMaximumSize(self._clearBtn.sizeHint())
        self._clearBtn.clicked.connect(self._clearFilters)
        self._btnHBox = QHBoxLayout()
        self._btnHBox.setAlignment(Qt.AlignBottom | Qt.AlignRight)
        self._btnHBox.addWidget(self._clearBtn, 0)

        # General layout
        mainHBox = QHBoxLayout()
        mainHBox.setAlignment(Qt.AlignLeft)
        mainHBox.addLayout(self._platformVBox, 0)
        mainHBox.addLayout(self._regionVBox, 0)
        mainHBox.addLayout(self._genreVBox, 0)
        mainHBox.addLayout(self._yearsVbox, 0)
        mainHBox.addWidget(self._inventoryGroup, 0)
        mainHBox.addLayout(self._btnHBox, 0)
        mainWidget = QWidget()
        mainWidget.setLayout(mainHBox)
        self.setWidget(mainWidget)
コード例 #20
0
    def __init__(self, game: Game) -> None:
        super().__init__("HQ Automation")
        self.game = game

        layout = QGridLayout()
        self.setLayout(layout)

        runway_repair = QCheckBox()
        runway_repair.setChecked(self.game.settings.automate_runway_repair)
        runway_repair.toggled.connect(self.set_runway_automation)

        layout.addWidget(QLabel("Automate runway repairs"), 0, 0)
        layout.addWidget(runway_repair, 0, 1, Qt.AlignRight)

        front_line = QCheckBox()
        front_line.setChecked(self.game.settings.automate_front_line_reinforcements)
        front_line.toggled.connect(self.set_front_line_automation)

        layout.addWidget(QLabel("Automate front-line purchases"), 1, 0)
        layout.addWidget(front_line, 1, 1, Qt.AlignRight)

        self.automate_aircraft_reinforcements = QCheckBox()
        self.automate_aircraft_reinforcements.setChecked(
            self.game.settings.automate_aircraft_reinforcements
        )
        self.automate_aircraft_reinforcements.toggled.connect(
            self.set_aircraft_automation
        )

        layout.addWidget(QLabel("Automate aircraft purchases"), 2, 0)
        layout.addWidget(self.automate_aircraft_reinforcements, 2, 1, Qt.AlignRight)

        self.auto_ato_behavior = AutoAtoBehaviorSelector(
            self.game.settings.auto_ato_behavior
        )
        self.auto_ato_behavior.currentIndexChanged.connect(self.set_auto_ato_behavior)
        layout.addWidget(
            QLabel(
                "Automatic package planning behavior<br>"
                "<strong>Aircraft auto-purchase is directed by the auto-planner,<br />"
                "so disabling auto-planning disables auto-purchase.</strong>"
            ),
            3,
            0,
        )
        layout.addWidget(self.auto_ato_behavior, 3, 1)

        self.auto_ato_player_missions_asap = QCheckBox()
        self.auto_ato_player_missions_asap.setChecked(
            self.game.settings.auto_ato_player_missions_asap
        )
        self.auto_ato_player_missions_asap.toggled.connect(
            self.set_auto_ato_player_missions_asap
        )

        layout.addWidget(
            QLabel("Automatically generated packages with players are scheduled ASAP"),
            4,
            0,
        )
        layout.addWidget(self.auto_ato_player_missions_asap, 4, 1, Qt.AlignRight)
コード例 #21
0
    def __init__(self):
        super(Window, self).__init__()

        self.renderArea = RenderArea()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.setWindowTitle("Basic Drawing")
コード例 #22
0
class QTgoLayoutGroupRow(QWidget):
    group_template_changed = Signal()

    def __init__(self, force_group: ForceGroup, group: TgoLayoutGroup) -> None:
        super().__init__()
        self.grid_layout = QGridLayout()
        self.setLayout(self.grid_layout)
        self.grid_layout.setColumnStretch(0, 100)
        self.amount_selector = QSpinBox()
        self.unit_selector = QComboBox()
        self.unit_selector.setMinimumWidth(250)
        self.group_selector = QCheckBox()

        # Add all possible units with the price
        for unit_type in force_group.unit_types_for_group(group):
            self.unit_selector.addItem(
                f"{unit_type.name} [${unit_type.price}M]",
                userData=(unit_type.dcs_unit_type, unit_type.price),
            )
        # Add all possible statics with price = 0
        for static_type in force_group.statics_for_group(group):
            self.unit_selector.addItem(f"{static_type} (Static)",
                                       userData=(static_type, 0))

        if self.unit_selector.count() == 0:
            raise LayoutException("No units available for the TgoLayoutGroup")

        self.unit_selector.adjustSize()
        self.unit_selector.setEnabled(self.unit_selector.count() > 1)
        self.grid_layout.addWidget(self.unit_selector,
                                   0,
                                   0,
                                   alignment=Qt.AlignRight)
        self.grid_layout.addWidget(self.amount_selector,
                                   0,
                                   1,
                                   alignment=Qt.AlignRight)

        dcs_unit_type, price = self.unit_selector.itemData(
            self.unit_selector.currentIndex())

        self.group_layout = QTgoLayoutGroup(group, dcs_unit_type,
                                            group.group_size, price)

        self.group_selector.setChecked(self.group_layout.enabled)
        self.group_selector.setEnabled(self.group_layout.layout.optional)

        self.amount_selector.setMinimum(1)
        self.amount_selector.setMaximum(self.group_layout.layout.max_size)
        self.amount_selector.setValue(self.group_layout.amount)
        self.amount_selector.setEnabled(self.group_layout.layout.max_size > 1)

        self.grid_layout.addWidget(self.group_selector,
                                   0,
                                   2,
                                   alignment=Qt.AlignRight)

        self.amount_selector.valueChanged.connect(self.on_group_changed)
        self.unit_selector.currentIndexChanged.connect(self.on_group_changed)
        self.group_selector.stateChanged.connect(self.on_group_changed)

    def on_group_changed(self) -> None:
        self.group_layout.enabled = self.group_selector.isChecked()
        unit_type, price = self.unit_selector.itemData(
            self.unit_selector.currentIndex())
        self.group_layout.dcs_unit_type = unit_type
        self.group_layout.unit_price = price
        self.group_layout.amount = self.amount_selector.value()
        self.group_template_changed.emit()
コード例 #23
0
    def initGeneratorLayout(self):
        self.generatorPage = QWidget()
        self.generatorLayout = QVBoxLayout()
        self.generatorLayout.setAlignment(Qt.AlignTop)
        self.generatorPage.setLayout(self.generatorLayout)

        self.gameplay = QGroupBox("Gameplay")
        self.gameplayLayout = QGridLayout()
        self.gameplayLayout.setAlignment(Qt.AlignTop)
        self.gameplay.setLayout(self.gameplayLayout)

        self.supercarrier = QCheckBox()
        self.supercarrier.setChecked(self.game.settings.supercarrier)
        self.supercarrier.toggled.connect(self.applySettings)

        self.generate_marks = QCheckBox()
        self.generate_marks.setChecked(self.game.settings.generate_marks)
        self.generate_marks.toggled.connect(self.applySettings)

        self.generate_dark_kneeboard = QCheckBox()
        self.generate_dark_kneeboard.setChecked(
            self.game.settings.generate_dark_kneeboard
        )
        self.generate_dark_kneeboard.toggled.connect(self.applySettings)

        self.never_delay_players = QCheckBox()
        self.never_delay_players.setChecked(
            self.game.settings.never_delay_player_flights
        )
        self.never_delay_players.toggled.connect(self.applySettings)
        self.never_delay_players.setToolTip(
            "When checked, player flights with a delayed start time will be "
            "spawned immediately. AI wingmen may begin startup immediately."
        )

        self.desired_player_mission_duration = TimeInputs(
            "Desired mission duration",
            self.game.settings.desired_player_mission_duration,
        )
        self.desired_player_mission_duration.spinner.valueChanged.connect(
            self.applySettings
        )

        self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0)
        self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"), 1, 0)
        self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight)

        dark_kneeboard_label = QLabel(
            "Generate Dark Kneeboard <br />"
            "<strong>Dark kneeboard for night missions.<br />"
            "This will likely make the kneeboard on the pilot leg unreadable.</strong>"
        )
        self.gameplayLayout.addWidget(dark_kneeboard_label, 2, 0)
        self.gameplayLayout.addWidget(self.generate_dark_kneeboard, 2, 1, Qt.AlignRight)
        self.gameplayLayout.addLayout(
            self.desired_player_mission_duration, 5, 0, Qt.AlignRight
        )

        spawn_players_immediately_tooltip = (
            "Always spawns player aircraft immediately, even if their start time is "
            "more than 10 minutes after the start of the mission. <strong>This does "
            "not alter the timing of your mission. Your TOT will not change. This "
            "option only allows the player to wait on the ground.</strong>"
        )
        spawn_immediately_label = QLabel(
            "Player flights ignore TOT and spawn immediately<br />"
            "<strong>Does not adjust package waypoint times.<br />"
            "Should not be used if players have runway or in-air starts.</strong>"
        )
        spawn_immediately_label.setToolTip(spawn_players_immediately_tooltip)
        self.gameplayLayout.addWidget(spawn_immediately_label, 3, 0)
        self.gameplayLayout.addWidget(self.never_delay_players, 3, 1, Qt.AlignRight)

        start_type_label = QLabel(
            "Default start type for AI aircraft<br /><strong>Warning: "
            "Options other than Cold will significantly reduce the<br />"
            "number of targets available for OCA/Aircraft missions,<br />"
            "and OCA/Aircraft flights will not be included in<br />"
            "automatically planned OCA packages.</strong>"
        )
        start_type_label.setToolTip(START_TYPE_TOOLTIP)
        start_type = StartTypeComboBox(self.game.settings)
        start_type.setCurrentText(self.game.settings.default_start_type)

        self.gameplayLayout.addWidget(start_type_label, 4, 0)
        self.gameplayLayout.addWidget(start_type, 4, 1)

        self.performance = QGroupBox("Performance")
        self.performanceLayout = QGridLayout()
        self.performanceLayout.setAlignment(Qt.AlignTop)
        self.performance.setLayout(self.performanceLayout)

        self.smoke = QCheckBox()
        self.smoke.setChecked(self.game.settings.perf_smoke_gen)
        self.smoke.toggled.connect(self.applySettings)

        self.smoke_spacing = QSpinBox()
        self.smoke_spacing.setMinimum(800)
        self.smoke_spacing.setMaximum(24000)
        self.smoke_spacing.setValue(self.game.settings.perf_smoke_spacing)
        self.smoke_spacing.valueChanged.connect(self.applySettings)

        self.red_alert = QCheckBox()
        self.red_alert.setChecked(self.game.settings.perf_red_alert_state)
        self.red_alert.toggled.connect(self.applySettings)

        self.arti = QCheckBox()
        self.arti.setChecked(self.game.settings.perf_artillery)
        self.arti.toggled.connect(self.applySettings)

        self.moving_units = QCheckBox()
        self.moving_units.setChecked(self.game.settings.perf_moving_units)
        self.moving_units.toggled.connect(self.applySettings)

        self.infantry = QCheckBox()
        self.infantry.setChecked(self.game.settings.perf_infantry)
        self.infantry.toggled.connect(self.applySettings)

        self.destroyed_units = QCheckBox()
        self.destroyed_units.setChecked(self.game.settings.perf_destroyed_units)
        self.destroyed_units.toggled.connect(self.applySettings)

        self.culling = QCheckBox()
        self.culling.setChecked(self.game.settings.perf_culling)
        self.culling.toggled.connect(self.applySettings)

        self.culling_distance = QSpinBox()
        self.culling_distance.setMinimum(10)
        self.culling_distance.setMaximum(10000)
        self.culling_distance.setValue(self.game.settings.perf_culling_distance)
        self.culling_distance.valueChanged.connect(self.applySettings)

        self.culling_do_not_cull_carrier = QCheckBox()
        self.culling_do_not_cull_carrier.setChecked(
            self.game.settings.perf_do_not_cull_carrier
        )
        self.culling_do_not_cull_carrier.toggled.connect(self.applySettings)

        self.performanceLayout.addWidget(
            QLabel("Smoke visual effect on frontline"), 0, 0
        )
        self.performanceLayout.addWidget(self.smoke, 0, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Smoke generator spacing (higher means less smoke)"),
            1,
            0,
            alignment=Qt.AlignRight,
        )
        self.performanceLayout.addWidget(
            self.smoke_spacing, 1, 1, alignment=Qt.AlignRight
        )
        self.performanceLayout.addWidget(QLabel("SAM starts in RED alert mode"), 2, 0)
        self.performanceLayout.addWidget(self.red_alert, 2, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Artillery strikes"), 3, 0)
        self.performanceLayout.addWidget(self.arti, 3, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Moving ground units"), 4, 0)
        self.performanceLayout.addWidget(
            self.moving_units, 4, 1, alignment=Qt.AlignRight
        )
        self.performanceLayout.addWidget(
            QLabel("Generate infantry squads along vehicles"), 5, 0
        )
        self.performanceLayout.addWidget(self.infantry, 5, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Include destroyed units carcass"), 6, 0
        )
        self.performanceLayout.addWidget(
            self.destroyed_units, 6, 1, alignment=Qt.AlignRight
        )

        self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1, 2)
        self.performanceLayout.addWidget(
            QLabel("Culling of distant units enabled"), 8, 0
        )
        self.performanceLayout.addWidget(self.culling, 8, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0)
        self.performanceLayout.addWidget(
            self.culling_distance, 9, 1, alignment=Qt.AlignRight
        )
        self.performanceLayout.addWidget(
            QLabel("Do not cull carrier's surroundings"), 10, 0
        )
        self.performanceLayout.addWidget(
            self.culling_do_not_cull_carrier, 10, 1, alignment=Qt.AlignRight
        )

        self.generatorLayout.addWidget(self.gameplay)
        self.generatorLayout.addWidget(
            QLabel(
                "Disabling settings below may improve performance, but will impact the overall quality of the experience."
            )
        )
        self.generatorLayout.addWidget(self.performance)
コード例 #24
0
class MainWindow(QMainWindow):
    def __init__(self, app_context):
        super(MainWindow, self).__init__()
        self.app_context = app_context
        self.title = 'Melbourne'

        self.contest = None
        self.thread = None

        self._init_window()
        self._init_layout()
        self._init_menus()

    def _init_window(self):
        self.setWindowTitle(self.title)

        # Set Window Size
        if fbs_runtime.platform.is_windows():
            self.setMaximumSize(600, 560)
            self.setMinimumSize(600, 560)
            self.resize(600, 560)
        else:
            self.setMaximumSize(500, 300)
            self.setMinimumSize(500, 300)
            self.resize(500, 300)

    def _init_menus(self):
        menu = self.menuBar()

        file_menu = menu.addMenu('&File')

        input_file_action = QAction("Select Input File", self)
        input_file_action.triggered.connect(self._set_input_file)
        input_file_action.setShortcut(QKeySequence.Open)

        output_folder_action = QAction("Select Output Folder", self)
        output_folder_action.triggered.connect(self._set_output_folder)
        output_folder_action.setShortcut(QKeySequence("Ctrl+Shift+O"))

        reload_contest_action = QAction("Reload Contest Details", self)
        reload_contest_action.triggered.connect(self._reload_contest)
        reload_contest_action.setShortcut(QKeySequence("Ctrl+R"))

        file_menu.addAction(input_file_action)
        file_menu.addAction(output_folder_action)
        file_menu.addAction(reload_contest_action)

        help_menu = self.menuBar().addMenu("&Help")
        about_action = QAction("&About", self)
        about_action.triggered.connect(self._show_about_dialog)
        help_menu.addAction(about_action)

    def _init_layout(self):
        # File Details Grid
        file_details_grid = QGridLayout()
        file_details_grid.setColumnStretch(1, 2)

        self.input_file_btn = QPushButton(
            qta.icon('fa5.file-excel', color="#2E7D32"), ' Input File')
        self.input_file_btn.setDefault(False)
        self.input_file_btn.setAutoDefault(False)
        self.input_file_btn.clicked.connect(self._set_input_file)
        self.input_file_le = QLineEdit()
        self.input_file_le.setReadOnly(True)
        self.input_file_le.textChanged.connect(self._check_if_ready)
        self.output_folder_btn = QPushButton(
            qta.icon('fa5s.folder', color="#0277BD"), ' Output Folder')
        self.output_folder_btn.setDefault(False)
        self.output_folder_btn.setAutoDefault(False)
        self.output_folder_btn.clicked.connect(self._set_output_folder)
        self.output_folder_le = QLineEdit()
        self.output_folder_le.setReadOnly(True)
        self.output_folder_le.textChanged.connect(self._check_if_ready)

        file_details_grid.addWidget(self.input_file_btn, 0, 0)
        file_details_grid.addWidget(self.input_file_le, 0, 1)
        file_details_grid.addWidget(self.output_folder_btn, 1, 0)
        file_details_grid.addWidget(self.output_folder_le, 1, 1)
        file_details_group = QGroupBox('File Details')
        file_details_group.setLayout(file_details_grid)

        # Scoreboard Details Grid
        scoreboard_details_grid = QGridLayout()
        scoreboard_details_grid.setColumnStretch(2, 2)

        self.scoreboard_title_le = QLineEdit()
        self.scoreboard_title_le.textChanged.connect(self._check_if_ready)
        self.accent_color_btn = QPushButton(
            qta.icon('fa5s.brush', color=DEFAULT_ACCENT_COLOR),
            ' Accent Color')
        self.accent_color_btn.setDefault(False)
        self.accent_color_btn.setAutoDefault(False)
        self.accent_color_btn.clicked.connect(self._set_accent_color)
        self.reset_accent_color_btn = QPushButton(
            qta.icon('fa5s.redo-alt', color="#212121"), ' Reset')
        self.reset_accent_color_btn.setDefault(False)
        self.reset_accent_color_btn.setAutoDefault(False)
        self.reset_accent_color_btn.clicked.connect(self._reset_accent_color)
        self.accent_color_le = QLineEdit(DEFAULT_ACCENT_COLOR)
        self.accent_color_le.setReadOnly(True)
        self.display_flags_check = QCheckBox('Display Flags')
        self.display_flags_check.setChecked(False)
        self.display_flags_check.stateChanged.connect(self._validate_flags)

        scoreboard_details_grid.addWidget(QLabel('Scoreboard Title'), 0, 0)
        scoreboard_details_grid.addWidget(self.scoreboard_title_le, 0, 1, 1, 2)
        scoreboard_details_grid.addWidget(self.accent_color_btn, 1, 0)
        scoreboard_details_grid.addWidget(self.reset_accent_color_btn, 1, 1)
        scoreboard_details_grid.addWidget(self.accent_color_le, 1, 2)
        scoreboard_details_grid.addWidget(self.display_flags_check, 2, 0, 1, 3)
        scoreboard_details_group = QGroupBox('Scoreboard Details')
        scoreboard_details_group.setLayout(scoreboard_details_grid)

        # Generation Grid
        generation_grid = QGridLayout()
        generation_grid.setColumnStretch(0, 2)

        self.progress_bar = QProgressBar()
        self.generate_btn = QPushButton(qta.icon('fa5s.play', color='#4CAF50'),
                                        ' Generate')
        self.generate_btn.setEnabled(False)
        self.generate_btn.setDefault(False)
        self.generate_btn.setAutoDefault(False)
        self.generate_btn.clicked.connect(self._generate_scoreboards)
        self.cancel_btn = QPushButton(qta.icon('fa5s.stop', color='#F44336'),
                                      ' Cancel')
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.setDefault(False)
        self.cancel_btn.setAutoDefault(False)
        self.cancel_btn.clicked.connect(self._cancel_generation)

        generation_grid.addWidget(self.progress_bar, 0, 0)
        generation_grid.addWidget(self.generate_btn, 0, 1)
        generation_grid.addWidget(self.cancel_btn, 0, 2)

        generation_group = QWidget()
        generation_group.setLayout(generation_grid)

        layout = QVBoxLayout()
        layout.addWidget(file_details_group)
        layout.addWidget(scoreboard_details_group)
        layout.addWidget(generation_group)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

    def _show_about_dialog(self):
        about_dialog = AboutDialog(self.app_context)
        about_dialog.exec_()

    def _set_input_file(self):
        home_directory = expanduser('~')
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.ExistingFile)
        path = dialog.getOpenFileName(self, 'Select Excel Spreadsheet',
                                      home_directory, 'Excel (*.xls, *.xlsx)')
        if path and len(path[0]) > 0:
            self.input_file_le.setText(path[0])
            self._load_contest()

    def _load_contest(self):
        if len(self.input_file_le.text()) > 0:
            try:
                self.contest = Contest.from_file(self.input_file_le.text())
                self._validate_flags()
            except ValueError as err:
                self.input_file_le.setText("")
                self.contest = None
                self._check_if_ready()
                alert = QMessageBox()
                alert.setIcon(QMessageBox.Critical)
                alert.setText("Unable to load contest details from file")
                alert.setWindowTitle("Error Loading Contest")
                alert.setDetailedText("{}".format(err))
                alert.setStandardButtons(QMessageBox.Ok)
                alert.setDefaultButton(QMessageBox.Ok)
                alert.setEscapeButton(QMessageBox.Ok)
                alert.exec_()

    def _reload_contest(self):
        self._load_contest()

        alert = QMessageBox()
        alert.setIcon(QMessageBox.Information)
        alert.setText("Successfully reloaded contest details from file")
        alert.setWindowTitle("Reloaded Contest Details")
        alert.setStandardButtons(QMessageBox.Ok)
        alert.setDefaultButton(QMessageBox.Ok)
        alert.setEscapeButton(QMessageBox.Ok)
        alert.exec_()

    def _set_output_folder(self):
        home_directory = expanduser('~')
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.DirectoryOnly)
        path = dialog.getExistingDirectory(self, 'Select Output Folder',
                                           home_directory,
                                           QFileDialog.ShowDirsOnly)
        if path and len(path) > 0:
            self.output_folder_le.setText(path)

    def _set_accent_color(self):
        color_btn_hex = webcolors.hex_to_rgb(self.accent_color_le.text())
        accent_color = QColor(color_btn_hex.red, color_btn_hex.green,
                              color_btn_hex.blue)

        dialog = QColorDialog()
        dialog.setCurrentColor(accent_color)
        color = dialog.getColor(accent_color, self, "Select Accent Color")
        if color.isValid():
            hex_color = webcolors.rgb_to_hex(
                (color.red(), color.green(), color.blue())).upper()
            self.accent_color_le.setText(hex_color)
            self.accent_color_btn.setIcon(
                qta.icon('fa5s.brush', color=hex_color))

    def _reset_accent_color(self):
        self.accent_color_le.setText(DEFAULT_ACCENT_COLOR)
        self.accent_color_btn.setIcon(
            qta.icon('fa5s.brush', color=DEFAULT_ACCENT_COLOR))

    def _validate_flags(self):
        def get_invalid_flags(self):
            invalid = []
            for flag in [entry.flag for entry in self.contest.entries]:
                try:
                    self.app_context.get_resource(join("flags", flag))
                except FileNotFoundError:
                    invalid.append(flag)
            return invalid

        if self.contest:
            if self.display_flags_check.isChecked():
                invalid_flags = get_invalid_flags(self)
                if invalid_flags:
                    self.display_flags_check.setChecked(False)
                    alert = QMessageBox()
                    alert.setIcon(QMessageBox.Warning)
                    alert.setText(
                        "Invalid flags were specified in the input file.")
                    alert.setWindowTitle("Invalid Flags Specified")
                    alert.setDetailedText('\n'.join(
                        sorted([
                            "{} was not found".format(flag)
                            for flag in invalid_flags
                        ])))
                    alert.setStandardButtons(QMessageBox.Ok)
                    alert.setDefaultButton(QMessageBox.Ok)
                    alert.setEscapeButton(QMessageBox.Ok)
                    alert.exec_()
                    return False
        return True

    def _check_if_ready(self):
        if self.contest and len(self.output_folder_le.text()) > 0 and len(
                self.scoreboard_title_le.text()) > 0:
            self.generate_btn.setEnabled(True)
        else:
            self.generate_btn.setEnabled(False)

    def _generate_scoreboards(self):
        ready_to_generate = self._validate_flags()
        if not ready_to_generate:
            return
        self.progress_bar.setMaximum(self.contest.num_voters)
        self.progress_bar.setValue(0)

        self.thread = ScoreboardThread(
            self.app_context,
            ScoreboardDetails(
                contest=self.contest,
                output_dir=self.output_folder_le.text(),
                title=self.scoreboard_title_le.text(),
                accent_color=self.accent_color_le.text(),
                display_flags=self.display_flags_check.isChecked()))

        self.thread.progress.connect(self._update_progress_bar)
        self.thread.finished.connect(self._finished_generation)
        self.cancel_btn.setEnabled(True)
        self.generate_btn.setEnabled(False)

        self.thread.start()

    def _finished_generation(self):
        self.cancel_btn.setEnabled(False)
        self.generate_btn.setEnabled(True)

    def _cancel_generation(self):
        self.thread.stop()
        self.thread.wait()
        self.progress_bar.setValue(0)
        self.cancel_btn.setEnabled(False)
        self.generate_btn.setEnabled(True)

    def _update_progress_bar(self, voter):
        self.progress_bar.setValue(voter)
コード例 #25
0
    def __init__(self, parent, nodes):
        super(SaveDialog, self).__init__(parent)

        self.all_nodes = nodes
        self.export_nodes = []
        self.nodes_check_box_list = []
        self.export_dir = ''
        self.package_name = ''

        # create UI

        # main layouts and widgets
        self.main_vertical_layout = QVBoxLayout(self)
        self.horizontal_layout = QHBoxLayout(self)
        self.nodes_vertical_layout = QVBoxLayout(self)
        self.nodes_vertical_layout.setAlignment(Qt.AlignTop)
        self.export_widget = QWidget(self)
        self.export_widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
        self.export_layout = QVBoxLayout(self)
        self.export_layout.setAlignment(Qt.AlignTop)
        self.export_widget.setLayout(self.export_layout)

        # nodes selection section
        self.nodes_group_box = QGroupBox(self)

        self.nodes_group_box.setLayout(QVBoxLayout(self))
        self.nodes_group_box.setTitle('Select nodes to export')

        self.nodes_scroll_area = QScrollArea(self)
        nodes_list_widget = QWidget()
        nodes_list_widget.setLayout(self.nodes_vertical_layout)

        for i in range(len(nodes)):
            n = nodes[i]
            node_check_box = QCheckBox(n.title)
            node_check_box.setObjectName('node_check_box_' + str(i))
            node_check_box.setChecked(True)
            self.nodes_vertical_layout.addWidget(node_check_box)
            self.nodes_check_box_list.append(node_check_box)

        self.nodes_scroll_area.setWidget(nodes_list_widget)
        self.nodes_group_box.layout().addWidget(self.nodes_scroll_area)

        # export settings section
        self.select_package_dir_button = QPushButton('Select package dir',
                                                     self)
        self.select_package_dir_button.clicked.connect(self.select_package_dir)

        self.package_dir_label = QLabel('package dir: -')

        self.export_button = QPushButton('export', self)
        self.export_button.clicked.connect(self.export)

        self.export_layout.addWidget(self.select_package_dir_button)
        self.export_layout.addWidget(self.package_dir_label)
        self.export_layout.addWidget(self.export_button)

        # button box
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Ok)
        self.button_box.button(QDialogButtonBox.Ok).clicked.connect(self.close)

        # merge layouts
        self.horizontal_layout.addWidget(self.nodes_group_box)
        self.horizontal_layout.addWidget(self.export_widget)
        self.main_vertical_layout.addLayout(self.horizontal_layout)
        self.main_vertical_layout.addWidget(self.button_box)

        self.setWindowTitle('Export Nodes')
        self.resize(500, 300)
コード例 #26
0
    def _init_layout(self):
        # File Details Grid
        file_details_grid = QGridLayout()
        file_details_grid.setColumnStretch(1, 2)

        self.input_file_btn = QPushButton(
            qta.icon('fa5.file-excel', color="#2E7D32"), ' Input File')
        self.input_file_btn.setDefault(False)
        self.input_file_btn.setAutoDefault(False)
        self.input_file_btn.clicked.connect(self._set_input_file)
        self.input_file_le = QLineEdit()
        self.input_file_le.setReadOnly(True)
        self.input_file_le.textChanged.connect(self._check_if_ready)
        self.output_folder_btn = QPushButton(
            qta.icon('fa5s.folder', color="#0277BD"), ' Output Folder')
        self.output_folder_btn.setDefault(False)
        self.output_folder_btn.setAutoDefault(False)
        self.output_folder_btn.clicked.connect(self._set_output_folder)
        self.output_folder_le = QLineEdit()
        self.output_folder_le.setReadOnly(True)
        self.output_folder_le.textChanged.connect(self._check_if_ready)

        file_details_grid.addWidget(self.input_file_btn, 0, 0)
        file_details_grid.addWidget(self.input_file_le, 0, 1)
        file_details_grid.addWidget(self.output_folder_btn, 1, 0)
        file_details_grid.addWidget(self.output_folder_le, 1, 1)
        file_details_group = QGroupBox('File Details')
        file_details_group.setLayout(file_details_grid)

        # Scoreboard Details Grid
        scoreboard_details_grid = QGridLayout()
        scoreboard_details_grid.setColumnStretch(2, 2)

        self.scoreboard_title_le = QLineEdit()
        self.scoreboard_title_le.textChanged.connect(self._check_if_ready)
        self.accent_color_btn = QPushButton(
            qta.icon('fa5s.brush', color=DEFAULT_ACCENT_COLOR),
            ' Accent Color')
        self.accent_color_btn.setDefault(False)
        self.accent_color_btn.setAutoDefault(False)
        self.accent_color_btn.clicked.connect(self._set_accent_color)
        self.reset_accent_color_btn = QPushButton(
            qta.icon('fa5s.redo-alt', color="#212121"), ' Reset')
        self.reset_accent_color_btn.setDefault(False)
        self.reset_accent_color_btn.setAutoDefault(False)
        self.reset_accent_color_btn.clicked.connect(self._reset_accent_color)
        self.accent_color_le = QLineEdit(DEFAULT_ACCENT_COLOR)
        self.accent_color_le.setReadOnly(True)
        self.display_flags_check = QCheckBox('Display Flags')
        self.display_flags_check.setChecked(False)
        self.display_flags_check.stateChanged.connect(self._validate_flags)

        scoreboard_details_grid.addWidget(QLabel('Scoreboard Title'), 0, 0)
        scoreboard_details_grid.addWidget(self.scoreboard_title_le, 0, 1, 1, 2)
        scoreboard_details_grid.addWidget(self.accent_color_btn, 1, 0)
        scoreboard_details_grid.addWidget(self.reset_accent_color_btn, 1, 1)
        scoreboard_details_grid.addWidget(self.accent_color_le, 1, 2)
        scoreboard_details_grid.addWidget(self.display_flags_check, 2, 0, 1, 3)
        scoreboard_details_group = QGroupBox('Scoreboard Details')
        scoreboard_details_group.setLayout(scoreboard_details_grid)

        # Generation Grid
        generation_grid = QGridLayout()
        generation_grid.setColumnStretch(0, 2)

        self.progress_bar = QProgressBar()
        self.generate_btn = QPushButton(qta.icon('fa5s.play', color='#4CAF50'),
                                        ' Generate')
        self.generate_btn.setEnabled(False)
        self.generate_btn.setDefault(False)
        self.generate_btn.setAutoDefault(False)
        self.generate_btn.clicked.connect(self._generate_scoreboards)
        self.cancel_btn = QPushButton(qta.icon('fa5s.stop', color='#F44336'),
                                      ' Cancel')
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.setDefault(False)
        self.cancel_btn.setAutoDefault(False)
        self.cancel_btn.clicked.connect(self._cancel_generation)

        generation_grid.addWidget(self.progress_bar, 0, 0)
        generation_grid.addWidget(self.generate_btn, 0, 1)
        generation_grid.addWidget(self.cancel_btn, 0, 2)

        generation_group = QWidget()
        generation_group.setLayout(generation_grid)

        layout = QVBoxLayout()
        layout.addWidget(file_details_group)
        layout.addWidget(scoreboard_details_group)
        layout.addWidget(generation_group)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
コード例 #27
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(787, 415)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.base = QFrame(self.centralwidget)
        self.base.setObjectName(u"base")
        self.base.setStyleSheet(u"QFrame{\n"
                                "\n"
                                "	\n"
                                "	background-color: rgb(97, 101, 157);\n"
                                "}")
        self.base.setFrameShape(QFrame.StyledPanel)
        self.base.setFrameShadow(QFrame.Raised)
        self.horizontalLayout = QHBoxLayout(self.base)
        self.horizontalLayout.setSpacing(0)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.frame_for_widgets = QFrame(self.base)
        self.frame_for_widgets.setObjectName(u"frame_for_widgets")
        self.frame_for_widgets.setStyleSheet(
            u"QFrame{\n"
            "\n"
            "border-radius:25px;\n"
            "\n"
            "\n"
            "\n"
            "background-color: rgb(24, 25, 39);\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "\n"
            "}")
        self.frame_for_widgets.setFrameShape(QFrame.NoFrame)
        self.frame_for_widgets.setFrameShadow(QFrame.Raised)
        self.verticalLayout_4 = QVBoxLayout(self.frame_for_widgets)
        self.verticalLayout_4.setSpacing(0)
        self.verticalLayout_4.setObjectName(u"verticalLayout_4")
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.frame = QFrame(self.frame_for_widgets)
        self.frame.setObjectName(u"frame")
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_2 = QHBoxLayout(self.frame)
        self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
        self.select_zip_button = QPushButton(self.frame)
        self.select_zip_button.setObjectName(u"select_zip_button")
        self.select_zip_button.setMinimumSize(QSize(75, 75))
        self.select_zip_button.setMaximumSize(QSize(75, 75))
        font = QFont()
        font.setFamily(u"Segoe UI Light")
        font.setPointSize(24)
        self.select_zip_button.setFont(font)
        self.select_zip_button.setStyleSheet(
            u"QPushButton{\n"
            "	color:rgb(30, 149, 198);\n"
            "	 border: 2px solid black;\n"
            "\n"
            "	border-color:rgb(240, 123, 255);\n"
            "	\n"
            "	background-color: rgb(42, 44, 68);\n"
            "	\n"
            "	border-radius:10px;\n"
            "}\n"
            "QPushButton:hover{\n"
            "\n"
            "\n"
            "border-color:rgb(255, 37, 255);\n"
            "\n"
            "\n"
            "}")

        self.horizontalLayout_2.addWidget(self.select_zip_button)

        self.horizontalSpacer = QSpacerItem(331, 20, QSizePolicy.Expanding,
                                            QSizePolicy.Minimum)

        self.horizontalLayout_2.addItem(self.horizontalSpacer)

        self.verticalLayout_4.addWidget(self.frame)

        self.frame_left_middle = QFrame(self.frame_for_widgets)
        self.frame_left_middle.setObjectName(u"frame_left_middle")
        self.frame_left_middle.setFrameShape(QFrame.StyledPanel)
        self.frame_left_middle.setFrameShadow(QFrame.Raised)
        self.verticalLayout_5 = QVBoxLayout(self.frame_left_middle)
        self.verticalLayout_5.setSpacing(0)
        self.verticalLayout_5.setObjectName(u"verticalLayout_5")
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.frame_left_middle_up = QFrame(self.frame_left_middle)
        self.frame_left_middle_up.setObjectName(u"frame_left_middle_up")
        self.frame_left_middle_up.setFrameShape(QFrame.StyledPanel)
        self.frame_left_middle_up.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_4 = QHBoxLayout(self.frame_left_middle_up)
        self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
        self.label = QLabel(self.frame_left_middle_up)
        self.label.setObjectName(u"label")
        font1 = QFont()
        font1.setFamily(u"Arial Rounded MT Bold")
        font1.setPointSize(11)
        self.label.setFont(font1)
        self.label.setStyleSheet(u"QLabel{\n"
                                 " color:rgb(30, 149, 198);\n"
                                 "\n"
                                 "	\n"
                                 "\n"
                                 "	}")
        self.label.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_3.addWidget(self.label)

        self.lineEdit = QLineEdit(self.frame_left_middle_up)
        self.lineEdit.setObjectName(u"lineEdit")
        self.lineEdit.setStyleSheet(u"QLineEdit{\n"
                                    "color:rgb(30, 149, 198);\n"
                                    "	background-color: rgb(65, 69, 106);\n"
                                    "\n"
                                    "border:2px solid black;\n"
                                    "\n"
                                    "border-radius:3px;\n"
                                    "border-color:rgb(240, 123, 255);\n"
                                    "\n"
                                    "}")

        self.horizontalLayout_3.addWidget(self.lineEdit)

        self.same_as_zip_name_checkbox = QCheckBox(self.frame_left_middle_up)
        self.same_as_zip_name_checkbox.setObjectName(
            u"same_as_zip_name_checkbox")
        font2 = QFont()
        font2.setFamily(u"Arial Rounded MT Bold")
        font2.setPointSize(10)
        self.same_as_zip_name_checkbox.setFont(font2)
        self.same_as_zip_name_checkbox.setStyleSheet(
            u"QCheckBox{\n"
            "color:rgb(30, 149, 198);\n"
            "\n"
            "}\n"
            "QCheckBox:unchecked {\n"
            "   \n"
            "	 color:rgb(30, 149, 198);\n"
            "}\n"
            "QCheckBox::indicator {\n"
            "    width: 13px;\n"
            "    height: 13px;\n"
            "	\n"
            "	color: rgb(30, 149, 198);\n"
            "	background-color: rgb(42, 44, 68);\n"
            "}\n"
            "QCheckBox::indicator:checked {\n"
            "   \n"
            "	\n"
            "	background-color: rgb(192, 98, 204);\n"
            "}\n"
            "QCheckBox:checked {\n"
            "\n"
            "color: rgb(38, 194, 255);\n"
            " \n"
            "}\n"
            "\n"
            "QCheckBox::indicator:checked {\n"
            "color: rgb(253, 111, 54);\n"
            "    \n"
            "}\n"
            "")

        self.horizontalLayout_3.addWidget(self.same_as_zip_name_checkbox)

        self.horizontalLayout_4.addLayout(self.horizontalLayout_3)

        self.horizontalSpacer_2 = QSpacerItem(85, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_4.addItem(self.horizontalSpacer_2)

        self.verticalLayout_5.addWidget(self.frame_left_middle_up)

        self.frame_3 = QFrame(self.frame_left_middle)
        self.frame_3.setObjectName(u"frame_3")
        self.frame_3.setFrameShape(QFrame.StyledPanel)
        self.frame_3.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_6 = QHBoxLayout(self.frame_3)
        self.horizontalLayout_6.setObjectName(u"horizontalLayout_6")
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
        self.label_2 = QLabel(self.frame_3)
        self.label_2.setObjectName(u"label_2")
        self.label_2.setMinimumSize(QSize(100, 0))
        font3 = QFont()
        font3.setFamily(u"Segoe UI")
        font3.setPointSize(12)
        self.label_2.setFont(font3)
        self.label_2.setStyleSheet(u"QLabel{\n"
                                   "\n"
                                   "	\n"
                                   "	\n"
                                   " color:rgb(30, 149, 198);\n"
                                   "\n"
                                   "	\n"
                                   "\n"
                                   "	}")
        self.label_2.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_5.addWidget(self.label_2)

        self.algorithm_combobox = QComboBox(self.frame_3)
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.addItem("")
        self.algorithm_combobox.setObjectName(u"algorithm_combobox")
        self.algorithm_combobox.setMinimumSize(QSize(150, 0))
        font4 = QFont()
        font4.setFamily(u"Segoe UI")
        font4.setPointSize(10)
        font4.setBold(True)
        font4.setWeight(75)
        self.algorithm_combobox.setFont(font4)
        self.algorithm_combobox.setStyleSheet(
            u"QComboBox{\n"
            "\n"
            "	\n"
            "	color:rgb(30, 149, 198);\n"
            "\n"
            "	border:2px solid black;\n"
            "	border-color:rgb(240, 123, 255);\n"
            "	background-color: rgb(42, 44, 68);\n"
            "	\n"
            "\n"
            "}\n"
            "QComboBox::down-arrow {\n"
            "  border:1px solid black;\n"
            "border-color:rgb(30, 149, 198);\n"
            "}\n"
            "\n"
            "ComboBox::drop-down {\n"
            "   \n"
            "	color: rgb(30, 149, 198);\n"
            "	background-color: rgb(56, 58, 91);\n"
            "}\n"
            "\n"
            "\n"
            "QComboBox::down-arrow:on { /* shift the arrow when popup is open */\n"
            "    top: 1px;\n"
            "    left: 1px;\n"
            "}\n"
            "")

        self.horizontalLayout_5.addWidget(self.algorithm_combobox)

        self.horizontalLayout_6.addLayout(self.horizontalLayout_5)

        self.horizontalSpacer_3 = QSpacerItem(146, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_6.addItem(self.horizontalSpacer_3)

        self.verticalLayout_5.addWidget(self.frame_3)

        self.verticalLayout_4.addWidget(self.frame_left_middle)

        self.frame_left_bottom = QFrame(self.frame_for_widgets)
        self.frame_left_bottom.setObjectName(u"frame_left_bottom")
        self.frame_left_bottom.setFrameShape(QFrame.StyledPanel)
        self.frame_left_bottom.setFrameShadow(QFrame.Raised)
        self.verticalLayout_6 = QVBoxLayout(self.frame_left_bottom)
        self.verticalLayout_6.setSpacing(0)
        self.verticalLayout_6.setObjectName(u"verticalLayout_6")
        self.verticalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.frame_for_start_button = QFrame(self.frame_left_bottom)
        self.frame_for_start_button.setObjectName(u"frame_for_start_button")
        self.frame_for_start_button.setFrameShape(QFrame.StyledPanel)
        self.frame_for_start_button.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_8 = QHBoxLayout(self.frame_for_start_button)
        self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
        self.horizontalLayout_7 = QHBoxLayout()
        self.horizontalLayout_7.setObjectName(u"horizontalLayout_7")
        self.label_3 = QLabel(self.frame_for_start_button)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setMinimumSize(QSize(100, 0))
        self.label_3.setFont(font2)
        self.label_3.setStyleSheet(u"QLabel{\n"
                                   "\n"
                                   "	\n"
                                   " color:rgb(30, 149, 198);\n"
                                   "\n"
                                   "	\n"
                                   "\n"
                                   "	}")
        self.label_3.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_7.addWidget(self.label_3)

        self.toolButton = QToolButton(self.frame_for_start_button)
        self.toolButton.setObjectName(u"toolButton")
        self.toolButton.setStyleSheet(u"QToolButton{\n"
                                      "	color:rgb(30, 149, 198);\n"
                                      "	 border: 2px solid black;\n"
                                      "\n"
                                      "	border-color:rgb(240, 123, 255);\n"
                                      "	\n"
                                      "	background-color: rgb(42, 44, 68);\n"
                                      "	\n"
                                      "	border-radius:1px;\n"
                                      "}\n"
                                      "QToolButton:hover{\n"
                                      "\n"
                                      "\n"
                                      "border-color:rgb(255, 37, 255);\n"
                                      "\n"
                                      "\n"
                                      "}")

        self.horizontalLayout_7.addWidget(self.toolButton)

        self.horizontalLayout_8.addLayout(self.horizontalLayout_7)

        self.horizontalSpacer_4 = QSpacerItem(190, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_8.addItem(self.horizontalSpacer_4)

        self.start_button = QPushButton(self.frame_for_start_button)
        self.start_button.setObjectName(u"start_button")
        self.start_button.setMinimumSize(QSize(75, 75))
        font5 = QFont()
        font5.setFamily(u"Segoe UI Light")
        font5.setPointSize(28)
        self.start_button.setFont(font5)
        self.start_button.setStyleSheet(u"QPushButton{\n"
                                        "	color:rgb(30, 149, 198);\n"
                                        "	 border: 2px solid black;\n"
                                        "\n"
                                        "	border-color:rgb(240, 123, 255);\n"
                                        "	\n"
                                        "	background-color: rgb(42, 44, 68);\n"
                                        "	\n"
                                        "	border-radius:10px;\n"
                                        "}\n"
                                        "QPushButton:hover{\n"
                                        "\n"
                                        "\n"
                                        "border-color:rgb(255, 37, 255);\n"
                                        "\n"
                                        "\n"
                                        "}")

        self.horizontalLayout_8.addWidget(self.start_button)

        self.verticalLayout_6.addWidget(self.frame_for_start_button)

        self.frame_for_progressbar = QFrame(self.frame_left_bottom)
        self.frame_for_progressbar.setObjectName(u"frame_for_progressbar")
        self.frame_for_progressbar.setFrameShape(QFrame.StyledPanel)
        self.frame_for_progressbar.setFrameShadow(QFrame.Raised)
        self.horizontalLayout_10 = QHBoxLayout(self.frame_for_progressbar)
        self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
        self.horizontalSpacer_5 = QSpacerItem(13, 20, QSizePolicy.Expanding,
                                              QSizePolicy.Minimum)

        self.horizontalLayout_10.addItem(self.horizontalSpacer_5)

        self.horizontalLayout_9 = QHBoxLayout()
        self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")
        self.label_progress = QLabel(self.frame_for_progressbar)
        self.label_progress.setObjectName(u"label_progress")
        self.label_progress.setFont(font2)
        self.label_progress.setStyleSheet(u"QLabel{\n"
                                          "\n"
                                          " color:rgb(30, 149, 198);\n"
                                          "	\n"
                                          "\n"
                                          "	}")
        self.label_progress.setAlignment(Qt.AlignCenter)

        self.horizontalLayout_9.addWidget(self.label_progress)

        self.progressBar = QProgressBar(self.frame_for_progressbar)
        self.progressBar.setObjectName(u"progressBar")
        self.progressBar.setMinimumSize(QSize(350, 20))
        self.progressBar.setMaximumSize(QSize(450, 20))
        font6 = QFont()
        font6.setFamily(u"Segoe UI")
        font6.setPointSize(9)
        self.progressBar.setFont(font6)
        self.progressBar.setStyleSheet(u"QProgressBar{\n"
                                       "\n"
                                       "	\n"
                                       "	color:rgb(30, 149, 198);\n"
                                       "\n"
                                       "	 border: 1px solid black;\n"
                                       "\n"
                                       "	border-color:rgb(240, 123, 255);\n"
                                       "	\n"
                                       "	background-color: rgb(42, 44, 68);\n"
                                       "	\n"
                                       "	border-radius:2px;\n"
                                       "}\n"
                                       "QProgressBar::chunk{\n"
                                       "\n"
                                       "border-radius:2px;\n"
                                       "\n"
                                       "	background-color:rgb(30, 149, 198);\n"
                                       "}\n"
                                       "QProgressBar:hover{\n"
                                       "border-color:rgb(255, 37, 255);\n"
                                       "}")
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(56)
        self.progressBar.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                      | Qt.AlignVCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setInvertedAppearance(False)

        self.horizontalLayout_9.addWidget(self.progressBar)

        self.horizontalLayout_10.addLayout(self.horizontalLayout_9)

        self.verticalLayout_6.addWidget(self.frame_for_progressbar)

        self.verticalLayout_4.addWidget(self.frame_left_bottom)

        self.horizontalLayout.addWidget(self.frame_for_widgets)

        self.frame_for_textedit = QFrame(self.base)
        self.frame_for_textedit.setObjectName(u"frame_for_textedit")
        sizePolicy1 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy1.setHorizontalStretch(0)
        sizePolicy1.setVerticalStretch(0)
        sizePolicy1.setHeightForWidth(
            self.frame_for_textedit.sizePolicy().hasHeightForWidth())
        self.frame_for_textedit.setSizePolicy(sizePolicy1)
        self.frame_for_textedit.setMinimumSize(QSize(30, 0))
        self.frame_for_textedit.setMaximumSize(QSize(350, 16777215))
        self.frame_for_textedit.setFrameShape(QFrame.StyledPanel)
        self.frame_for_textedit.setFrameShadow(QFrame.Raised)
        self.verticalLayout_2 = QVBoxLayout(self.frame_for_textedit)
        self.verticalLayout_2.setSpacing(0)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")
        self.verticalLayout_2.setContentsMargins(-1, 0, 0, 0)
        self.terminal_output = QTextEdit(self.frame_for_textedit)
        self.terminal_output.setObjectName(u"terminal_output")
        self.terminal_output.setFont(font2)
        self.terminal_output.setStyleSheet(
            u"\n"
            "QTextEdit, QListView {\n"
            "   color:rgb(255, 37, 255);\n"
            "    background-color:rgb(40, 41, 65);\n"
            "	border:3px solid black;\n"
            "	border-radius:10px;\n"
            "	border-color:rgb(30, 149, 198);\n"
            "    background-attachment: scroll;\n"
            "}")

        self.verticalLayout_2.addWidget(self.terminal_output)

        self.horizontalLayout.addWidget(self.frame_for_textedit)

        self.verticalLayout.addWidget(self.base)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)

        QMetaObject.connectSlotsByName(MainWindow)

    # setupUi

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            QCoreApplication.translate("MainWindow", u"MainWindow", None))
        self.select_zip_button.setText(
            QCoreApplication.translate("MainWindow", u"Zip", None))
        self.label.setText(
            QCoreApplication.translate("MainWindow", u"Video Name :", None))
        self.same_as_zip_name_checkbox.setText(
            QCoreApplication.translate("MainWindow", u"Same as Zip name",
                                       None))
        self.label_2.setText(
            QCoreApplication.translate("MainWindow", u"Algorithm", None))
        self.algorithm_combobox.setItemText(
            0, QCoreApplication.translate("MainWindow", u"Select", None))
        self.algorithm_combobox.setItemText(
            1,
            QCoreApplication.translate("MainWindow", u"Very Fast - Good",
                                       None))
        self.algorithm_combobox.setItemText(
            2, QCoreApplication.translate("MainWindow", u"Fast - Better",
                                          None))
        self.algorithm_combobox.setItemText(
            3, QCoreApplication.translate("MainWindow", u"Slow - Best", None))

        self.label_3.setText(
            QCoreApplication.translate("MainWindow", u"Video Location", None))
        self.toolButton.setText(
            QCoreApplication.translate("MainWindow", u"...", None))
        self.start_button.setText(
            QCoreApplication.translate("MainWindow", u"Start", None))
        self.label_progress.setText(
            QCoreApplication.translate("MainWindow", u"Progress :", None))
        self.terminal_output.setHtml(
            QCoreApplication.translate(
                "MainWindow",
                u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:'Arial Rounded MT Bold'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Segoe UI Light'; color:#f07bff;\">Zipvy Ready...</span></p></body></html>",
                None))
コード例 #28
0
ファイル: MARS_gui.py プロジェクト: AndrewUlmer/MARS
    def Layout(self):
        #LAYOUT
        self.select_video = QLabel(self)
        self.select_video.setText("Folder Selected:")
        self.select_video.setVisible(False)

        self.browse_btn = QPushButton("Browse", self)
        self.browse_btn.setStatusTip(" Browse Folder")
        # self.browse_btn.setStyleSheet("background-color: rgb(186, 186, 186); border-radius: 15px;border-style: solid;border-width: 2px;border-color: black;");
        self.browse_btn.clicked.connect(self.browse)

        self.VideoName = QLabel(self)

        self.todo = QLabel(self)
        self.todo.setText("What do you want to do?")
        self.todo.setVisible(False)

        ## Various checkboxes for activities to perform within MARS.
        self.doPose = 0
        self.pose_chbox = QCheckBox('[Pose]', self)
        self.pose_chbox.stateChanged.connect(self.checkDoPose)
        self.pose_chbox.setVisible(False)

        self.doFeats = 0
        self.feat_chbox = QCheckBox('[Features]', self)
        self.feat_chbox.stateChanged.connect(self.checkDoFeat)
        self.feat_chbox.setVisible(False)

        self.doActions = 0
        self.actions_chbox = QCheckBox('[Classify Actions]', self)
        self.actions_chbox.stateChanged.connect(self.checkDoActions)
        self.actions_chbox.setVisible(False)

        # self.ddlist_label = QLabel(self)
        # self.ddlist_label.setText("Classifier:")
        # self.ddlist_label.move(200, 150)
        # self.ddlist_label.resize(150, 30)
        # self.ddlist_label.setVisible(False)
        #
        # self.ddlist = QComboBox(self)
        # self.ddlist.setVisible(False)
        # self.ddlist.setStatusTip('Choose the classifier you\'d like to use.')
        # self.ddlist.move(220, 120)
        # self.ddlist.resize(150, 50)
        # self.ddlist.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        self.doVideo = 0
        self.video_chbox = QCheckBox('[Produce Video]', self)
        self.video_chbox.stateChanged.connect(self.checkDoVideo)
        self.video_chbox.setVisible(False)

        self.doOverwrite = 0
        self.overwrite_chbox = QCheckBox('[Overwrite]', self)
        self.overwrite_chbox.setStyleSheet("background-color: #ff7a7a")
        self.overwrite_chbox.stateChanged.connect(self.checkDoOverwrite)
        self.overwrite_chbox.setVisible(False)

        ## Checkboxes that pick which view(s) to use, as well as the internal values they represent.
        self.doTop = 1  # change to 0 if we want to re-enable view checkboxes
        self.top_chbox = QCheckBox('[Top]', self)
        self.top_chbox.stateChanged.connect(self.checkDoTop)
        self.top_chbox.setVisible(False)

        self.doToppcf = 0
        self.toppcf_chbox = QCheckBox('[Top (w/ Front pixel features)]', self)
        self.toppcf_chbox.stateChanged.connect(self.checkDoToppcf)
        self.toppcf_chbox.setVisible(False)

        self.doFront = 0
        self.front_chbox = QCheckBox('[Front]', self)
        self.front_chbox.stateChanged.connect(self.checkDoFront)
        self.front_chbox.setVisible(False)

        # Button to run MARS.
        self.run_mars = QPushButton("[Run MARS]", self)
        self.run_mars.setVisible(False)
        self.run_mars.setStatusTip('Run detection and actions classification')
        self.run_mars.setStyleSheet(
            "background-color: rgb(142, 229, 171); border-radius: 15px;")
        self.run_mars.clicked.connect(self.run_event)

        # Button to reset the form for MARS.
        self.reset_btn = QPushButton("[Reset]", self)
        self.reset_btn.setVisible(False)
        self.reset_btn.setStatusTip('Reset buttons')
        self.reset_btn.setStyleSheet(
            "background-color: rgb(229, 200, 142);border-radius: 15px")
        self.reset_btn.clicked.connect(self.reset)

        # Button for adding things to queue.
        self.add2queue_btn = QPushButton("[Enqueue]", self)
        self.add2queue_btn.setVisible(False)
        self.add2queue_btn.setStyleSheet(
            "background-color: rgb(216,191,216);border-radius: 50px")
        self.add2queue_btn.clicked.connect(self.addToQueue)

        self.progress = QLabel(self)
        self.progress.setVisible(True)

        # Progress bar above the global progress, shows the progress on the current task.
        self.progbar = QProgressBar(self)
        self.progbar.setStyleSheet(
            "background-color: #FFA07A; border: 3px solid #000000;")
        self.progbar.setVisible(True)
        self.progbar.setAlignment(QtCore.Qt.AlignCenter)
        # Label for progress bar.
        self.progbar_label = QLabel(self)
        self.progbar_label.setText("Current Task Progress:")

        # Big progress bar at the bottom. Global progress.
        self.big_progbar = QProgressBar(self)
        self.big_progbar.setVisible(True)
        self.big_progbar.setStyleSheet(
            "background-color: #add8e6; border: 3px solid #FFFFFF;")
        self.big_progbar.setAlignment(QtCore.Qt.AlignCenter)
        # Label for big progress bar.
        self.big_progbar_label = QLabel(self)
        self.big_progbar_label.setText("Global Video Progress:")

        # Layout for the browsing span.
        self.button_layout = QHBoxLayout()
        self.button_layout.addWidget(self.browse_btn)
        self.button_layout.addWidget(self.select_video)
        self.button_layout.addWidget(self.VideoName)
        self.button_layout.addWidget(self.add2queue_btn)
        self.button_layout.addStretch(0.5)

        # Layout for the menu at the top.
        self.menu_layout = QHBoxLayout()
        self.menu_layout.addWidget(self.toolbar)
        self.menu_layout.addStretch()
        self.menu_layout.addWidget(self.toolbar2)

        # Layout for the view selection (Top, Toppcf, Front)
        # self.view_layout = QHBoxLayout()
        # self.view_layout.addWidget(self.top_chbox)
        # self.view_layout.addWidget(self.toppcf_chbox)
        # self.view_layout.addWidget(self.front_chbox)
        # self.view_layout.addStretch()

        # Layout for the checkboxes.
        self.chbox_layout = QHBoxLayout()
        self.chbox_layout.setSpacing(10)
        self.chbox_layout.addWidget(self.pose_chbox)
        self.chbox_layout.addWidget(self.feat_chbox)
        self.chbox_layout.addWidget(self.actions_chbox)
        self.chbox_layout.addWidget(self.video_chbox)
        self.chbox_layout.addWidget(self.overwrite_chbox)
        self.chbox_layout.addStretch(1)

        # Layout for the activity buttons, RUN and RESET.
        self.active_layout = QHBoxLayout()
        self.active_layout.addWidget(self.run_mars, stretch=2)
        self.active_layout.addWidget(self.reset_btn, stretch=1)

        # # Layout for the task progress bar.
        # self.task_progbar_layout = QtGui.QHBoxLayout()
        # self.task_progbar_layout.addWidget(self.progbar_label)
        # self.task_progbar_layout.addWidget(self.progbar, stretch=1)
        #
        # # Layout for the global progress bar.
        # self.global_progbar_layout = QtGui.QHBoxLayout()
        # self.global_progbar_layout.addWidget(self.big_progbar_label)
        # self.global_progbar_layout.addWidget(self.big_progbar)

        # Layout for the labels, to get ther vertically-aligned.
        self.progbar_label_layout = QVBoxLayout()
        self.progbar_label_layout.addWidget(self.progbar_label)
        self.progbar_label_layout.addWidget(self.big_progbar_label)

        # Layout for the progress bars themselves, to get them vertically-aligned.
        self.progbar_bar_layout = QVBoxLayout()
        self.progbar_bar_layout.addWidget(self.progbar)
        self.progbar_bar_layout.addWidget(self.big_progbar)

        # Layout for the combined progress bars and labels.
        self.progbar_layout = QHBoxLayout()
        self.progbar_layout.addLayout(self.progbar_label_layout)
        self.progbar_layout.addLayout(self.progbar_bar_layout, stretch=1)

        # This layout puts everything on the screen.
        self.main_layout = QVBoxLayout()
        self.main_layout.addLayout(self.menu_layout)
        self.main_layout.addWidget(self.toto)
        self.main_layout.addLayout(self.button_layout)
        self.main_layout.addWidget(self.todo)
        # self.main_layout.addLayout(self.view_layout)
        self.main_layout.addLayout(self.chbox_layout)
        self.main_layout.addLayout(self.active_layout)
        self.main_layout.addWidget(self.progress)

        self.main_layout.addStretch()
        self.main_layout.addLayout(self.progbar_layout)
コード例 #29
0
    def __init__(self, parent, metadata):
        """Groupbox for custom extension fields filling form."""
        super().__init__()
        self.setTitle(metadata['neurodata_type'])
        self.parent = parent
        self.metadata = metadata
        self.group_type = metadata['neurodata_type']

        self.lbl_name = QLabel('name<span style="color:' +
                               required_asterisk_color + ';">*</span>:')
        self.form_name = QLineEdit(metadata['name'])
        self.form_name.setToolTip("The unique name of this " +
                                  metadata['neurodata_type'] + " group.")
        nInstances = 0
        for grp in self.parent.groups_list:
            if isinstance(grp, metadata['neurodata_type']):
                nInstances += 1
        if nInstances > 0:
            self.form_name.setText(metadata['name'] + str(nInstances))

        self.grid = QGridLayout()
        self.grid.setColumnStretch(3, 1)
        self.grid.setColumnStretch(5, 1)
        self.grid.addWidget(self.lbl_name, 0, 0, 1, 2)
        self.grid.addWidget(self.form_name, 0, 2, 1, 4)

        # Dynamically created custom fields
        self.intValidator = QIntValidator(self)
        self.floatValidator = QDoubleValidator(self)
        keys_list = list(metadata.keys())
        keys_list.remove('name')
        keys_list.remove('neurodata_type')
        for ii, key in enumerate(keys_list):
            val = metadata[key]
            lbl_key = QLabel(key + ':')
            setattr(self, 'lbl_' + key, lbl_key)
            if isinstance(val, bool):
                chk_val = QLineEdit(str(val))
                chk_val = QCheckBox("True")
                chk_val.setChecked(val)
                setattr(self, 'form_' + key, chk_val)
                self.grid.addWidget(lbl_key, ii + 1, 0, 1, 2)
                self.grid.addWidget(chk_val, ii + 1, 2, 1, 2)
            elif isinstance(val, (int, np.int)):
                form_val = QLineEdit(str(val))
                form_val.setValidator(self.intValidator)
                setattr(self, 'form_' + key, form_val)
                self.grid.addWidget(lbl_key, ii + 1, 0, 1, 2)
                self.grid.addWidget(form_val, ii + 1, 2, 1, 4)
            elif isinstance(val, (float, np.float)):
                form_val = QLineEdit(str(val))
                form_val.setValidator(self.floatValidator)
                setattr(self, 'form_' + key, form_val)
                self.grid.addWidget(lbl_key, ii + 1, 0, 1, 2)
                self.grid.addWidget(form_val, ii + 1, 2, 1, 4)
            elif isinstance(val, str):
                form_val = QLineEdit(str(val))
                setattr(self, 'form_' + key, form_val)
                self.grid.addWidget(lbl_key, ii + 1, 0, 1, 2)
                self.grid.addWidget(form_val, ii + 1, 2, 1, 4)
            elif isinstance(val, datetime):
                pass
                # form_date = QLineEdit(val.strftime("%d/%m/%Y"))
                # form_date.setToolTip("dd/mm/yyyy")
                # setattr(self, 'form_date_'+str(ii), form_date)
                # form_time = QLineEdit(val.strftime("%H:%M"))
                # form_time.setToolTip("dd/mm/yyyy")
                # setattr(self, 'form_time_'+str(ii), form_time)
                # self.grid.addWidget(lbl_key, ii+1, 0, 1, 2)
                # self.grid.addWidget(form_date, ii+1, 2, 1, 2)
                # self.grid.addWidget(form_time, ii+1, 4, 1, 2)
        self.setLayout(self.grid)
コード例 #30
0
ファイル: MARS_gui.py プロジェクト: AndrewUlmer/MARS
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        #window setup
        resolution = QDesktopWidget().screenGeometry()
        self.screen_w = resolution.width()
        self.screen_h = resolution.height()
        self.setGeometry(0, 0, 650, 550)
        self.setWindowTitle('MARS_v1_8')
        self.setWindowIcon(QIcon('icons/mouse.png'))
        self.queue = Queue()
        self.queue_list = []
        self.str_proc = ''
        self.fname = ''

        #center window
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        #adjust size
        self.resize(self.screen_w / 2, self.screen_h / 2)
        self.Menu()
        self.Layout()

        central_widget = QWidget()
        central_widget.setLayout(self.main_layout)
        self.setCentralWidget(central_widget)

    def Menu(self):
        #this creates an action exit, a shortcut and status tip
        exitAction = QAction(QIcon('icons/exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        openFile = QAction(QIcon('icons/open.png'), '&Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.browse)

        runAction = QAction(QIcon('icons/run.png'), '&Run', self)
        runAction.setShortcut('Ctrl+R')
        runAction.setStatusTip('Run Mars')
        runAction.triggered.connect(self.run_event)

        resetAction = QAction(QIcon('icons/reset.png'), '&Reset', self)
        resetAction.setShortcut('Ctrl+X')
        resetAction.setStatusTip('Reset Mars')
        resetAction.triggered.connect(self.reset)

        #create status bar to show tooltip
        statusbar = QStatusBar(self)
        self.setStatusBar(statusbar)

        #create menu
        self.menu_File = QMenu('&File', self)
        self.menuBar().addMenu(self.menu_File)
        self.menu_File.addAction(openFile)
        self.menu_File.addAction(runAction)
        self.menu_File.addAction(resetAction)
        self.menu_File.addSeparator()
        self.menu_File.addAction(exitAction)

        #create toolbar
        self.toolbar = QToolBar("Toolbar", self)
        self.toolbar.addAction(openFile)
        self.toolbar.addAction(runAction)
        self.toolbar.addAction(resetAction)
        self.toolbar.addSeparator()
        # self.toolbar.move(5, 5)
        self.toolbar2 = QToolBar("ToolbarExit", self)
        self.toolbar2.addAction(exitAction)

        self.toto = QFrame(self)
        self.toto.setFrameShape(QFrame.HLine)
        self.toto.setFrameShadow(QFrame.Sunken)
        self.toto.setLineWidth(2)

    def Layout(self):
        #LAYOUT
        self.select_video = QLabel(self)
        self.select_video.setText("Folder Selected:")
        self.select_video.setVisible(False)

        self.browse_btn = QPushButton("Browse", self)
        self.browse_btn.setStatusTip(" Browse Folder")
        # self.browse_btn.setStyleSheet("background-color: rgb(186, 186, 186); border-radius: 15px;border-style: solid;border-width: 2px;border-color: black;");
        self.browse_btn.clicked.connect(self.browse)

        self.VideoName = QLabel(self)

        self.todo = QLabel(self)
        self.todo.setText("What do you want to do?")
        self.todo.setVisible(False)

        ## Various checkboxes for activities to perform within MARS.
        self.doPose = 0
        self.pose_chbox = QCheckBox('[Pose]', self)
        self.pose_chbox.stateChanged.connect(self.checkDoPose)
        self.pose_chbox.setVisible(False)

        self.doFeats = 0
        self.feat_chbox = QCheckBox('[Features]', self)
        self.feat_chbox.stateChanged.connect(self.checkDoFeat)
        self.feat_chbox.setVisible(False)

        self.doActions = 0
        self.actions_chbox = QCheckBox('[Classify Actions]', self)
        self.actions_chbox.stateChanged.connect(self.checkDoActions)
        self.actions_chbox.setVisible(False)

        # self.ddlist_label = QLabel(self)
        # self.ddlist_label.setText("Classifier:")
        # self.ddlist_label.move(200, 150)
        # self.ddlist_label.resize(150, 30)
        # self.ddlist_label.setVisible(False)
        #
        # self.ddlist = QComboBox(self)
        # self.ddlist.setVisible(False)
        # self.ddlist.setStatusTip('Choose the classifier you\'d like to use.')
        # self.ddlist.move(220, 120)
        # self.ddlist.resize(150, 50)
        # self.ddlist.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        self.doVideo = 0
        self.video_chbox = QCheckBox('[Produce Video]', self)
        self.video_chbox.stateChanged.connect(self.checkDoVideo)
        self.video_chbox.setVisible(False)

        self.doOverwrite = 0
        self.overwrite_chbox = QCheckBox('[Overwrite]', self)
        self.overwrite_chbox.setStyleSheet("background-color: #ff7a7a")
        self.overwrite_chbox.stateChanged.connect(self.checkDoOverwrite)
        self.overwrite_chbox.setVisible(False)

        ## Checkboxes that pick which view(s) to use, as well as the internal values they represent.
        self.doTop = 1  # change to 0 if we want to re-enable view checkboxes
        self.top_chbox = QCheckBox('[Top]', self)
        self.top_chbox.stateChanged.connect(self.checkDoTop)
        self.top_chbox.setVisible(False)

        self.doToppcf = 0
        self.toppcf_chbox = QCheckBox('[Top (w/ Front pixel features)]', self)
        self.toppcf_chbox.stateChanged.connect(self.checkDoToppcf)
        self.toppcf_chbox.setVisible(False)

        self.doFront = 0
        self.front_chbox = QCheckBox('[Front]', self)
        self.front_chbox.stateChanged.connect(self.checkDoFront)
        self.front_chbox.setVisible(False)

        # Button to run MARS.
        self.run_mars = QPushButton("[Run MARS]", self)
        self.run_mars.setVisible(False)
        self.run_mars.setStatusTip('Run detection and actions classification')
        self.run_mars.setStyleSheet(
            "background-color: rgb(142, 229, 171); border-radius: 15px;")
        self.run_mars.clicked.connect(self.run_event)

        # Button to reset the form for MARS.
        self.reset_btn = QPushButton("[Reset]", self)
        self.reset_btn.setVisible(False)
        self.reset_btn.setStatusTip('Reset buttons')
        self.reset_btn.setStyleSheet(
            "background-color: rgb(229, 200, 142);border-radius: 15px")
        self.reset_btn.clicked.connect(self.reset)

        # Button for adding things to queue.
        self.add2queue_btn = QPushButton("[Enqueue]", self)
        self.add2queue_btn.setVisible(False)
        self.add2queue_btn.setStyleSheet(
            "background-color: rgb(216,191,216);border-radius: 50px")
        self.add2queue_btn.clicked.connect(self.addToQueue)

        self.progress = QLabel(self)
        self.progress.setVisible(True)

        # Progress bar above the global progress, shows the progress on the current task.
        self.progbar = QProgressBar(self)
        self.progbar.setStyleSheet(
            "background-color: #FFA07A; border: 3px solid #000000;")
        self.progbar.setVisible(True)
        self.progbar.setAlignment(QtCore.Qt.AlignCenter)
        # Label for progress bar.
        self.progbar_label = QLabel(self)
        self.progbar_label.setText("Current Task Progress:")

        # Big progress bar at the bottom. Global progress.
        self.big_progbar = QProgressBar(self)
        self.big_progbar.setVisible(True)
        self.big_progbar.setStyleSheet(
            "background-color: #add8e6; border: 3px solid #FFFFFF;")
        self.big_progbar.setAlignment(QtCore.Qt.AlignCenter)
        # Label for big progress bar.
        self.big_progbar_label = QLabel(self)
        self.big_progbar_label.setText("Global Video Progress:")

        # Layout for the browsing span.
        self.button_layout = QHBoxLayout()
        self.button_layout.addWidget(self.browse_btn)
        self.button_layout.addWidget(self.select_video)
        self.button_layout.addWidget(self.VideoName)
        self.button_layout.addWidget(self.add2queue_btn)
        self.button_layout.addStretch(0.5)

        # Layout for the menu at the top.
        self.menu_layout = QHBoxLayout()
        self.menu_layout.addWidget(self.toolbar)
        self.menu_layout.addStretch()
        self.menu_layout.addWidget(self.toolbar2)

        # Layout for the view selection (Top, Toppcf, Front)
        # self.view_layout = QHBoxLayout()
        # self.view_layout.addWidget(self.top_chbox)
        # self.view_layout.addWidget(self.toppcf_chbox)
        # self.view_layout.addWidget(self.front_chbox)
        # self.view_layout.addStretch()

        # Layout for the checkboxes.
        self.chbox_layout = QHBoxLayout()
        self.chbox_layout.setSpacing(10)
        self.chbox_layout.addWidget(self.pose_chbox)
        self.chbox_layout.addWidget(self.feat_chbox)
        self.chbox_layout.addWidget(self.actions_chbox)
        self.chbox_layout.addWidget(self.video_chbox)
        self.chbox_layout.addWidget(self.overwrite_chbox)
        self.chbox_layout.addStretch(1)

        # Layout for the activity buttons, RUN and RESET.
        self.active_layout = QHBoxLayout()
        self.active_layout.addWidget(self.run_mars, stretch=2)
        self.active_layout.addWidget(self.reset_btn, stretch=1)

        # # Layout for the task progress bar.
        # self.task_progbar_layout = QtGui.QHBoxLayout()
        # self.task_progbar_layout.addWidget(self.progbar_label)
        # self.task_progbar_layout.addWidget(self.progbar, stretch=1)
        #
        # # Layout for the global progress bar.
        # self.global_progbar_layout = QtGui.QHBoxLayout()
        # self.global_progbar_layout.addWidget(self.big_progbar_label)
        # self.global_progbar_layout.addWidget(self.big_progbar)

        # Layout for the labels, to get ther vertically-aligned.
        self.progbar_label_layout = QVBoxLayout()
        self.progbar_label_layout.addWidget(self.progbar_label)
        self.progbar_label_layout.addWidget(self.big_progbar_label)

        # Layout for the progress bars themselves, to get them vertically-aligned.
        self.progbar_bar_layout = QVBoxLayout()
        self.progbar_bar_layout.addWidget(self.progbar)
        self.progbar_bar_layout.addWidget(self.big_progbar)

        # Layout for the combined progress bars and labels.
        self.progbar_layout = QHBoxLayout()
        self.progbar_layout.addLayout(self.progbar_label_layout)
        self.progbar_layout.addLayout(self.progbar_bar_layout, stretch=1)

        # This layout puts everything on the screen.
        self.main_layout = QVBoxLayout()
        self.main_layout.addLayout(self.menu_layout)
        self.main_layout.addWidget(self.toto)
        self.main_layout.addLayout(self.button_layout)
        self.main_layout.addWidget(self.todo)
        # self.main_layout.addLayout(self.view_layout)
        self.main_layout.addLayout(self.chbox_layout)
        self.main_layout.addLayout(self.active_layout)
        self.main_layout.addWidget(self.progress)

        self.main_layout.addStretch()
        self.main_layout.addLayout(self.progbar_layout)
#        self.main_layout.addLayout(self.task_progbar_layout)
#        self.main_layout.addLayout(self.global_progbar_layout)

    def addToQueue(self):
        self.queue.put(self.fname)
        self.queue_list.append(self.fname)
        barMsg = self.fname + " added to the list!\n"
        msg = barMsg
        self.updateProgess(barMsg, msg)

    def browse(self):
        # sender = self.sender()
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.Directory)
        dialog.setOption(QFileDialog.ShowDirsOnly)
        if os.path.exists(self.fname):
            dir_to_use = self.fname
        else:
            dir_to_use = os.path.curdir

        self.fname = dialog.getExistingDirectory(self, 'Choose Directory',
                                                 dir_to_use)
        self.statusBar().showMessage(self.fname + ' selected ')
        if os.path.exists(self.fname) and os.path.isdir(
                self.fname) and self.fname != '':
            files = os.listdir(self.fname)
            seq_files = [
                f for f in files if f.endswith('.seq') or f.endswith('.avi')
                or f.endswith('.mp4') or f.endswith('.mpg')
            ]
            self.vid_name = self.fname.split('/')[-1]
            #if len(seq_files) >= 2:
            self.VideoName.setText(self.fname)
            self.todo.setVisible(True)

            self.select_video.setVisible(True)
            self.add2queue_btn.setVisible(True)
            # self.ddlist_label.setVisible(True)
            # self.ddlist.setVisible(True)

            self.pose_chbox.setVisible(True)
            self.feat_chbox.setVisible(True)
            self.actions_chbox.setVisible(True)
            self.video_chbox.setVisible(True)

            self.front_chbox.setVisible(True)
            self.top_chbox.setVisible(True)
            self.toppcf_chbox.setVisible(True)

            self.run_mars.setVisible(True)
            self.reset_btn.setVisible(True)
            self.overwrite_chbox.setVisible(True)
            #else:
            #    QMessageBox.information(self, "Not all needed files exists", "Select a folder containing .seq files!")
        else:
            QMessageBox.information(
                self, " Wrong file selected",
                "No compatible movie files found! Supported formats: .seq, .avi, .mp4, .mpg"
            )
            self.fname = dir_to_use

    def checkDoPose(self, state):
        if state == QtCore.Qt.Checked:
            self.doPose = 1
        else:
            self.doPose = 0

    def checkDoFeat(self, state):
        if state == QtCore.Qt.Checked:
            self.doFeats = 1
        else:
            self.doFeats = 0

    def checkDoActions(self, state):
        if state == QtCore.Qt.Checked:
            self.doActions = 1
        else:
            self.doActions = 0

    def checkDoVideo(self, state):
        if state == QtCore.Qt.Checked:
            self.doVideo = 1
        else:
            self.doVideo = 0

    def checkDoOverwrite(self, state):
        if state == QtCore.Qt.Checked:
            self.doOverwrite = 1
        else:
            self.doOverwrite = 0

    def checkDoTop(self, state):
        if state == QtCore.Qt.Checked:
            self.doTop = 1
            # self.ddlist.addItem("top mlp")
            # self.ddlist.addItem("top xgb")
            # self.ddlist.addItem("top mlp wnd")
            # self.ddlist.addItem("top xgb wnd")
        else:
            self.doTop = 0
            # self.ddlist.clear()

    def checkDoToppcf(self, state):
        if state == QtCore.Qt.Checked:
            self.doToppcf = 1
            # self.ddlist.addItem("top pcf mlp")
            # self.ddlist.addItem("top pcf xgb")
            # self.ddlist.addItem("top pcf mlp wnd")
            # self.ddlist.addItem("top pcf xgb wnd")
        else:
            self.doToppcf = 0
            # self.ddlist.clear()

    def checkDoFront(self, state):
        if state == QtCore.Qt.Checked:
            self.doFront = 1
            # self.ddlist.addItem("topfront mlp")
            # self.ddlist.addItem("topfront xgb")
            # self.ddlist.addItem("topfront mlp wnd")
            # self.ddlist.addItem("topfront xgb wnd")
        else:
            self.doFront = 0
            # self.ddlist.clear()

    def reset(self):
        todo = [self.doPose, self.doFeats, self.doActions]
        # if not self.todo.isVisible() or  sum(todo)== 0:
        #     QMessageBox.information(self, "Reset", "Nothing to reset")
        # else:
        self.doPose = 0
        self.doFeats = 0
        self.doActions = 0
        self.doVideo = 0
        self.doOverwrite = 0

        self.doFront = 0
        self.doTop = 0
        self.doToppcf = 0

        self.pose_chbox.setCheckState(QtCore.Qt.Unchecked)
        self.feat_chbox.setCheckState(QtCore.Qt.Unchecked)
        self.actions_chbox.setCheckState(QtCore.Qt.Unchecked)
        self.video_chbox.setCheckState(QtCore.Qt.Unchecked)
        self.overwrite_chbox.setCheckState(QtCore.Qt.Unchecked)

        self.front_chbox.setCheckState(QtCore.Qt.Unchecked)
        self.top_chbox.setCheckState(QtCore.Qt.Unchecked)
        self.toppcf_chbox.setCheckState(QtCore.Qt.Unchecked)

        self.str_proc = ''
        self.progress.setText(self.str_proc)

        self.VideoName.setText('')
        self.fname = ''

        self.statusBar().showMessage('')
        self.changeEnable_wdj(True)
        self.clearProgress()

    def changeEnable_wdj(self, b=False):
        self.run_mars.setEnabled(b)
        self.reset_btn.setEnabled(b)

        self.pose_chbox.setEnabled(b)
        self.feat_chbox.setEnabled(b)
        self.actions_chbox.setEnabled(b)
        self.video_chbox.setEnabled(b)
        self.overwrite_chbox.setEnabled(b)

        # self.add2queue_btn.setEnabled(b)
        # self.ddlist.setEnabled(b)

        self.front_chbox.setEnabled(b)
        self.top_chbox.setEnabled(b)
        self.toppcf_chbox.setEnabled(b)

    # def stop_event(self):
    #     print('Stopped')
    #     # self.genericThread.stop()
    #     # self.genericThread.wait()
    #     self.statusBar().showMessage('Stopped processing')
    #     self.changeEnable_wdj(True)
    #     # self.stop_run.setVisible(False)

    def update_thread(self, prog):
        if prog == 1:
            print('Thread pose done')
        if prog == 2:
            print('Thread features done')
        if prog == 3:
            print('Thread actions done')
        if prog == 4:
            print('Thread video done')

    def thread_done(self):
        print('Thread ended')
        # self.changeEnable_wdj(True)
        # self.stop_run.setVisible(False)

    def queue_done(self):
        print('Queue ended')
        self.changeEnable_wdj(True)

    def updateProgess(self, barMsg, msg):
        self.statusBar().showMessage(barMsg)
        self.str_proc += msg
        self.progress.setText(self.str_proc)
        self.scrollText()

    def updateProgbar(self, value, set_max):
        if set_max != 0:
            self.progbar.setMaximum(set_max)
        self.progbar.setValue(value)

    def updateBigProgbar(self, value, set_max):
        if set_max != 0:
            self.big_progbar.setMaximum(set_max)
        self.big_progbar.setValue(value)

    def clearProgress(self):
        self.str_proc = 'Console cleared. \n'
        self.progress.setText(self.str_proc)
        self.resize(self.screen_w / 2, self.screen_h / 2)
        # self.adjustSize()
        # self.changeEnable_wdj(True)

    def scrollText(self):
        MAX_LINES = 20
        all_lines = self.str_proc.splitlines()
        if len(all_lines) > MAX_LINES:
            renewed_lines = all_lines[-MAX_LINES:]
            self.str_proc = '\n'.join(renewed_lines) + '\n'

    def run_event(self):
        todo = [self.doPose, self.doFeats, self.doActions, self.doVideo]
        if not self.todo.isVisible():
            QMessageBox.information(self, "Empty selection",
                                    "Select a folder to process.")
        elif sum(todo) == 0:
            QMessageBox.information(self, "Empty selection",
                                    "Select at least one task to do.")
        else:
            self.str_proc = ''
            self.progress.setVisible(True)
            self.genericThread = GenericThread(self.doPose, self.doFeats,
                                               self.doActions, self.doVideo,
                                               self.doOverwrite, self.doFront,
                                               self.doTop, self.doToppcf,
                                               self.queue, self.fname)
            self.genericThread.update_th.connect(self.update_thread)
            self.genericThread.done_th.connect(self.thread_done)
            self.genericThread.done_queue.connect(self.queue_done)

            self.genericThread.update_progbar_sig.connect(self.updateProgbar)
            self.genericThread.update_big_progbar_sig.connect(
                self.updateBigProgbar)
            self.genericThread.update_progress.connect(self.updateProgess)

            # self.genericThread.classifier_to_use = self.ddlist.currentText()
            self.genericThread.clear_sig.connect(self.clearProgress)

            self.genericThread.start()
            # self.stop_run.setVisible(True)
            self.changeEnable_wdj(False)
コード例 #31
0
class RecoView(BaseView):
    def __init__(self, workspace, default_docking_position, *args, **kwargs):
        super(RecoView,
              self).__init__('reco', workspace, default_docking_position,
                             *args, **kwargs)

        self.caption = 'CTF Clippy'

        self._string_table = None  # type: QStringTable

        self._extracted_strings = None  # type :  QLabel
        self._seed_words = []
        self._list_of_strings = None
        self._gen_urls = None  # type : List of QLabels
        self._print_str = ""

        self.data_ext_chbox = None
        self.seed_words_chbox = None

        self.seed_text_edit = None

        self.client = Elasticsearch(["http://172.17.0.1:9200"])

        self._init_widgets()

    def valid_keyword(self, prob_keyword):
        if prob_keyword.startswith("_") or prob_keyword.isnumeric(
        ) or prob_keyword.startswith("sub"):
            return False
        return True

    def get_keywords(self):
        self._list_of_strings = []
        for string_item in self._string_table.items:
            string_obj = filter_string_for_display(
                string_item._mem_data.content.decode("utf-8"))
            for word in string_obj.split(" "):
                if self.valid_keyword(word):
                    self._list_of_strings.append(word)
        for addr, element in list(self._string_table.cfg.kb.functions.items()):
            if self.valid_keyword(element.name):
                self._list_of_strings.append(element.name)
        print_str = self._list_of_strings[0]
        for strs in self._list_of_strings[1:]:
            print_str += ", " + strs
        self._print_str = print_str

    def search_index_es(self, query, client, cond="or", index="ctf-writeups"):
        query = {
            "from": 0,
            "size": 30,
            "query": {
                "match": {
                    "tag": {
                        "query": " ".join(query),
                        "operator": cond
                    }
                }
            }
        }
        res = client.search(index=index, body=query)
        print("Got %d Hits:" % res['hits']['total'])
        hits = []
        urls = []
        for hit in res['hits']['hits']:
            hits.append(hit["_source"])
            urls.append(hit["_source"]["url"].strip().split("\t")[1])
        _l.error(str(len(urls)) + " " + str(urls))
        purls = []
        for url in urls:
            if url in purls:
                continue
            purls.append(url)
        return hits, purls

    def create_tags(self, keywords):
        tags = keywords
        tags.append("C")
        tags.append("c")
        overflow = [
            "input", "scanf", "sscanf", "fscanf", "gets", "gets", "puts",
            "fprintf"
        ]
        for keyword in keywords:
            for inputs in overflow:
                if inputs in keyword:
                    tags.append("overflow")
                    tags.append("buffer")
        return tags

    def reload(self):
        self._string_table.cfg = self.workspace.instance.cfg
        self._string_table.setVisible(False)
        self.get_keywords()

        keywords = []
        if self.data_ext_chbox.isChecked():
            keywords = keywords + self._list_of_strings
        if self.seed_words_chbox.isChecked():
            keywords = keywords + self._seed_words

        tags = self.create_tags(keywords)
        _l.error(tags)
        ctfs, urls = self.search_index_es(tags,
                                          self.client,
                                          cond="or",
                                          index="ctf-writeups-bin2")
        topctfs = ctfs[0:10]
        topurls = urls[0:10]
        _l.error(topurls)

        self._gen_urls.setVisible(False)

        for idx, url in enumerate(topurls):
            self._gen_urls.setItem(idx, 0, QTableWidgetItem(url))

        self._gen_urls.resizeColumnsToContents()
        self._gen_urls.setVisible(True)

        # self._extracted_strings.setText(self._print_str)
        # self._extracted_strings.setWordWrap(True)
        # self._extracted_strings.setVisible(True)

    def sizeHint(self):
        return QSize(400, 800)

    def _on_keywords_added(self, text):
        self._seed_words = text.split(",")
        self.reload()

    def _on_string_selected(self, s):
        """
        A string reference is selected.

        :param s:
        :return:
        """

        pass

    def _open_link(self, item):
        _l.error(item.text())
        webbrowser.open(item.text(), new=2)

    #
    # Private methods
    #

    def _init_widgets(self):
        self._string_table = QStringTable(
            self, selection_callback=self._on_string_selected)
        self._string_table.setVisible(False)

        clippy = QLabel(self)
        clippy.setText("CTF Clippy:")

        clippy_hello = QLabel(self)
        clippy_hello.setText(
            "Looks like you are analyzing binary, here are few writeups which might help!"
        )

        clippy_layout = QHBoxLayout()
        clippy_layout.addWidget(clippy)
        clippy_layout.addWidget(clippy_hello)

        seed_words = QLabel(self)
        seed_words.setText("Search seed words:")

        self.seed_text_edit = QLineEdit()
        self.seed_text_edit.textChanged.connect(self._on_keywords_added)

        seed_layout = QHBoxLayout()
        seed_layout.addWidget(seed_words)
        seed_layout.addWidget(self.seed_text_edit)

        self.data_ext_chbox = QCheckBox("Data Extractor")
        self.seed_words_chbox = QCheckBox("Seed Words")
        self.data_ext_chbox.setChecked(True)
        self.seed_words_chbox.setChecked(True)
        self.data_ext_chbox.stateChanged.connect(
            lambda: self._on_keywords_added(self.seed_text_edit.text()))
        self.seed_words_chbox.stateChanged.connect(
            lambda: self._on_keywords_added(self.seed_text_edit.text()))

        chbox_layout = QHBoxLayout()
        chbox_layout.addWidget(self.data_ext_chbox)
        chbox_layout.addWidget(self.seed_words_chbox)

        self._gen_urls = QTableWidget()
        self._gen_urls.setRowCount(10)
        self._gen_urls.setColumnCount(1)
        self._gen_urls.setVisible(False)
        self._gen_urls.itemDoubleClicked.connect(self._open_link)
        self._gen_urls.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)

        layout = QVBoxLayout()
        layout.addLayout(clippy_layout)
        layout.addLayout(seed_layout)
        layout.addLayout(chbox_layout)
        layout.addWidget(self._gen_urls)
        # layout.addWidget(self._string_table)
        layout.setContentsMargins(0, 0, 0, 0)

        self.setLayout(layout)
コード例 #32
0
    def __init__(self, parent):
        super().__init__(parent)

        self.setWindowTitle("customer - Table")
        self.setWindowIcon(QtGui.QIcon("assets/img/icons8-edit-file-64.png"))

        self.resize(662, 438)
        self.save_talble_changes = QPushButton("Save table changes", self)
        self.save_talble_changes.setGeometry(390, 290, 251, 31)

        self.add_table_main = QPushButton("Add Column ", self)
        self.add_table_main.setGeometry(390, 260, 251, 28)
        #self.add_table_main.clicked.connect(self.add_column)

        self.delet_table_column = QPushButton("Delet table column", self)
        self.delet_table_column.setGeometry(390, 330, 251, 31)

        self.not_null_box = QCheckBox("Not Null", self)
        self.not_null_box.setGeometry(220, 330, 81, 61)

        self.colm_name_label = QLabel("Column Name:", self)
        self.colm_name_label.setGeometry(10, 250, 111, 41)

        self.table_name_label_2 = QLabel("Table Name", self)
        self.table_name_label_2.setGeometry(10, 10, 91, 21)

        self.comn_name_line_edit = QLineEdit(self)
        self.comn_name_line_edit.setGeometry(110, 260, 151, 22)

        self.data_type_label = QLabel("Data Type", self)
        self.data_type_label.setGeometry(10, 300, 61, 16)

        self.data_type_line_edit = QLineEdit(self)
        self.data_type_line_edit.setGeometry(110, 300, 151, 22)

        self.table_name_line_edit = QLineEdit(self)
        self.table_name_line_edit.setGeometry(110, 10, 391, 22)

        self.foreign_key_box = QCheckBox("Foreign Key", self)
        self.foreign_key_box.setGeometry(120, 330, 91, 61)

        self.primary_key_box = QCheckBox("Primary Key", self)
        self.primary_key_box.setGeometry(20, 330, 111, 61)

        self.table_widget = QTableWidget(self)

        if (self.table_widget.columnCount() < 6):
            self.table_widget.setColumnCount(6)

        __qtablewidgetitem = QTableWidgetItem()
        self.table_widget.setHorizontalHeaderItem(0, __qtablewidgetitem)
        __qtablewidgetitem1 = QTableWidgetItem()
        self.table_widget.setHorizontalHeaderItem(1, __qtablewidgetitem1)
        __qtablewidgetitem2 = QTableWidgetItem()
        self.table_widget.setHorizontalHeaderItem(2, __qtablewidgetitem2)
        __qtablewidgetitem3 = QTableWidgetItem()
        self.table_widget.setHorizontalHeaderItem(3, __qtablewidgetitem3)
        __qtablewidgetitem4 = QTableWidgetItem()
        self.table_widget.setHorizontalHeaderItem(4, __qtablewidgetitem4)
        __qtablewidgetitem5 = QTableWidgetItem()
        self.table_widget.setHorizontalHeaderItem(5, __qtablewidgetitem5)

        self.table_widget.setGeometry(0, 40, 661, 201)
        self.table_widget.setColumnWidth(2, 85)
        self.table_widget.setColumnWidth(3, 85)
        self.table_widget.setColumnWidth(4, 85)

        self.frame = QFrame(self)
        self.frame.setGeometry(0, 390, 661, 51)
        self.frame.setStyleSheet(u"background-color: rgb(45,45,45);")
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)

        self.cancel_button = QPushButton("Cancel button", self.frame)
        self.cancel_button.setGeometry(550, 10, 111, 28)

        self.cancel_button.setStyleSheet(
            u"background-color: rgb(255,255,255);")
        self.add_table_button = QPushButton("Add table", self.frame)

        self.add_table_button.setGeometry(442, 10, 101, 28)
        self.add_table_button.setStyleSheet(
            u"background-color: rgb(255,255,255);")

        self.tables()

        self.show()
コード例 #33
0
ファイル: export.py プロジェクト: strohne/Facepager
    def __init__(self,*args,**kwargs):
        super(ExportFileDialog,self).__init__(*args,**kwargs)

        self.mainWindow = self.parent()
        self.setWindowTitle("Export nodes to CSV")
        self.setAcceptMode(QFileDialog.AcceptSave)
        self.setOption(QFileDialog.DontUseNativeDialog)
        #self.setFilter("CSV Files (*.csv)")
        self.setDefaultSuffix("csv")

        self.optionBOM = QCheckBox("Use a BOM",self)
        self.optionBOM.setCheckState(Qt.CheckState.Checked)

        self.optionLinebreaks = QCheckBox("Remove line breaks",self)
        self.optionLinebreaks.setCheckState(Qt.CheckState.Checked)

        self.optionSeparator = QComboBox(self)
        self.optionSeparator.insertItems(0, [";","\\t",","])
        self.optionSeparator.setEditable(True)

        #self.optionLinebreaks.setCheckState(Qt.CheckState.Checked)

        self.optionWide = QCheckBox("Convert to wide format (experimental feature)",self)
        self.optionWide.setCheckState(Qt.CheckState.Unchecked)

        # if none or all are selected, export all
        # if one or more are selected, export selective
        self.optionAll = QComboBox(self)
        self.optionAll.insertItems(0, ['All nodes (faster for large datasets, ordered by internal ID)','Selected nodes (ordered like shown in nodes view)'])
        if self.mainWindow.tree.noneOrAllSelected():
            self.optionAll.setCurrentIndex(0)
        else:
            self.optionAll.setCurrentIndex(1)

        layout = self.layout()
        row = layout.rowCount()
        layout.addWidget(QLabel('Options'),row,0)

        options = QHBoxLayout()
        options.addWidget(self.optionBOM)
        options.addWidget(self.optionLinebreaks)
        options.addWidget(QLabel('Separator'))
        options.addWidget(self.optionSeparator)
        options.addStretch(1)

        layout.addLayout(options,row,1,1,2)

        layout.addWidget(QLabel('Post processing'),row+1,0)
        layout.addWidget(self.optionWide,row+1,1,1,2)

        layout.addWidget(QLabel('Export mode'),row+2,0)
        layout.addWidget(self.optionAll,row+2,1,1,2)
        self.setLayout(layout)

        if self.exec_():

            if os.path.isfile(self.selectedFiles()[0]):
                os.remove(self.selectedFiles()[0])
            output = open(self.selectedFiles()[0], 'w', newline='', encoding='utf8')
            if self.optionBOM.isChecked() and not self.optionWide.isChecked():
                output.write('\ufeff')

            try:
                if self.optionAll.currentIndex() == 0:
                    self.exportAllNodes(output)
                else:
                    self.exportSelectedNodes(output)
            finally:
                output.close()

            if self.optionWide.isChecked():
                self.convertToWideFormat(self.selectedFiles()[0])
コード例 #34
0
 def create_visibility_checkbox(self, v):
     cb = QCheckBox(self.ui.table)
     cb.setChecked(v)
     cb.toggled.connect(self.update_config_visibilities)
     self.visibility_boxes.append(cb)
     return self.create_table_widget(cb)
コード例 #35
0
ファイル: MainWindow.py プロジェクト: goph-R/TilePad
    def __init__(self, app, parent=None):
        super(MainWindow, self).__init__(parent)
        self.imagesDir = app.dir + '/images/'
        self.setWindowIcon(QIcon(self.imagesDir + 'icon.png'))
        self.path = ''

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

        self.setMinimumWidth(540)

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

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

        # widgets
        self.showPixmapWidget = None

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

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

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

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

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

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

        self.reorderTilesCheckBox = QCheckBox("Reorder tiles")

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

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

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

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

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

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

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

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

        self.setTitle()
コード例 #36
0
    def initDifficultyLayout(self):

        self.difficultyPage = QWidget()
        self.difficultyLayout = QVBoxLayout()
        self.difficultyLayout.setAlignment(Qt.AlignTop)
        self.difficultyPage.setLayout(self.difficultyLayout)

        # DCS AI difficulty settings
        self.aiDifficultySettings = QGroupBox("AI Difficulty")
        self.aiDifficultyLayout = QGridLayout()
        self.playerCoalitionSkill = QComboBox()
        self.enemyCoalitionSkill = QComboBox()
        self.enemyAASkill = QComboBox()
        for skill in CONST.SKILL_OPTIONS:
            self.playerCoalitionSkill.addItem(skill)
            self.enemyCoalitionSkill.addItem(skill)
            self.enemyAASkill.addItem(skill)

        self.playerCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.player_skill)
        )
        self.enemyCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill)
        )
        self.enemyAASkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill)
        )

        self.player_income = TenthsSpinSlider(
            "Player income multiplier",
            0,
            50,
            int(self.game.settings.player_income_multiplier * 10),
        )
        self.player_income.spinner.valueChanged.connect(self.applySettings)
        self.enemy_income = TenthsSpinSlider(
            "Enemy income multiplier",
            0,
            50,
            int(self.game.settings.enemy_income_multiplier * 10),
        )
        self.enemy_income.spinner.valueChanged.connect(self.applySettings)

        self.playerCoalitionSkill.currentIndexChanged.connect(self.applySettings)
        self.enemyCoalitionSkill.currentIndexChanged.connect(self.applySettings)
        self.enemyAASkill.currentIndexChanged.connect(self.applySettings)

        # Mission generation settings related to difficulty
        self.missionSettings = QGroupBox("Mission Difficulty")
        self.missionLayout = QGridLayout()

        self.manpads = QCheckBox()
        self.manpads.setChecked(self.game.settings.manpads)
        self.manpads.toggled.connect(self.applySettings)

        self.noNightMission = QCheckBox()
        self.noNightMission.setChecked(self.game.settings.night_disabled)
        self.noNightMission.toggled.connect(self.applySettings)

        # DCS Mission options
        self.missionRestrictionsSettings = QGroupBox("Mission Restrictions")
        self.missionRestrictionsLayout = QGridLayout()

        self.difficultyLabel = QComboBox()
        [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS]
        self.difficultyLabel.setCurrentIndex(
            CONST.LABELS_OPTIONS.index(self.game.settings.labels)
        )
        self.difficultyLabel.currentIndexChanged.connect(self.applySettings)

        self.mapVisibiitySelection = QComboBox()
        self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All:
            self.mapVisibiitySelection.setCurrentIndex(0)
        self.mapVisibiitySelection.addItem("Fog of War", ForcedOptions.Views.Allies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies:
            self.mapVisibiitySelection.setCurrentIndex(1)
        self.mapVisibiitySelection.addItem(
            "Allies Only", ForcedOptions.Views.OnlyAllies
        )
        if (
            self.game.settings.map_coalition_visibility
            == ForcedOptions.Views.OnlyAllies
        ):
            self.mapVisibiitySelection.setCurrentIndex(2)
        self.mapVisibiitySelection.addItem(
            "Own Aircraft Only", ForcedOptions.Views.MyAircraft
        )
        if (
            self.game.settings.map_coalition_visibility
            == ForcedOptions.Views.MyAircraft
        ):
            self.mapVisibiitySelection.setCurrentIndex(3)
        self.mapVisibiitySelection.addItem("Map Only", ForcedOptions.Views.OnlyMap)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap:
            self.mapVisibiitySelection.setCurrentIndex(4)
        self.mapVisibiitySelection.currentIndexChanged.connect(self.applySettings)

        self.ext_views = QCheckBox()
        self.ext_views.setChecked(self.game.settings.external_views_allowed)
        self.ext_views.toggled.connect(self.applySettings)

        def set_invulnerable_player_pilots(checked: bool) -> None:
            self.game.settings.invulnerable_player_pilots = checked

        invulnerable_player_pilots_label = QLabel(
            "Player pilots cannot be killed<br />"
            "<strong>Aircraft are vulnerable, but the player's pilot will be<br />"
            "returned to the squadron at the end of the mission</strong>"
        )

        invulnerable_player_pilots_checkbox = QCheckBox()
        invulnerable_player_pilots_checkbox.setChecked(
            self.game.settings.invulnerable_player_pilots
        )
        invulnerable_player_pilots_checkbox.toggled.connect(
            set_invulnerable_player_pilots
        )

        self.aiDifficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0)
        self.aiDifficultyLayout.addWidget(
            self.playerCoalitionSkill, 0, 1, Qt.AlignRight
        )
        self.aiDifficultyLayout.addWidget(QLabel("Enemy coalition skill"), 1, 0)
        self.aiDifficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1, Qt.AlignRight)
        self.aiDifficultyLayout.addWidget(QLabel("Enemy AA and vehicles skill"), 2, 0)
        self.aiDifficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight)
        self.aiDifficultyLayout.addLayout(self.player_income, 3, 0)
        self.aiDifficultyLayout.addLayout(self.enemy_income, 4, 0)
        self.aiDifficultyLayout.addWidget(invulnerable_player_pilots_label, 5, 0)
        self.aiDifficultyLayout.addWidget(
            invulnerable_player_pilots_checkbox, 5, 1, Qt.AlignRight
        )
        self.aiDifficultySettings.setLayout(self.aiDifficultyLayout)
        self.difficultyLayout.addWidget(self.aiDifficultySettings)

        self.missionLayout.addWidget(QLabel("Manpads on frontlines"), 0, 0)
        self.missionLayout.addWidget(self.manpads, 0, 1, Qt.AlignRight)
        self.missionLayout.addWidget(QLabel("No night missions"), 1, 0)
        self.missionLayout.addWidget(self.noNightMission, 1, 1, Qt.AlignRight)
        self.missionSettings.setLayout(self.missionLayout)
        self.difficultyLayout.addWidget(self.missionSettings)

        self.missionRestrictionsLayout.addWidget(QLabel("In Game Labels"), 0, 0)
        self.missionRestrictionsLayout.addWidget(
            self.difficultyLabel, 0, 1, Qt.AlignRight
        )
        self.missionRestrictionsLayout.addWidget(QLabel("Map visibility options"), 1, 0)
        self.missionRestrictionsLayout.addWidget(
            self.mapVisibiitySelection, 1, 1, Qt.AlignRight
        )
        self.missionRestrictionsLayout.addWidget(QLabel("Allow external views"), 2, 0)
        self.missionRestrictionsLayout.addWidget(self.ext_views, 2, 1, Qt.AlignRight)
        self.missionRestrictionsSettings.setLayout(self.missionRestrictionsLayout)
        self.difficultyLayout.addWidget(self.missionRestrictionsSettings)
コード例 #37
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.renderArea = RenderArea()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.setWindowTitle("Basic Drawing")

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

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

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

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

        if style == Qt.LinearGradientPattern:
            linearGradient = QLinearGradient(0, 0, 100, 100)
            linearGradient.setColorAt(0.0, Qt.white)
            linearGradient.setColorAt(0.2, Qt.green)
            linearGradient.setColorAt(1.0, Qt.black)
            self.renderArea.setBrush(QBrush(linearGradient))
        elif style == Qt.RadialGradientPattern:
            radialGradient = QRadialGradient(50, 50, 50, 70, 70)
            radialGradient.setColorAt(0.0, Qt.white)
            radialGradient.setColorAt(0.2, Qt.green)
            radialGradient.setColorAt(1.0, Qt.black)
            self.renderArea.setBrush(QBrush(radialGradient))
        elif style == Qt.ConicalGradientPattern:
            conicalGradient = QConicalGradient(50, 50, 150)
            conicalGradient.setColorAt(0.0, Qt.white)
            conicalGradient.setColorAt(0.2, Qt.green)
            conicalGradient.setColorAt(1.0, Qt.black)
            self.renderArea.setBrush(QBrush(conicalGradient))
        elif style == Qt.TexturePattern:
            self.renderArea.setBrush(QBrush(QPixmap(':/images/brick.png')))
        else:
            self.renderArea.setBrush(QBrush(Qt.green, style))
コード例 #38
0
class QSettingsWindow(QDialog):
    def __init__(self, game: Game):
        super().__init__()

        self.game = game
        self.pluginsPage = None
        self.pluginsOptionsPage = None
        self.campaign_management_page = QWidget()

        self.setModal(True)
        self.setWindowTitle("Settings")
        self.setWindowIcon(CONST.ICONS["Settings"])
        self.setMinimumSize(600, 250)

        self.initUi()

    def initUi(self):
        self.layout = QGridLayout()

        self.categoryList = QListView()
        self.right_layout = QStackedLayout()

        self.categoryList.setMaximumWidth(175)

        self.categoryModel = QStandardItemModel(self.categoryList)

        self.categoryList.setIconSize(QSize(32, 32))

        self.initDifficultyLayout()
        difficulty = QStandardItem("Difficulty")
        difficulty.setIcon(CONST.ICONS["Missile"])
        difficulty.setEditable(False)
        difficulty.setSelectable(True)
        self.categoryModel.appendRow(difficulty)
        self.right_layout.addWidget(self.difficultyPage)

        self.init_campaign_management_layout()
        campaign_management = QStandardItem("Campaign Management")
        campaign_management.setIcon(CONST.ICONS["Money"])
        campaign_management.setEditable(False)
        campaign_management.setSelectable(True)
        self.categoryModel.appendRow(campaign_management)
        self.right_layout.addWidget(self.campaign_management_page)

        self.initGeneratorLayout()
        generator = QStandardItem("Mission Generator")
        generator.setIcon(CONST.ICONS["Generator"])
        generator.setEditable(False)
        generator.setSelectable(True)
        self.categoryModel.appendRow(generator)
        self.right_layout.addWidget(self.generatorPage)

        self.initCheatLayout()
        cheat = QStandardItem("Cheat Menu")
        cheat.setIcon(CONST.ICONS["Cheat"])
        cheat.setEditable(False)
        cheat.setSelectable(True)
        self.categoryModel.appendRow(cheat)
        self.right_layout.addWidget(self.cheatPage)

        self.pluginsPage = PluginsPage()
        plugins = QStandardItem("LUA Plugins")
        plugins.setIcon(CONST.ICONS["Plugins"])
        plugins.setEditable(False)
        plugins.setSelectable(True)
        self.categoryModel.appendRow(plugins)
        self.right_layout.addWidget(self.pluginsPage)

        self.pluginsOptionsPage = PluginOptionsPage()
        pluginsOptions = QStandardItem("LUA Plugins Options")
        pluginsOptions.setIcon(CONST.ICONS["PluginsOptions"])
        pluginsOptions.setEditable(False)
        pluginsOptions.setSelectable(True)
        self.categoryModel.appendRow(pluginsOptions)
        self.right_layout.addWidget(self.pluginsOptionsPage)

        self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.categoryList.setModel(self.categoryModel)
        self.categoryList.selectionModel().setCurrentIndex(
            self.categoryList.indexAt(QPoint(1, 1)), QItemSelectionModel.Select
        )
        self.categoryList.selectionModel().selectionChanged.connect(
            self.onSelectionChanged
        )

        self.layout.addWidget(self.categoryList, 0, 0, 1, 1)
        self.layout.addLayout(self.right_layout, 0, 1, 5, 1)

        self.setLayout(self.layout)

    def init(self):
        pass

    def initDifficultyLayout(self):

        self.difficultyPage = QWidget()
        self.difficultyLayout = QVBoxLayout()
        self.difficultyLayout.setAlignment(Qt.AlignTop)
        self.difficultyPage.setLayout(self.difficultyLayout)

        # DCS AI difficulty settings
        self.aiDifficultySettings = QGroupBox("AI Difficulty")
        self.aiDifficultyLayout = QGridLayout()
        self.playerCoalitionSkill = QComboBox()
        self.enemyCoalitionSkill = QComboBox()
        self.enemyAASkill = QComboBox()
        for skill in CONST.SKILL_OPTIONS:
            self.playerCoalitionSkill.addItem(skill)
            self.enemyCoalitionSkill.addItem(skill)
            self.enemyAASkill.addItem(skill)

        self.playerCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.player_skill)
        )
        self.enemyCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill)
        )
        self.enemyAASkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill)
        )

        self.player_income = TenthsSpinSlider(
            "Player income multiplier",
            0,
            50,
            int(self.game.settings.player_income_multiplier * 10),
        )
        self.player_income.spinner.valueChanged.connect(self.applySettings)
        self.enemy_income = TenthsSpinSlider(
            "Enemy income multiplier",
            0,
            50,
            int(self.game.settings.enemy_income_multiplier * 10),
        )
        self.enemy_income.spinner.valueChanged.connect(self.applySettings)

        self.playerCoalitionSkill.currentIndexChanged.connect(self.applySettings)
        self.enemyCoalitionSkill.currentIndexChanged.connect(self.applySettings)
        self.enemyAASkill.currentIndexChanged.connect(self.applySettings)

        # Mission generation settings related to difficulty
        self.missionSettings = QGroupBox("Mission Difficulty")
        self.missionLayout = QGridLayout()

        self.manpads = QCheckBox()
        self.manpads.setChecked(self.game.settings.manpads)
        self.manpads.toggled.connect(self.applySettings)

        self.noNightMission = QCheckBox()
        self.noNightMission.setChecked(self.game.settings.night_disabled)
        self.noNightMission.toggled.connect(self.applySettings)

        # DCS Mission options
        self.missionRestrictionsSettings = QGroupBox("Mission Restrictions")
        self.missionRestrictionsLayout = QGridLayout()

        self.difficultyLabel = QComboBox()
        [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS]
        self.difficultyLabel.setCurrentIndex(
            CONST.LABELS_OPTIONS.index(self.game.settings.labels)
        )
        self.difficultyLabel.currentIndexChanged.connect(self.applySettings)

        self.mapVisibiitySelection = QComboBox()
        self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All:
            self.mapVisibiitySelection.setCurrentIndex(0)
        self.mapVisibiitySelection.addItem("Fog of War", ForcedOptions.Views.Allies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies:
            self.mapVisibiitySelection.setCurrentIndex(1)
        self.mapVisibiitySelection.addItem(
            "Allies Only", ForcedOptions.Views.OnlyAllies
        )
        if (
            self.game.settings.map_coalition_visibility
            == ForcedOptions.Views.OnlyAllies
        ):
            self.mapVisibiitySelection.setCurrentIndex(2)
        self.mapVisibiitySelection.addItem(
            "Own Aircraft Only", ForcedOptions.Views.MyAircraft
        )
        if (
            self.game.settings.map_coalition_visibility
            == ForcedOptions.Views.MyAircraft
        ):
            self.mapVisibiitySelection.setCurrentIndex(3)
        self.mapVisibiitySelection.addItem("Map Only", ForcedOptions.Views.OnlyMap)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap:
            self.mapVisibiitySelection.setCurrentIndex(4)
        self.mapVisibiitySelection.currentIndexChanged.connect(self.applySettings)

        self.ext_views = QCheckBox()
        self.ext_views.setChecked(self.game.settings.external_views_allowed)
        self.ext_views.toggled.connect(self.applySettings)

        def set_invulnerable_player_pilots(checked: bool) -> None:
            self.game.settings.invulnerable_player_pilots = checked

        invulnerable_player_pilots_label = QLabel(
            "Player pilots cannot be killed<br />"
            "<strong>Aircraft are vulnerable, but the player's pilot will be<br />"
            "returned to the squadron at the end of the mission</strong>"
        )

        invulnerable_player_pilots_checkbox = QCheckBox()
        invulnerable_player_pilots_checkbox.setChecked(
            self.game.settings.invulnerable_player_pilots
        )
        invulnerable_player_pilots_checkbox.toggled.connect(
            set_invulnerable_player_pilots
        )

        self.aiDifficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0)
        self.aiDifficultyLayout.addWidget(
            self.playerCoalitionSkill, 0, 1, Qt.AlignRight
        )
        self.aiDifficultyLayout.addWidget(QLabel("Enemy coalition skill"), 1, 0)
        self.aiDifficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1, Qt.AlignRight)
        self.aiDifficultyLayout.addWidget(QLabel("Enemy AA and vehicles skill"), 2, 0)
        self.aiDifficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight)
        self.aiDifficultyLayout.addLayout(self.player_income, 3, 0)
        self.aiDifficultyLayout.addLayout(self.enemy_income, 4, 0)
        self.aiDifficultyLayout.addWidget(invulnerable_player_pilots_label, 5, 0)
        self.aiDifficultyLayout.addWidget(
            invulnerable_player_pilots_checkbox, 5, 1, Qt.AlignRight
        )
        self.aiDifficultySettings.setLayout(self.aiDifficultyLayout)
        self.difficultyLayout.addWidget(self.aiDifficultySettings)

        self.missionLayout.addWidget(QLabel("Manpads on frontlines"), 0, 0)
        self.missionLayout.addWidget(self.manpads, 0, 1, Qt.AlignRight)
        self.missionLayout.addWidget(QLabel("No night missions"), 1, 0)
        self.missionLayout.addWidget(self.noNightMission, 1, 1, Qt.AlignRight)
        self.missionSettings.setLayout(self.missionLayout)
        self.difficultyLayout.addWidget(self.missionSettings)

        self.missionRestrictionsLayout.addWidget(QLabel("In Game Labels"), 0, 0)
        self.missionRestrictionsLayout.addWidget(
            self.difficultyLabel, 0, 1, Qt.AlignRight
        )
        self.missionRestrictionsLayout.addWidget(QLabel("Map visibility options"), 1, 0)
        self.missionRestrictionsLayout.addWidget(
            self.mapVisibiitySelection, 1, 1, Qt.AlignRight
        )
        self.missionRestrictionsLayout.addWidget(QLabel("Allow external views"), 2, 0)
        self.missionRestrictionsLayout.addWidget(self.ext_views, 2, 1, Qt.AlignRight)
        self.missionRestrictionsSettings.setLayout(self.missionRestrictionsLayout)
        self.difficultyLayout.addWidget(self.missionRestrictionsSettings)

    def init_campaign_management_layout(self) -> None:
        campaign_layout = QVBoxLayout()
        campaign_layout.setAlignment(Qt.AlignTop)
        self.campaign_management_page.setLayout(campaign_layout)

        general = QGroupBox("General")
        campaign_layout.addWidget(general)

        general_layout = QGridLayout()
        general.setLayout(general_layout)

        def set_restict_weapons_by_date(value: bool) -> None:
            self.game.settings.restrict_weapons_by_date = value

        restrict_weapons = QCheckBox()
        restrict_weapons.setChecked(self.game.settings.restrict_weapons_by_date)
        restrict_weapons.toggled.connect(set_restict_weapons_by_date)

        tooltip_text = (
            "Restricts weapon availability based on the campaign date. Data is "
            "extremely incomplete so does not affect all weapons."
        )
        restrict_weapons.setToolTip(tooltip_text)
        restrict_weapons_label = QLabel("Restrict weapons by date (WIP)")
        restrict_weapons_label.setToolTip(tooltip_text)

        general_layout.addWidget(restrict_weapons_label, 0, 0)
        general_layout.addWidget(restrict_weapons, 0, 1, Qt.AlignRight)

        def set_old_awec(value: bool) -> None:
            self.game.settings.disable_legacy_aewc = not value

        old_awac = QCheckBox()
        old_awac.setChecked(not self.game.settings.disable_legacy_aewc)
        old_awac.toggled.connect(set_old_awec)

        old_awec_info = (
            "If checked, an invulnerable friendly AEW&C aircraft that begins the "
            "mission on station will be be spawned. This behavior will be removed in a "
            "future release."
        )

        old_awac.setToolTip(old_awec_info)
        old_awac_label = QLabel(
            "Spawn invulnerable, always-available AEW&C aircraft (deprecated)"
        )
        old_awac_label.setToolTip(old_awec_info)

        general_layout.addWidget(old_awac_label, 1, 0)
        general_layout.addWidget(old_awac, 1, 1, Qt.AlignRight)

        def set_old_tanker(value: bool) -> None:
            self.game.settings.disable_legacy_tanker = not value

        old_tanker = QCheckBox()
        old_tanker.setChecked(not self.game.settings.disable_legacy_tanker)
        old_tanker.toggled.connect(set_old_tanker)

        old_tanker_info = (
            "If checked, an invulnerable friendly Tanker aircraft that begins the "
            "mission on station will be be spawned. This behavior will be removed in a "
            "future release."
        )

        old_tanker.setToolTip(old_tanker_info)
        old_tanker_label = QLabel(
            "Spawn invulnerable, always-available Tanker aircraft (deprecated)"
        )
        old_tanker_label.setToolTip(old_tanker_info)

        general_layout.addWidget(old_tanker_label, 2, 0)
        general_layout.addWidget(old_tanker, 2, 1, Qt.AlignRight)

        campaign_layout.addWidget(PilotSettingsBox(self.game))
        campaign_layout.addWidget(HqAutomationSettingsBox(self.game))

    def initGeneratorLayout(self):
        self.generatorPage = QWidget()
        self.generatorLayout = QVBoxLayout()
        self.generatorLayout.setAlignment(Qt.AlignTop)
        self.generatorPage.setLayout(self.generatorLayout)

        self.gameplay = QGroupBox("Gameplay")
        self.gameplayLayout = QGridLayout()
        self.gameplayLayout.setAlignment(Qt.AlignTop)
        self.gameplay.setLayout(self.gameplayLayout)

        self.supercarrier = QCheckBox()
        self.supercarrier.setChecked(self.game.settings.supercarrier)
        self.supercarrier.toggled.connect(self.applySettings)

        self.generate_marks = QCheckBox()
        self.generate_marks.setChecked(self.game.settings.generate_marks)
        self.generate_marks.toggled.connect(self.applySettings)

        self.generate_dark_kneeboard = QCheckBox()
        self.generate_dark_kneeboard.setChecked(
            self.game.settings.generate_dark_kneeboard
        )
        self.generate_dark_kneeboard.toggled.connect(self.applySettings)

        self.never_delay_players = QCheckBox()
        self.never_delay_players.setChecked(
            self.game.settings.never_delay_player_flights
        )
        self.never_delay_players.toggled.connect(self.applySettings)
        self.never_delay_players.setToolTip(
            "When checked, player flights with a delayed start time will be "
            "spawned immediately. AI wingmen may begin startup immediately."
        )

        self.desired_player_mission_duration = TimeInputs(
            "Desired mission duration",
            self.game.settings.desired_player_mission_duration,
        )
        self.desired_player_mission_duration.spinner.valueChanged.connect(
            self.applySettings
        )

        self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0)
        self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"), 1, 0)
        self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight)

        dark_kneeboard_label = QLabel(
            "Generate Dark Kneeboard <br />"
            "<strong>Dark kneeboard for night missions.<br />"
            "This will likely make the kneeboard on the pilot leg unreadable.</strong>"
        )
        self.gameplayLayout.addWidget(dark_kneeboard_label, 2, 0)
        self.gameplayLayout.addWidget(self.generate_dark_kneeboard, 2, 1, Qt.AlignRight)
        self.gameplayLayout.addLayout(
            self.desired_player_mission_duration, 5, 0, Qt.AlignRight
        )

        spawn_players_immediately_tooltip = (
            "Always spawns player aircraft immediately, even if their start time is "
            "more than 10 minutes after the start of the mission. <strong>This does "
            "not alter the timing of your mission. Your TOT will not change. This "
            "option only allows the player to wait on the ground.</strong>"
        )
        spawn_immediately_label = QLabel(
            "Player flights ignore TOT and spawn immediately<br />"
            "<strong>Does not adjust package waypoint times.<br />"
            "Should not be used if players have runway or in-air starts.</strong>"
        )
        spawn_immediately_label.setToolTip(spawn_players_immediately_tooltip)
        self.gameplayLayout.addWidget(spawn_immediately_label, 3, 0)
        self.gameplayLayout.addWidget(self.never_delay_players, 3, 1, Qt.AlignRight)

        start_type_label = QLabel(
            "Default start type for AI aircraft<br /><strong>Warning: "
            "Options other than Cold will significantly reduce the<br />"
            "number of targets available for OCA/Aircraft missions,<br />"
            "and OCA/Aircraft flights will not be included in<br />"
            "automatically planned OCA packages.</strong>"
        )
        start_type_label.setToolTip(START_TYPE_TOOLTIP)
        start_type = StartTypeComboBox(self.game.settings)
        start_type.setCurrentText(self.game.settings.default_start_type)

        self.gameplayLayout.addWidget(start_type_label, 4, 0)
        self.gameplayLayout.addWidget(start_type, 4, 1)

        self.performance = QGroupBox("Performance")
        self.performanceLayout = QGridLayout()
        self.performanceLayout.setAlignment(Qt.AlignTop)
        self.performance.setLayout(self.performanceLayout)

        self.smoke = QCheckBox()
        self.smoke.setChecked(self.game.settings.perf_smoke_gen)
        self.smoke.toggled.connect(self.applySettings)

        self.smoke_spacing = QSpinBox()
        self.smoke_spacing.setMinimum(800)
        self.smoke_spacing.setMaximum(24000)
        self.smoke_spacing.setValue(self.game.settings.perf_smoke_spacing)
        self.smoke_spacing.valueChanged.connect(self.applySettings)

        self.red_alert = QCheckBox()
        self.red_alert.setChecked(self.game.settings.perf_red_alert_state)
        self.red_alert.toggled.connect(self.applySettings)

        self.arti = QCheckBox()
        self.arti.setChecked(self.game.settings.perf_artillery)
        self.arti.toggled.connect(self.applySettings)

        self.moving_units = QCheckBox()
        self.moving_units.setChecked(self.game.settings.perf_moving_units)
        self.moving_units.toggled.connect(self.applySettings)

        self.infantry = QCheckBox()
        self.infantry.setChecked(self.game.settings.perf_infantry)
        self.infantry.toggled.connect(self.applySettings)

        self.destroyed_units = QCheckBox()
        self.destroyed_units.setChecked(self.game.settings.perf_destroyed_units)
        self.destroyed_units.toggled.connect(self.applySettings)

        self.culling = QCheckBox()
        self.culling.setChecked(self.game.settings.perf_culling)
        self.culling.toggled.connect(self.applySettings)

        self.culling_distance = QSpinBox()
        self.culling_distance.setMinimum(10)
        self.culling_distance.setMaximum(10000)
        self.culling_distance.setValue(self.game.settings.perf_culling_distance)
        self.culling_distance.valueChanged.connect(self.applySettings)

        self.culling_do_not_cull_carrier = QCheckBox()
        self.culling_do_not_cull_carrier.setChecked(
            self.game.settings.perf_do_not_cull_carrier
        )
        self.culling_do_not_cull_carrier.toggled.connect(self.applySettings)

        self.performanceLayout.addWidget(
            QLabel("Smoke visual effect on frontline"), 0, 0
        )
        self.performanceLayout.addWidget(self.smoke, 0, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Smoke generator spacing (higher means less smoke)"),
            1,
            0,
            alignment=Qt.AlignRight,
        )
        self.performanceLayout.addWidget(
            self.smoke_spacing, 1, 1, alignment=Qt.AlignRight
        )
        self.performanceLayout.addWidget(QLabel("SAM starts in RED alert mode"), 2, 0)
        self.performanceLayout.addWidget(self.red_alert, 2, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Artillery strikes"), 3, 0)
        self.performanceLayout.addWidget(self.arti, 3, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Moving ground units"), 4, 0)
        self.performanceLayout.addWidget(
            self.moving_units, 4, 1, alignment=Qt.AlignRight
        )
        self.performanceLayout.addWidget(
            QLabel("Generate infantry squads along vehicles"), 5, 0
        )
        self.performanceLayout.addWidget(self.infantry, 5, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Include destroyed units carcass"), 6, 0
        )
        self.performanceLayout.addWidget(
            self.destroyed_units, 6, 1, alignment=Qt.AlignRight
        )

        self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1, 2)
        self.performanceLayout.addWidget(
            QLabel("Culling of distant units enabled"), 8, 0
        )
        self.performanceLayout.addWidget(self.culling, 8, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0)
        self.performanceLayout.addWidget(
            self.culling_distance, 9, 1, alignment=Qt.AlignRight
        )
        self.performanceLayout.addWidget(
            QLabel("Do not cull carrier's surroundings"), 10, 0
        )
        self.performanceLayout.addWidget(
            self.culling_do_not_cull_carrier, 10, 1, alignment=Qt.AlignRight
        )

        self.generatorLayout.addWidget(self.gameplay)
        self.generatorLayout.addWidget(
            QLabel(
                "Disabling settings below may improve performance, but will impact the overall quality of the experience."
            )
        )
        self.generatorLayout.addWidget(self.performance)

    def initCheatLayout(self):

        self.cheatPage = QWidget()
        self.cheatLayout = QVBoxLayout()
        self.cheatPage.setLayout(self.cheatLayout)

        self.cheat_options = CheatSettingsBox(self.game, self.applySettings)
        self.cheatLayout.addWidget(self.cheat_options)

        self.moneyCheatBox = QGroupBox("Money Cheat")
        self.moneyCheatBox.setAlignment(Qt.AlignTop)
        self.moneyCheatBoxLayout = QGridLayout()
        self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout)

        cheats_amounts = [25, 50, 100, 200, 500, 1000, -25, -50, -100, -200]
        for i, amount in enumerate(cheats_amounts):
            if amount > 0:
                btn = QPushButton("Cheat +" + str(amount) + "M")
                btn.setProperty("style", "btn-success")
            else:
                btn = QPushButton("Cheat " + str(amount) + "M")
                btn.setProperty("style", "btn-danger")
            btn.clicked.connect(self.cheatLambda(amount))
            self.moneyCheatBoxLayout.addWidget(btn, i / 2, i % 2)
        self.cheatLayout.addWidget(self.moneyCheatBox, stretch=1)

    def cheatLambda(self, amount):
        return lambda: self.cheatMoney(amount)

    def cheatMoney(self, amount):
        logging.info("CHEATING FOR AMOUNT : " + str(amount) + "M")
        self.game.budget += amount
        if amount > 0:
            self.game.informations.append(
                Information(
                    "CHEATER",
                    "You are a cheater and you should feel bad",
                    self.game.turn,
                )
            )
        else:
            self.game.informations.append(
                Information("CHEATER", "You are still a cheater !", self.game.turn)
            )
        GameUpdateSignal.get_instance().updateGame(self.game)

    def applySettings(self):
        self.game.settings.player_skill = CONST.SKILL_OPTIONS[
            self.playerCoalitionSkill.currentIndex()
        ]
        self.game.settings.enemy_skill = CONST.SKILL_OPTIONS[
            self.enemyCoalitionSkill.currentIndex()
        ]
        self.game.settings.enemy_vehicle_skill = CONST.SKILL_OPTIONS[
            self.enemyAASkill.currentIndex()
        ]
        self.game.settings.player_income_multiplier = self.player_income.value
        self.game.settings.enemy_income_multiplier = self.enemy_income.value
        self.game.settings.manpads = self.manpads.isChecked()
        self.game.settings.labels = CONST.LABELS_OPTIONS[
            self.difficultyLabel.currentIndex()
        ]
        self.game.settings.night_disabled = self.noNightMission.isChecked()
        self.game.settings.map_coalition_visibility = (
            self.mapVisibiitySelection.currentData()
        )
        self.game.settings.external_views_allowed = self.ext_views.isChecked()
        self.game.settings.generate_marks = self.generate_marks.isChecked()
        self.game.settings.never_delay_player_flights = (
            self.never_delay_players.isChecked()
        )

        self.game.settings.supercarrier = self.supercarrier.isChecked()

        self.game.settings.generate_dark_kneeboard = (
            self.generate_dark_kneeboard.isChecked()
        )

        self.game.settings.desired_player_mission_duration = (
            self.desired_player_mission_duration.value
        )

        self.game.settings.perf_red_alert_state = self.red_alert.isChecked()
        self.game.settings.perf_smoke_gen = self.smoke.isChecked()
        self.game.settings.perf_smoke_spacing = self.smoke_spacing.value()
        self.game.settings.perf_artillery = self.arti.isChecked()
        self.game.settings.perf_moving_units = self.moving_units.isChecked()
        self.game.settings.perf_infantry = self.infantry.isChecked()
        self.game.settings.perf_destroyed_units = self.destroyed_units.isChecked()

        self.game.settings.perf_culling = self.culling.isChecked()
        self.game.settings.perf_culling_distance = int(self.culling_distance.value())
        self.game.settings.perf_do_not_cull_carrier = (
            self.culling_do_not_cull_carrier.isChecked()
        )

        self.game.settings.show_red_ato = self.cheat_options.show_red_ato
        self.game.settings.enable_frontline_cheats = (
            self.cheat_options.show_frontline_cheat
        )
        self.game.settings.enable_base_capture_cheat = (
            self.cheat_options.show_base_capture_cheat
        )

        self.game.compute_conflicts_position()
        GameUpdateSignal.get_instance().updateGame(self.game)

    def onSelectionChanged(self):
        index = self.categoryList.selectionModel().currentIndex().row()
        self.right_layout.setCurrentIndex(index)
コード例 #39
0
    def _init_cfg_options_tab(self, tab):
        resolve_indirect_jumps = QCheckBox(self)
        resolve_indirect_jumps.setText('Resolve indirect jumps')
        resolve_indirect_jumps.setChecked(True)
        self.option_widgets['resolve_indirect_jumps'] = resolve_indirect_jumps

        collect_data_refs = QCheckBox(self)
        collect_data_refs.setText(
            'Collect cross-references and infer data types')
        collect_data_refs.setChecked(True)
        self.option_widgets['collect_data_refs'] = collect_data_refs

        layout = QVBoxLayout()
        layout.addWidget(resolve_indirect_jumps)
        layout.addWidget(collect_data_refs)
        layout.addStretch(0)
        frame = QFrame(self)
        frame.setLayout(layout)
        tab.addTab(frame, 'CFG Options')
コード例 #40
0
    def init_campaign_management_layout(self) -> None:
        campaign_layout = QVBoxLayout()
        campaign_layout.setAlignment(Qt.AlignTop)
        self.campaign_management_page.setLayout(campaign_layout)

        general = QGroupBox("General")
        campaign_layout.addWidget(general)

        general_layout = QGridLayout()
        general.setLayout(general_layout)

        def set_restict_weapons_by_date(value: bool) -> None:
            self.game.settings.restrict_weapons_by_date = value

        restrict_weapons = QCheckBox()
        restrict_weapons.setChecked(self.game.settings.restrict_weapons_by_date)
        restrict_weapons.toggled.connect(set_restict_weapons_by_date)

        tooltip_text = (
            "Restricts weapon availability based on the campaign date. Data is "
            "extremely incomplete so does not affect all weapons."
        )
        restrict_weapons.setToolTip(tooltip_text)
        restrict_weapons_label = QLabel("Restrict weapons by date (WIP)")
        restrict_weapons_label.setToolTip(tooltip_text)

        general_layout.addWidget(restrict_weapons_label, 0, 0)
        general_layout.addWidget(restrict_weapons, 0, 1, Qt.AlignRight)

        def set_old_awec(value: bool) -> None:
            self.game.settings.disable_legacy_aewc = not value

        old_awac = QCheckBox()
        old_awac.setChecked(not self.game.settings.disable_legacy_aewc)
        old_awac.toggled.connect(set_old_awec)

        old_awec_info = (
            "If checked, an invulnerable friendly AEW&C aircraft that begins the "
            "mission on station will be be spawned. This behavior will be removed in a "
            "future release."
        )

        old_awac.setToolTip(old_awec_info)
        old_awac_label = QLabel(
            "Spawn invulnerable, always-available AEW&C aircraft (deprecated)"
        )
        old_awac_label.setToolTip(old_awec_info)

        general_layout.addWidget(old_awac_label, 1, 0)
        general_layout.addWidget(old_awac, 1, 1, Qt.AlignRight)

        def set_old_tanker(value: bool) -> None:
            self.game.settings.disable_legacy_tanker = not value

        old_tanker = QCheckBox()
        old_tanker.setChecked(not self.game.settings.disable_legacy_tanker)
        old_tanker.toggled.connect(set_old_tanker)

        old_tanker_info = (
            "If checked, an invulnerable friendly Tanker aircraft that begins the "
            "mission on station will be be spawned. This behavior will be removed in a "
            "future release."
        )

        old_tanker.setToolTip(old_tanker_info)
        old_tanker_label = QLabel(
            "Spawn invulnerable, always-available Tanker aircraft (deprecated)"
        )
        old_tanker_label.setToolTip(old_tanker_info)

        general_layout.addWidget(old_tanker_label, 2, 0)
        general_layout.addWidget(old_tanker, 2, 1, Qt.AlignRight)

        campaign_layout.addWidget(PilotSettingsBox(self.game))
        campaign_layout.addWidget(HqAutomationSettingsBox(self.game))
コード例 #41
0
class UserExportedAttributeWidget(mayaMixin.MayaQWidgetDockableMixin, QWidget):

    _currentInstance = None

    @classmethod
    def closeCurrentInstance(cls):
        if cls._currentInstance is not None:
            if cls._currentInstance._mayaSelectionChangedJob is not None:
                cmds.scriptJob(kill=cls._currentInstance._mayaSelectionChangedJob)
                cls._currentInstance._mayaSelectionChangedJob = None

            if cls._currentInstance._mayaUndoJob is not None:
                cmds.scriptJob(kill=cls._currentInstance._mayaUndoJob)
                cls._currentInstance._mayaUndoJob = None

            if cls._currentInstance._mayaRedoJob is not None:
                cmds.scriptJob(kill=cls._currentInstance._mayaRedoJob)
                cls._currentInstance._mayaRedoJob = None

            cls._currentInstance.close()
            cls._currentInstance = None

    def __init__(self, parent=None):
        UserExportedAttributeWidget.closeCurrentInstance()

        super(UserExportedAttributeWidget, self).__init__(parent=parent)
        self._setupUI()

        self._mayaSelectionChangedJob = cmds.scriptJob(event=["SelectionChanged", self._syncUI])
        self._mayaUndoJob = cmds.scriptJob(event=["Undo", self._syncUI])
        self._mayaRedoJob = cmds.scriptJob(event=["Redo", self._syncUI])

        UserExportedAttributeWidget._currentInstance = self

        # Force a sync on the first load.
        self._syncUI()

    def _setupUI(self):
        self.setWindowTitle("Export Attributes to USD")
        layout = QVBoxLayout()

        # This section contains the attributes tagged for export.
        label = QLabel()
        label.setText('Exported Attributes:')
        layout.addWidget(label)

        self.exportedAttrsModel = ExportedAttributesModel()
        self.exportedAttrsView = ExportedAttributesView()
        self.exportedAttrsView.verticalHeader().hide()
        self.exportedAttrsView.setModel(self.exportedAttrsModel)
        selectionModel = self.exportedAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(self._onExportedAttrsSelectionChanged)
        self.exportedAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.exportedAttrsView)

        self.removeExportedAttrButton = QPushButton("Remove Exported Attribute")
        self.removeExportedAttrButton.clicked.connect(self._onRemoveExportedAttrPressed)
        self.removeExportedAttrButton.setEnabled(False)
        layout.addWidget(self.removeExportedAttrButton)

        # This section contains the attributes available for export.
        label = QLabel()
        label.setText('Available Attributes:')
        layout.addWidget(label)

        self.userDefinedCheckBox = QCheckBox('User Defined')
        self.userDefinedCheckBox.setToolTip('Show only user-defined (dynamic) attributes')
        self.userDefinedCheckBox.setChecked(True)
        self.userDefinedCheckBox.stateChanged.connect(self._syncUI)
        layout.addWidget(self.userDefinedCheckBox)

        self.addAttrsModel = AddAttributesModel()
        self.addAttrsView = AddAttributesView()
        self.addAttrsView.setModel(self.addAttrsModel)
        selectionModel = self.addAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(self._onAddAttrsSelectionChanged)
        self.addAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.addAttrsView)

        self.addExportedAttrButton = QPushButton("Add Exported Attribute")
        self.addExportedAttrButton.clicked.connect(self._onAddExportedAttrPressed)
        self.addExportedAttrButton.setEnabled(False)
        layout.addWidget(self.addExportedAttrButton)

        self.setLayout(layout)

    def _onExportedAttrsSelectionChanged(self, selected, deselected):
        if selected.isEmpty():
            self.removeExportedAttrButton.setEnabled(False)
        else:
            self.removeExportedAttrButton.setEnabled(True)

    def _onAddAttrsSelectionChanged(self, selected, deselected):
        if selected.isEmpty():
            self.addExportedAttrButton.setEnabled(False)
        else:
            self.addExportedAttrButton.setEnabled(True)

    def _onRemoveExportedAttrPressed(self):
        selectedNodeNames = cmds.ls(selection=True, long=True)
        if not selectedNodeNames:
            return

        mayaAttrNames = [x.data() for x in self.exportedAttrsView.selectedIndexes()]
        if not mayaAttrNames:
            return

        for selectedNodeName in selectedNodeNames:
            ExportedAttribute.RemoveExportedAttributesForNode(selectedNodeName,
                mayaAttrNames)

        self._syncUI()

    def _onAddExportedAttrPressed(self):
        selectedNodeNames = cmds.ls(selection=True, long=True)
        if not selectedNodeNames:
            return

        exportedAttrs = [ExportedAttribute(x.data()) for x in self.addAttrsView.selectedIndexes()]
        if not exportedAttrs:
            return

        for selectedNodeName in selectedNodeNames:
            ExportedAttribute.UpdateExportedAttributesForNode(selectedNodeName,
                exportedAttrs)

        self._syncUI()

    def _onModelDataChanged(self, topLeft, bottomRight):
        self._syncUI()

    def _syncUI(self):
        # Since _syncUI is called in response to events that invalidate/clear
        # the selections in the views, disable the buttons until something is
        # selected again.
        self.removeExportedAttrButton.setEnabled(False)
        self.addExportedAttrButton.setEnabled(False)

        selectedNodeNames = cmds.ls(selection=True, long=True)
        if not selectedNodeNames:
            self.addAttrsModel.setStringList([])
            self.exportedAttrsModel.exportedAttributes = []
            self.exportedAttrsView.resizeColumnsToContents()
            return

        # Collect the export attributes common to all selected nodes. If the
        # same attribute is configured differently on multiple objects (e.g.
        # different usdAttrName), then do not include that attribute.
        allExportedAttributeNames = set()
        commonExportedAttributeNames = set()
        commonExportedAttrs = {}
        for exportedAttr in ExportedAttribute.GetExportedAttributesFromNode(selectedNodeNames[0]):
            mayaAttrName = exportedAttr.mayaAttrName
            allExportedAttributeNames.add(mayaAttrName)
            commonExportedAttributeNames.add(mayaAttrName)
            commonExportedAttrs[mayaAttrName] = exportedAttr

        for selectedNodeName in selectedNodeNames[1:]:
            exportedAttrNames = set()
            for exportedAttr in ExportedAttribute.GetExportedAttributesFromNode(selectedNodeName):
                mayaAttrName = exportedAttr.mayaAttrName
                allExportedAttributeNames.add(mayaAttrName)
                if (mayaAttrName in commonExportedAttrs and
                        commonExportedAttrs[mayaAttrName] == exportedAttr):
                    exportedAttrNames.add(mayaAttrName)
            commonExportedAttributeNames.intersection_update(exportedAttrNames)

        commonExportedAttrs = [commonExportedAttrs[x] for x in commonExportedAttributeNames]
        commonExportedAttrs.sort(key=lambda x: x.mayaAttrName)
        self.exportedAttrsModel.exportedAttributes = commonExportedAttrs

        # Normally, the combo boxes for selecting usdAttrType and
        # primvarInterpolation would only appear when the table cell is put into
        # edit mode. Instead, we want the combo boxes to always be visible, so
        # we tell the view to open them as persistent editors.
        for row in xrange(self.exportedAttrsModel.rowCount()):
            usdAttrTypeIndex = self.exportedAttrsModel.index(row,
                ExportedAttributesModel.USD_ATTR_TYPE_COLUMN)
            self.exportedAttrsView.openPersistentEditor(usdAttrTypeIndex)

            # Only open the interpolation editor if this is a primvar.
            if self.exportedAttrsModel.data(usdAttrTypeIndex) == USD_ATTR_TYPE_PRIMVAR:
                primvarInterpolationIndex = self.exportedAttrsModel.index(row,
                    ExportedAttributesModel.PRIMVAR_INTERPOLATION_COLUMN)
                self.exportedAttrsView.openPersistentEditor(primvarInterpolationIndex)

            # Only open the double-to-single precision editor if the Maya
            # attribute is double-based.
            mayaAttrNameIndex = self.exportedAttrsModel.index(row,
                ExportedAttributesModel.MAYA_ATTR_NAME_COLUMN)
            mayaAttrName = self.exportedAttrsModel.data(mayaAttrNameIndex)
            if _ShouldEnableDoublePrecisionEditor(mayaAttrName):
                doublePrecisionIndex = self.exportedAttrsModel.index(row,
                    ExportedAttributesModel.DOUBLE_PRECISION_COLUMN)
                self.exportedAttrsView.openPersistentEditor(doublePrecisionIndex)

        self.exportedAttrsView.resizeColumnsToContents()

        # Collect the attributes common to all selected nodes.
        cmdOptions = {'read': True}
        if self.userDefinedCheckBox.isChecked():
            cmdOptions['userDefined'] = True

        commonAttrNames = set(cmds.listAttr(selectedNodeNames[0], **cmdOptions) or [])
        for selectedNodeName in selectedNodeNames[1:]:
            attrNames = set(cmds.listAttr(selectedNodeName, **cmdOptions) or [])
            commonAttrNames.intersection_update(attrNames)

        # Subtract out reserved attribute names and attributes already being
        # exported by ANY node.
        commonAttrNames -= RESERVED_ATTRIBUTES
        commonAttrNames -= allExportedAttributeNames

        self.addAttrsModel.setStringList(sorted(list(commonAttrNames)))
コード例 #42
0
ファイル: plots.py プロジェクト: nsidere/sherloq
class PlotsWidget(ToolWidget):
    def __init__(self, image, parent=None):
        super(PlotsWidget, self).__init__(parent)

        choices = ["Red", "Green", "Blue", "Hue", "Saturation", "Value"]
        self.xaxis_combo = QComboBox()
        self.xaxis_combo.addItems(choices)
        self.xaxis_combo.setCurrentIndex(3)
        self.yaxis_combo = QComboBox()
        self.yaxis_combo.addItems(choices)
        self.yaxis_combo.setCurrentIndex(4)
        self.zaxis_combo = QComboBox()
        self.zaxis_combo.addItems(choices)
        self.zaxis_combo.setCurrentIndex(5)
        self.sampling_spin = QSpinBox()
        levels = int(np.log2(min(image.shape[:-1])))
        self.sampling_spin.setRange(0, levels)
        self.sampling_spin.setSpecialValueText(self.tr("Off"))
        # self.sampling_spin.setSuffix(self.tr(' level(s)'))
        self.sampling_spin.setValue(1)
        self.size_spin = QSpinBox()
        self.size_spin.setRange(1, 10)
        self.size_spin.setValue(1)
        self.size_spin.setSuffix(self.tr(" pt"))
        self.markers = [
            ",", ".", "o", "8", "s", "p", "P", "*", "h", "H", "X", "D"
        ]
        self.alpha_spin = QDoubleSpinBox()
        self.alpha_spin.setRange(0, 1)
        self.alpha_spin.setDecimals(2)
        self.alpha_spin.setSingleStep(0.05)
        self.alpha_spin.setValue(1)
        self.colors_check = QCheckBox(self.tr("Show colors"))
        self.grid_check = QCheckBox(self.tr("Show grid"))
        self.norm_check = QCheckBox(self.tr("Normalized"))
        self.total_label = QLabel()

        img = np.copy(image)
        self.colors = [None] * (levels + 1)
        for scale in range(levels + 1):
            rgb = cv.cvtColor(img.astype(np.float32) / 255, cv.COLOR_BGR2RGB)
            hsv = cv.cvtColor(rgb, cv.COLOR_RGB2HSV)
            hsv[:, :, 0] /= 360
            shape = (img.shape[0] * img.shape[1], img.shape[2])
            self.colors[scale] = np.concatenate(
                (np.reshape(rgb, shape), np.reshape(hsv, shape)), axis=1)
            img = cv.pyrDown(img)

        figure2 = Figure()
        plot2_canvas = FigureCanvas(figure2)
        self.axes2 = plot2_canvas.figure.subplots()
        toolbar2 = NavigationToolbar(plot2_canvas, self)
        plot2_layout = QVBoxLayout()
        plot2_layout.addWidget(plot2_canvas)
        plot2_layout.addWidget(toolbar2)
        plot2_widget = QWidget()
        plot2_widget.setLayout(plot2_layout)

        figure3 = Figure()
        plot3_canvas = FigureCanvas(figure3)
        self.axes3 = plot3_canvas.figure.add_subplot(111, projection="3d")
        toolbar3 = NavigationToolbar(plot3_canvas, self)
        plot3_layout = QVBoxLayout()
        plot3_layout.addWidget(plot3_canvas)
        plot3_layout.addWidget(toolbar3)
        plot3_widget = QWidget()
        plot3_widget.setLayout(plot3_layout)

        self.tab_widget = QTabWidget()
        self.tab_widget.addTab(plot2_widget, "2D Plot")
        self.tab_widget.addTab(plot3_widget, "3D Plot")
        self.redraw()
        figure2.set_tight_layout(True)
        figure3.set_tight_layout(True)

        self.xaxis_combo.currentIndexChanged.connect(self.redraw)
        self.yaxis_combo.currentIndexChanged.connect(self.redraw)
        self.zaxis_combo.currentIndexChanged.connect(self.redraw)
        self.sampling_spin.valueChanged.connect(self.redraw)
        self.size_spin.valueChanged.connect(self.redraw)
        self.alpha_spin.valueChanged.connect(self.redraw)
        self.colors_check.stateChanged.connect(self.redraw)
        self.grid_check.stateChanged.connect(self.redraw)
        self.norm_check.stateChanged.connect(self.redraw)
        self.tab_widget.currentChanged.connect(self.redraw)

        params_layout = QGridLayout()
        params_layout.addWidget(QLabel(self.tr("X axis:")), 0, 0)
        params_layout.addWidget(self.xaxis_combo, 0, 1)
        params_layout.addWidget(QLabel(self.tr("Y axis:")), 1, 0)
        params_layout.addWidget(self.yaxis_combo, 1, 1)
        params_layout.addWidget(QLabel(self.tr("Z axis:")), 2, 0)
        params_layout.addWidget(self.zaxis_combo, 2, 1)
        params_layout.addWidget(QLabel(self.tr("Subsampling:")), 0, 2)
        params_layout.addWidget(self.sampling_spin, 0, 3)
        params_layout.addWidget(QLabel(self.tr("Point size:")), 1, 2)
        params_layout.addWidget(self.size_spin, 1, 3)
        params_layout.addWidget(QLabel(self.tr("Point alpha:")), 2, 2)
        params_layout.addWidget(self.alpha_spin, 2, 3)
        params_layout.addWidget(self.colors_check, 0, 4)
        params_layout.addWidget(self.grid_check, 1, 4)
        params_layout.addWidget(self.total_label, 2, 4)
        bottom_layout = QHBoxLayout()
        bottom_layout.addLayout(params_layout)
        bottom_layout.addStretch()

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.tab_widget)
        main_layout.addLayout(bottom_layout)
        self.setLayout(main_layout)

    def redraw(self):
        start = time()
        v = self.sampling_spin.value()
        x = self.colors[v][:, self.xaxis_combo.currentIndex()]
        y = self.colors[v][:, self.yaxis_combo.currentIndex()]
        s = self.size_spin.value()**2
        c = None if not self.colors_check.isChecked(
        ) else self.colors[v][:, :3]

        if self.tab_widget.currentIndex() == 0:
            self.zaxis_combo.setEnabled(False)
            self.grid_check.setEnabled(True)
            self.alpha_spin.setEnabled(True)
            a = self.alpha_spin.value()
            xlim = self.axes2.get_xlim()
            ylim = self.axes2.get_ylim()
            self.axes2.clear()
            self.axes2.set_facecolor([0.5] * 3 if c is not None else [1.0] * 3)
            self.axes2.scatter(x, y, s, c, ".", alpha=a)
            self.axes2.set_xlabel(self.xaxis_combo.currentText())
            self.axes2.set_ylabel(self.yaxis_combo.currentText())
            self.axes2.grid(self.grid_check.isChecked(), which="both")
            self.axes2.set_xlim(xlim)
            self.axes2.set_ylim(ylim)
            self.axes2.figure.canvas.draw()
        else:
            self.zaxis_combo.setEnabled(True)
            self.grid_check.setEnabled(False)
            self.alpha_spin.setEnabled(False)
            z = self.colors[v][:, self.zaxis_combo.currentIndex()]
            self.axes3.clear()
            self.axes3.set_facecolor([0.5] * 3 if c is not None else [1.0] * 3)
            self.axes3.scatter(x, y, z, s=s, c=c, marker=".", depthshade=True)
            self.axes3.set_xlabel(self.xaxis_combo.currentText())
            self.axes3.set_ylabel(self.yaxis_combo.currentText())
            self.axes3.set_zlabel(self.zaxis_combo.currentText())
            self.axes3.grid(self.grid_check.isChecked(), which="both")
            self.axes3.figure.canvas.draw()

        self.total_label.setText(self.tr(f"[{len(x)} points]"))
        self.info_message.emit(f"Plot redraw = {elapsed_time(start)}")
コード例 #43
0
ファイル: ToolBox.py プロジェクト: bakhyeonjae/Sherlock
    def __init__(self, mode, parentQWidget = None):
        QVBoxLayout.__init__(self)

        self.sig.connect(self.addThreadList)
        self.mode = mode

        self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)

        self.groupBoxSearch = QGroupBox()
        self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };")
        vboxSearch = QVBoxLayout()
        self.searchTitle = QLabel("Search Messages")
        vboxSearch.addWidget(self.searchTitle)
        self.searchHLayout = QHBoxLayout()
        self.editTextSearch = QTextEdit('')
        self.editTextSearch.setFixedSize(200,30)
        self.buttonSearch = QPushButton('Search')
        self.buttonSearch.setFixedSize(100,30)
        self.buttonSearch.clicked.connect(self.searchMsg)
        vboxSearch.addWidget(self.editTextSearch)
        self.searchHLayout.addWidget(self.buttonSearch)
        self.searchCursor = QLabel()
        self.searchHLayout.addWidget(self.searchCursor)
        vboxSearch.addLayout(self.searchHLayout)
        self.browseHLayout = QHBoxLayout()
        self.buttonLookUp = QPushButton('\u21e7')  #Arrow up
        self.buttonLookUp.setFixedWidth(100)
        self.buttonLookUp.clicked.connect(self.moveToPrev)
        self.buttonLookDown = QPushButton('\u21e9') #Arrow down
        self.buttonLookDown.setFixedWidth(100)
        self.buttonLookDown.clicked.connect(self.moveToNext)
        self.browseHLayout.addWidget(self.buttonLookUp)
        self.browseHLayout.addWidget(self.buttonLookDown)
        vboxSearch.addLayout(self.browseHLayout)
        self.groupBoxSearch.setLayout(vboxSearch)
        self.addWidget(self.groupBoxSearch)
        self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.buttonHiddenLifelines = QPushButton('Show hidden life-lines')
        self.buttonHiddenLifelines.setFixedWidth(200)
        self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines)
        self.addWidget(self.buttonHiddenLifelines)

        self.buttonHiddenMessages = QPushButton('Show hidden Messages')
        self.buttonHiddenMessages.setFixedWidth(200)
        self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages)
        self.addWidget(self.buttonHiddenMessages)

        if const.mode_interactive == mode:
            self.buttonCapture = QPushButton('Capture')
            self.buttonCapture.setFixedWidth(200)
            self.buttonCapture.clicked.connect(self.notifyCapture)
            self.addWidget(self.buttonCapture)
        self.msgRcv = []
        self.msgInfo = QLabel("Message Info.")
        self.groupBoxMessageInfo = QGroupBox()
        self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")
        vbox = QVBoxLayout()
        vbox.addWidget(self.msgInfo)
        self.tableTime = QTableWidget(3,2)
        self.tableTime.setHorizontalHeaderLabels(['-','time'])
        self.tableTime.setColumnWidth(0,80)
        self.tableTime.setColumnWidth(1,150)
        vwidth = self.tableTime.verticalHeader().length()
        hwidth = self.tableTime.horizontalHeader().height()
        fwidth = self.tableTime.frameWidth() * 2
        self.tableTime.setFixedHeight(vwidth + hwidth + fwidth)
        self.tableTime.horizontalHeader().setStretchLastSection(True)
        self.tableTime.setItem(0,0,QTableWidgetItem('begin'))
        self.tableTime.setItem(0,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(1,0,QTableWidgetItem('end'))
        self.tableTime.setItem(1,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(2,0,QTableWidgetItem('duration'))
        self.tableTime.setItem(2,1,QTableWidgetItem(' - '))
        vbox.addWidget(self.tableTime)

        self.titleArg = QLabel('Argument List')
        vbox.addWidget(self.titleArg)

        max_arg_num = 10
        self.tableArgs = QTableWidget(max_arg_num,2)
        self.tableArgs.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_arg_num):
            self.tableArgs.setItem(idx,0,QTableWidgetItem())
            self.tableArgs.setItem(idx,1,QTableWidgetItem())
        self.tableArgs.horizontalHeader().setStretchLastSection(True)
        vbox.addWidget(self.tableArgs)

        self.titleArg = QLabel('Return Value List')
        vbox.addWidget(self.titleArg)

        max_ret_num = 4
        self.tableRet = QTableWidget(max_ret_num,2)
        self.tableRet.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_ret_num):
            self.tableRet.setItem(idx,0,QTableWidgetItem())
            self.tableRet.setItem(idx,1,QTableWidgetItem())
        self.tableRet.horizontalHeader().setStretchLastSection(True)
        vwidth = self.tableRet.verticalHeader().length()
        hwidth = self.tableRet.horizontalHeader().height()
        fwidth = self.tableRet.frameWidth() * 2
        self.tableRet.setFixedHeight(vwidth + hwidth + fwidth)
        vbox.addWidget(self.tableRet)

        self.buttonSrcView = QPushButton('view code')
        self.buttonSrcView.setFixedWidth(200)
        self.buttonSrcView.clicked.connect(self.openSourceViewer)
        self.buttonHide = QPushButton('Hide')
        self.buttonHide.setFixedWidth(200)
        self.buttonHide.clicked.connect(self.notifyHide)
        self.buttonHideAllMsg = QPushButton('Hide All')
        self.buttonHideAllMsg.setFixedWidth(200)
        self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected)
        self.groupBoxMessageInfo.setLayout(vbox)
        self.checkHideCircular = QCheckBox('Hide Circular Messages')
        self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked)
        self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage)
        self.addWidget(self.checkHideCircular)
        self.addWidget(self.groupBoxMessageInfo)
        self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)
コード例 #44
0
ファイル: bug_860.py プロジェクト: BadSingleton/pyside2
 def testSimpleSignal(self):
     box = QCheckBox('check me')
     box.stateChanged[int].connect(self.cb_changedVoid)
     self._changed = False
     box.setChecked(True)
     self.assert_(self._changed)
コード例 #45
0
ファイル: plots.py プロジェクト: nsidere/sherloq
    def __init__(self, image, parent=None):
        super(PlotsWidget, self).__init__(parent)

        choices = ["Red", "Green", "Blue", "Hue", "Saturation", "Value"]
        self.xaxis_combo = QComboBox()
        self.xaxis_combo.addItems(choices)
        self.xaxis_combo.setCurrentIndex(3)
        self.yaxis_combo = QComboBox()
        self.yaxis_combo.addItems(choices)
        self.yaxis_combo.setCurrentIndex(4)
        self.zaxis_combo = QComboBox()
        self.zaxis_combo.addItems(choices)
        self.zaxis_combo.setCurrentIndex(5)
        self.sampling_spin = QSpinBox()
        levels = int(np.log2(min(image.shape[:-1])))
        self.sampling_spin.setRange(0, levels)
        self.sampling_spin.setSpecialValueText(self.tr("Off"))
        # self.sampling_spin.setSuffix(self.tr(' level(s)'))
        self.sampling_spin.setValue(1)
        self.size_spin = QSpinBox()
        self.size_spin.setRange(1, 10)
        self.size_spin.setValue(1)
        self.size_spin.setSuffix(self.tr(" pt"))
        self.markers = [
            ",", ".", "o", "8", "s", "p", "P", "*", "h", "H", "X", "D"
        ]
        self.alpha_spin = QDoubleSpinBox()
        self.alpha_spin.setRange(0, 1)
        self.alpha_spin.setDecimals(2)
        self.alpha_spin.setSingleStep(0.05)
        self.alpha_spin.setValue(1)
        self.colors_check = QCheckBox(self.tr("Show colors"))
        self.grid_check = QCheckBox(self.tr("Show grid"))
        self.norm_check = QCheckBox(self.tr("Normalized"))
        self.total_label = QLabel()

        img = np.copy(image)
        self.colors = [None] * (levels + 1)
        for scale in range(levels + 1):
            rgb = cv.cvtColor(img.astype(np.float32) / 255, cv.COLOR_BGR2RGB)
            hsv = cv.cvtColor(rgb, cv.COLOR_RGB2HSV)
            hsv[:, :, 0] /= 360
            shape = (img.shape[0] * img.shape[1], img.shape[2])
            self.colors[scale] = np.concatenate(
                (np.reshape(rgb, shape), np.reshape(hsv, shape)), axis=1)
            img = cv.pyrDown(img)

        figure2 = Figure()
        plot2_canvas = FigureCanvas(figure2)
        self.axes2 = plot2_canvas.figure.subplots()
        toolbar2 = NavigationToolbar(plot2_canvas, self)
        plot2_layout = QVBoxLayout()
        plot2_layout.addWidget(plot2_canvas)
        plot2_layout.addWidget(toolbar2)
        plot2_widget = QWidget()
        plot2_widget.setLayout(plot2_layout)

        figure3 = Figure()
        plot3_canvas = FigureCanvas(figure3)
        self.axes3 = plot3_canvas.figure.add_subplot(111, projection="3d")
        toolbar3 = NavigationToolbar(plot3_canvas, self)
        plot3_layout = QVBoxLayout()
        plot3_layout.addWidget(plot3_canvas)
        plot3_layout.addWidget(toolbar3)
        plot3_widget = QWidget()
        plot3_widget.setLayout(plot3_layout)

        self.tab_widget = QTabWidget()
        self.tab_widget.addTab(plot2_widget, "2D Plot")
        self.tab_widget.addTab(plot3_widget, "3D Plot")
        self.redraw()
        figure2.set_tight_layout(True)
        figure3.set_tight_layout(True)

        self.xaxis_combo.currentIndexChanged.connect(self.redraw)
        self.yaxis_combo.currentIndexChanged.connect(self.redraw)
        self.zaxis_combo.currentIndexChanged.connect(self.redraw)
        self.sampling_spin.valueChanged.connect(self.redraw)
        self.size_spin.valueChanged.connect(self.redraw)
        self.alpha_spin.valueChanged.connect(self.redraw)
        self.colors_check.stateChanged.connect(self.redraw)
        self.grid_check.stateChanged.connect(self.redraw)
        self.norm_check.stateChanged.connect(self.redraw)
        self.tab_widget.currentChanged.connect(self.redraw)

        params_layout = QGridLayout()
        params_layout.addWidget(QLabel(self.tr("X axis:")), 0, 0)
        params_layout.addWidget(self.xaxis_combo, 0, 1)
        params_layout.addWidget(QLabel(self.tr("Y axis:")), 1, 0)
        params_layout.addWidget(self.yaxis_combo, 1, 1)
        params_layout.addWidget(QLabel(self.tr("Z axis:")), 2, 0)
        params_layout.addWidget(self.zaxis_combo, 2, 1)
        params_layout.addWidget(QLabel(self.tr("Subsampling:")), 0, 2)
        params_layout.addWidget(self.sampling_spin, 0, 3)
        params_layout.addWidget(QLabel(self.tr("Point size:")), 1, 2)
        params_layout.addWidget(self.size_spin, 1, 3)
        params_layout.addWidget(QLabel(self.tr("Point alpha:")), 2, 2)
        params_layout.addWidget(self.alpha_spin, 2, 3)
        params_layout.addWidget(self.colors_check, 0, 4)
        params_layout.addWidget(self.grid_check, 1, 4)
        params_layout.addWidget(self.total_label, 2, 4)
        bottom_layout = QHBoxLayout()
        bottom_layout.addLayout(params_layout)
        bottom_layout.addStretch()

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.tab_widget)
        main_layout.addLayout(bottom_layout)
        self.setLayout(main_layout)
コード例 #46
0
 def testSimpleSignal(self):
     box = QCheckBox('check me')
     box.stateChanged[int].connect(self.cb_changedVoid)
     self._changed = False
     box.setChecked(True)
     self.assertTrue(self._changed)
コード例 #47
0
ファイル: ToolBox.py プロジェクト: bakhyeonjae/Sherlock
class ToolBox(QVBoxLayout):

    sig = QtCore.Signal(object)
    listThread = None
    groupBoxThreadInfo = None
    threadvbox = None
    mode = None

    def __init__(self, mode, parentQWidget = None):
        QVBoxLayout.__init__(self)

        self.sig.connect(self.addThreadList)
        self.mode = mode

        self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)

        self.groupBoxSearch = QGroupBox()
        self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };")
        vboxSearch = QVBoxLayout()
        self.searchTitle = QLabel("Search Messages")
        vboxSearch.addWidget(self.searchTitle)
        self.searchHLayout = QHBoxLayout()
        self.editTextSearch = QTextEdit('')
        self.editTextSearch.setFixedSize(200,30)
        self.buttonSearch = QPushButton('Search')
        self.buttonSearch.setFixedSize(100,30)
        self.buttonSearch.clicked.connect(self.searchMsg)
        vboxSearch.addWidget(self.editTextSearch)
        self.searchHLayout.addWidget(self.buttonSearch)
        self.searchCursor = QLabel()
        self.searchHLayout.addWidget(self.searchCursor)
        vboxSearch.addLayout(self.searchHLayout)
        self.browseHLayout = QHBoxLayout()
        self.buttonLookUp = QPushButton('\u21e7')  #Arrow up
        self.buttonLookUp.setFixedWidth(100)
        self.buttonLookUp.clicked.connect(self.moveToPrev)
        self.buttonLookDown = QPushButton('\u21e9') #Arrow down
        self.buttonLookDown.setFixedWidth(100)
        self.buttonLookDown.clicked.connect(self.moveToNext)
        self.browseHLayout.addWidget(self.buttonLookUp)
        self.browseHLayout.addWidget(self.buttonLookDown)
        vboxSearch.addLayout(self.browseHLayout)
        self.groupBoxSearch.setLayout(vboxSearch)
        self.addWidget(self.groupBoxSearch)
        self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.buttonHiddenLifelines = QPushButton('Show hidden life-lines')
        self.buttonHiddenLifelines.setFixedWidth(200)
        self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines)
        self.addWidget(self.buttonHiddenLifelines)

        self.buttonHiddenMessages = QPushButton('Show hidden Messages')
        self.buttonHiddenMessages.setFixedWidth(200)
        self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages)
        self.addWidget(self.buttonHiddenMessages)

        if const.mode_interactive == mode:
            self.buttonCapture = QPushButton('Capture')
            self.buttonCapture.setFixedWidth(200)
            self.buttonCapture.clicked.connect(self.notifyCapture)
            self.addWidget(self.buttonCapture)
        self.msgRcv = []
        self.msgInfo = QLabel("Message Info.")
        self.groupBoxMessageInfo = QGroupBox()
        self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")
        vbox = QVBoxLayout()
        vbox.addWidget(self.msgInfo)
        self.tableTime = QTableWidget(3,2)
        self.tableTime.setHorizontalHeaderLabels(['-','time'])
        self.tableTime.setColumnWidth(0,80)
        self.tableTime.setColumnWidth(1,150)
        vwidth = self.tableTime.verticalHeader().length()
        hwidth = self.tableTime.horizontalHeader().height()
        fwidth = self.tableTime.frameWidth() * 2
        self.tableTime.setFixedHeight(vwidth + hwidth + fwidth)
        self.tableTime.horizontalHeader().setStretchLastSection(True)
        self.tableTime.setItem(0,0,QTableWidgetItem('begin'))
        self.tableTime.setItem(0,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(1,0,QTableWidgetItem('end'))
        self.tableTime.setItem(1,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(2,0,QTableWidgetItem('duration'))
        self.tableTime.setItem(2,1,QTableWidgetItem(' - '))
        vbox.addWidget(self.tableTime)

        self.titleArg = QLabel('Argument List')
        vbox.addWidget(self.titleArg)

        max_arg_num = 10
        self.tableArgs = QTableWidget(max_arg_num,2)
        self.tableArgs.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_arg_num):
            self.tableArgs.setItem(idx,0,QTableWidgetItem())
            self.tableArgs.setItem(idx,1,QTableWidgetItem())
        self.tableArgs.horizontalHeader().setStretchLastSection(True)
        vbox.addWidget(self.tableArgs)

        self.titleArg = QLabel('Return Value List')
        vbox.addWidget(self.titleArg)

        max_ret_num = 4
        self.tableRet = QTableWidget(max_ret_num,2)
        self.tableRet.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_ret_num):
            self.tableRet.setItem(idx,0,QTableWidgetItem())
            self.tableRet.setItem(idx,1,QTableWidgetItem())
        self.tableRet.horizontalHeader().setStretchLastSection(True)
        vwidth = self.tableRet.verticalHeader().length()
        hwidth = self.tableRet.horizontalHeader().height()
        fwidth = self.tableRet.frameWidth() * 2
        self.tableRet.setFixedHeight(vwidth + hwidth + fwidth)
        vbox.addWidget(self.tableRet)

        self.buttonSrcView = QPushButton('view code')
        self.buttonSrcView.setFixedWidth(200)
        self.buttonSrcView.clicked.connect(self.openSourceViewer)
        self.buttonHide = QPushButton('Hide')
        self.buttonHide.setFixedWidth(200)
        self.buttonHide.clicked.connect(self.notifyHide)
        self.buttonHideAllMsg = QPushButton('Hide All')
        self.buttonHideAllMsg.setFixedWidth(200)
        self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected)
        self.groupBoxMessageInfo.setLayout(vbox)
        self.checkHideCircular = QCheckBox('Hide Circular Messages')
        self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked)
        self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage)
        self.addWidget(self.checkHideCircular)
        self.addWidget(self.groupBoxMessageInfo)
        self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)

    def reset(self):
        for idx in reversed(range(0,self.listThread.count())):
            self.listThread.takeItem(idx)

    def setMsgInfoMessage(self,msg):
        self.strMessage = msg

    def changeHideCircularMessage(self,state):
        if state == QtCore.Qt.Unchecked:
            self.diagramView.hideCircularChanged(False)
        elif state == QtCore.Qt.Checked:
            self.diagramView.hideCircularChanged(True)
    
    def setMsgInfoModule(self,module):
        self.strModule = module

    def updateSearchStatus(self,curr,number):
        self.searchCursor.setText("%d/%d" % (curr,number))

    def connectSourceViewer(self,viewer):
        self.srcViewer = viewer

    def openSourceViewer(self):
        self.srcViewer.openViewer(self.strModule,self.strMessage)

    def setMessageInfoTime(self,begin,end,duration):
        self.tableTime.item(0,1).setText(begin)
        self.tableTime.item(1,1).setText(end)
        self.tableTime.item(2,1).setText(duration + ' msec')

    def setMessageInfoArg(self,listParam,listArg):
        # Clear the contents in the table
        max_arg_num = 10
        for idx in range(0,max_arg_num):
            self.tableArgs.item(idx,0).setText('')
            self.tableArgs.item(idx,1).setText('')

        if listArg:
            for idx, text in enumerate(listArg):
                self.tableArgs.item(idx,1).setText(text)
            for idx, text in enumerate(listParam):
                self.tableArgs.item(idx,0).setText(text)
        else:
            for idx in range(0,self.tableArgs.rowCount()):
                self.tableArgs.item(idx,1).setText('')
                self.tableArgs.item(idx,0).setText('')

    def setMessageInfoRet(self,listRet):
        if listRet:
            for idx, text in enumerate(listRet):
                self.tableRet.item(idx,1).setText(text)
        else:
            for idx in range(0,self.tableRet.rowCount()):
                self.tableRet.item(idx,1).setText('')
                self.tableRet.item(idx,0).setText('')

    def notifyInteractiveStateChanged(self,state):
        if const.mode_interactive != self.mode:
            return

        if const.STATE_INTERACTIVE_CAPTURING == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Stop Capture')
        if const.STATE_INTERACTIVE_PROCESSING == state:
            self.buttonCapture.setEnabled(False)
        if const.STATE_INTERACTIVE_IDLE == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')
        if const.STATE_INTERACTIVE_RESET == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')
        elif const.STATE_INTERACTIVE_ACTIVE == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')

    def setMessageInfo(self,info):
        self.msgInfo.setText(info)

    def setAvailable(self,threads):
        self.sig.emit(threads)

    def toggleThreadDisplay(self,item):
        print(self.listThread.currentRow())
        #if item.isSelected():
        #    print(item.text() + "  is selected")
        #else:
        #    print(item.text() + "  is not selected")
        self.diagramView.showThread(self.listThread.currentRow(),item.isSelected())

    def hideAllMsgNamedAsSelected(self):
        self.diagramView.hideAllMessageSelected()

    def addThreadList(self,threads):

        if not self.groupBoxThreadInfo:
            self.groupBoxThreadInfo = QGroupBox()
            self.threadInfo = QLabel("Thread Info.")
            self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")

        if not self.threadvbox:
            self.threadvbox = QVBoxLayout()

        if not self.listThread:
            self.listThread = QListWidget()
            
        self.listThread.setFixedWidth(200)
        self.listThread.setSelectionMode(QAbstractItemView.MultiSelection)
        QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay)
        self.threadvbox.addWidget(self.threadInfo)
        self.threadvbox.addWidget(self.listThread)
        self.groupBoxThreadInfo.setLayout(self.threadvbox)
        self.addWidget(self.groupBoxThreadInfo)
        self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy)

        for id in threads:
            item = QListWidgetItem(id)
            self.listThread.addItem(item)

    def connectController(self,controller):
        self.controller = controller
        self.connect(controller,QtCore.SIGNAL('setAvailable()'),self.setAvailable)
       
    def connectDiagramView(self,view):
        self.diagramView = view
 
    def disconnectMsgRcv(self,receiver):
        print("Implement this method !!! disconnectMsgRcv")

    def connectMsgRcv(self,receiver):
        self.msgRcv.append(receiver)

    def notifyHide(self):
        for rcv in self.msgRcv:
            rcv.activateHide(True)

    def showHiddenLifelines(self):
        response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems(self.diagramView.getHiddenLifeLines())
        if response:
            self.diagramView.showLifelines(selected_items)

    def showHiddenMessages(self):
        response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems(self.diagramView.getHiddenMessages(),self.diagramView.getHiddenLifeLines())
        if response:
            if selected_items[3] in self.diagramView.getHiddenLifeLines():
                confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine(selected_items[3])
                if confirmation:
                    self.diagramView.showLifelines([selected_items[3]])
                    self.diagramView.showMessages(selected_items)
            else:
                self.diagramView.showMessages(selected_items)

    def notifyCapture(self):
        for rcv in self.msgRcv:
            rcv.activateCapture(True)
    
    def moveToPrev(self):
        for rcv in self.msgRcv:
            rcv.moveToPrev()
        
    def moveToNext(self):
        for rcv in self.msgRcv:
            rcv.moveToNext()

    def searchMsg(self):
        str = self.editTextSearch.toPlainText()
        for rcv in self.msgRcv:
            rcv.searchMessage(str)
コード例 #48
0
class AutoScrollEditor(CustomDialog):
    def __init__(self, parent, level_ref: LevelRef):
        super(AutoScrollEditor, self).__init__(parent,
                                               title="Autoscroll Editor")
        self.level_ref = level_ref

        self.original_autoscroll_item = _get_autoscroll(self.level_ref.enemies)

        QVBoxLayout(self)

        self.enabled_checkbox = QCheckBox("Enable Autoscroll in level", self)
        self.enabled_checkbox.toggled.connect(self._insert_autoscroll_object)

        self.y_position_spinner = Spinner(self, maximum=0x60 - 1)
        self.y_position_spinner.valueChanged.connect(self._update_y_position)

        self.auto_scroll_type_label = QLabel(self)

        self.layout().addWidget(self.enabled_checkbox)
        self.layout().addWidget(self.y_position_spinner)
        self.layout().addWidget(self.auto_scroll_type_label)

        self.update()

    def update(self):
        autoscroll_item = _get_autoscroll(self.level_ref.enemies)

        self.enabled_checkbox.setChecked(autoscroll_item is not None)
        self.y_position_spinner.setEnabled(autoscroll_item is not None)

        if autoscroll_item is None:
            self.auto_scroll_type_label.setText(AUTOSCROLL_LABELS[-1])
        else:
            self.y_position_spinner.setValue(autoscroll_item.y_position)
            self.auto_scroll_type_label.setText(
                AUTOSCROLL_LABELS[autoscroll_item.y_position >> 4])

    def _update_y_position(self, _):
        autoscroll_item = _get_autoscroll(self.level_ref.enemies)

        autoscroll_item.y_position = self.y_position_spinner.value()

        self.level_ref.data_changed.emit()

        self.update()

    def _insert_autoscroll_object(self, should_insert: bool):
        autoscroll_item = _get_autoscroll(self.level_ref.enemies)

        if autoscroll_item is not None:
            self.level_ref.enemies.remove(autoscroll_item)

        if should_insert:
            self.level_ref.enemies.insert(0, self._create_autoscroll_object())

        self.level_ref.data_changed.emit()

        self.update()

    def _create_autoscroll_object(self):
        return self.level_ref.level.enemy_item_factory.from_properties(
            OBJ_AUTOSCROLL, 0, self.y_position_spinner.value())

    def closeEvent(self, event):
        current_autoscroll_item = _get_autoscroll(self.level_ref.enemies)

        if not (self.original_autoscroll_item is None
                and current_autoscroll_item is None):
            added_or_removed_autoscroll = self.original_autoscroll_item is None or current_autoscroll_item is None

            if (added_or_removed_autoscroll
                    or self.original_autoscroll_item.y_position !=
                    current_autoscroll_item.y_position):
                self.level_ref.save_level_state()

        super(AutoScrollEditor, self).closeEvent(event)