コード例 #1
1
ファイル: hellogl2.py プロジェクト: amirkogit/QtTestGround
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.glWidget = GLWidget()

        self.xSlider = self.createSlider(SIGNAL("xRotationChanged(int)"),
                                         self.glWidget.setXRotation)
        self.ySlider = self.createSlider(SIGNAL("yRotationChanged(int)"),
                                         self.glWidget.setYRotation)
        self.zSlider = self.createSlider(SIGNAL("zRotationChanged(int)"),
                                         self.glWidget.setZRotation)

        mainLayout = QHBoxLayout()
        mainLayout.addWidget(self.glWidget)
        mainLayout.addWidget(self.xSlider)
        mainLayout.addWidget(self.ySlider)
        mainLayout.addWidget(self.zSlider)
        self.setLayout(mainLayout)

        self.xSlider.setValue(15 * 16)
        self.ySlider.setValue(345 * 16)
        self.zSlider.setValue(0 * 16)

        self.setWindowTitle(self.tr("Hello GL"))
コード例 #2
1
class Widget(QWidget):

    cinema_url_label_text = "粘贴独播库的连续剧/综艺/动漫 URL: "
    movie_url_label_text = "粘贴独播库的电影 URL: "

    cinema_dest_label_text = "输入连续剧/综艺/动漫名 (用来命名下载的目录): "
    movie_dest_label_text = "输入电影名 (用来命名下载的文件): "

    def __init__(self):
        QWidget.__init__(self)

        self.q = None
        self.pool = None

        self.top = QHBoxLayout()
        self.top.setMargin(10)

        self.radioButtonMov = QRadioButton("电影")
        self.radioButtonCinema = QRadioButton("连续剧/综艺/动漫")

        self.top.addWidget(self.radioButtonMov)
        self.top.addWidget(self.radioButtonCinema)

        self.middle = QVBoxLayout()
        self.middle.setMargin(10)

        self.url_label = QLabel()
        self.url = QLineEdit()
        self.url_label.setBuddy(self.url)
        self.middle.addWidget(self.url_label)
        self.middle.addWidget(self.url)

        self.browse_folder_label = QLabel("下载到:")
        self.browseFolder = QPushButton("选择目录")
        self.browse_folder_label.setBuddy(self.browseFolder)
        self.middle.addWidget(self.browse_folder_label)
        self.middle.addWidget(self.browseFolder)
        self.browse_folder_value = ""

        self.dest_file_label = QLabel()
        # "输入电影/电视剧名 (用来命名下载的文件/目录): " title set by choose_movie_widgets() later
        self.folder_or_filename = QLineEdit()
        self.dest_file_label.setBuddy(self.folder_or_filename)
        self.middle.addWidget(self.dest_file_label)
        self.middle.addWidget(self.folder_or_filename)

        self.bk_cinemae_spin_from = 1
        self.bk_cinemae_spin_to = 1
        self.fromEpSpinBox = QSpinBox()
        self.fromEpSpinBox.setMinimum(1)
        self.fromEpSpinBox.setMaximum(2147483647)
        self.fromEpLabel = QLabel("&从第几集开始下载:")
        self.fromEpLabel.setBuddy(self.fromEpSpinBox)

        self.toEpSpinBox = QSpinBox()
        self.toEpSpinBox.setMinimum(1)
        self.toEpSpinBox.setMaximum(2147483647)
        self.toEpLabel = QLabel("&到第几集停止下载:")
        self.toEpLabel.setBuddy(self.toEpSpinBox)

        self.cinema_ly = QHBoxLayout()
        #self.cinema_ly.setMargin(10)
        self.cinema_ly.addWidget(self.fromEpLabel)
        self.cinema_ly.addWidget(self.fromEpSpinBox)
        self.cinema_ly.addWidget(self.toEpLabel)
        self.cinema_ly.addWidget(self.toEpSpinBox)
        self.middle.addLayout(self.cinema_ly)

        self.proxy_label = QLabel("(如有)代理:")
        self.proxy = QLineEdit()
        self.proxy_label.setBuddy(self.proxy)
        self.middle.addWidget(self.proxy_label)
        self.middle.addWidget(self.proxy)

        self.add = QPushButton("开始下载")
        self.add.setEnabled(False)
        self.middle.addWidget(self.add)

        self.stop_me = QPushButton("停止下载")
        self.stop_me.setEnabled(False)
        self.middle.addWidget(self.stop_me)

        self.log_area = QPlainTextEdit()
        self.log_area.setReadOnly(True)
        self.log_area.setMaximumBlockCount(1000)
        self.middle.addWidget(self.log_area)

        #self.table_view.setSizePolicy(size)
        #self.layout.addWidget(self.table)
        self.layout = QVBoxLayout()
        self.layout.addLayout(self.top)
        self.layout.addLayout(self.middle)
        self.setLayout(self.layout)

        self.radioButtonMov.toggled.connect(self.choose_movie_widgets)
        self.radioButtonCinema.toggled.connect(self.choose_cinema_widgets)
        self.url.textChanged[str].connect(self.check_disable_download)
        self.browseFolder.clicked.connect(self.add_folder)
        self.folder_or_filename.textChanged[str].connect(
            self.check_disable_download)
        self.add.clicked.connect(self.start_download)
        self.stop_me.clicked.connect(self.stop_download)

        self.radioButtonMov.setChecked(
            True)  #set default only after .connect above

        # TESTING PURPOSE
        '''
        self.radioButtonMov.setChecked(False)
        self.url.setText('https://www.duboku.net/voddetail-969.html')
        self.browse_folder_value = 'C:/Users/Administrator/Documents/duboku'
        self.folder_or_filename.setText('初恋')
        '''

        #set current process (not queue that one) log handler:
        logger = logging.getLogger(__name__)
        handler2 = LoggerWriter()
        logger.addHandler(handler2)
        logger.setLevel(logging.INFO)  #DEBUG
        handler2.emitter.sigLog.connect(self.log_area.appendPlainText)
        sys.stdout = handler2  #LoggerWriter()
        #sys.stderr = handler2 #Seems no difference
        #handler2.emitter.sigLog.emit('hihi')

    @Slot()
    def choose_movie_widgets(self):

        if self.radioButtonMov.isChecked():

            self.url_label.setText(self.movie_url_label_text)
            self.dest_file_label.setText(self.movie_dest_label_text)

            self.fromEpLabel.setDisabled(True)
            self.toEpLabel.setDisabled(True)

            self.fromEpSpinBox.setDisabled(True)
            self.toEpSpinBox.setDisabled(True)

            self.bk_cinemae_spin_from = self.fromEpSpinBox.value()
            self.bk_cinemae_spin_to = self.toEpSpinBox.value()
            self.fromEpSpinBox.setValue(1)
            self.toEpSpinBox.setValue(1)

    @Slot()
    def choose_cinema_widgets(self):

        if self.radioButtonCinema.isChecked():

            self.url_label.setText(self.cinema_url_label_text)
            self.dest_file_label.setText(self.cinema_dest_label_text)

            self.fromEpLabel.setEnabled(True)
            self.toEpLabel.setEnabled(True)

            self.fromEpSpinBox.setEnabled(True)
            self.toEpSpinBox.setEnabled(True)

            self.fromEpSpinBox.setValue(self.bk_cinemae_spin_from)
            self.toEpSpinBox.setValue(self.bk_cinemae_spin_to)

    @Slot()
    def add_folder(self, s):

        #fname = QFileDialog.getOpenFileName(self, 'Open file', "c:\'", "Image files (*.jpg *.gif)")
        #fname = QFileDialog.getOpenFileName(self, 'Open file', '', QFileDialog.ShowDirsOnly)
        fname = QFileDialog.getExistingDirectory(self, '选择下载至什么目录', '',
                                                 QFileDialog.ShowDirsOnly)
        #print('repr: ' + repr(fname))
        if fname and fname.strip():
            fname = fname.strip()
            self.browse_folder_value = fname
            #if getOpenFileName, will return ('/home/xiaobai/Pictures/disco.jpg', 'Image files (*.jpg *.gif)')
            #, while if getExistingDirectory, will return single path string only
            self.browseFolder.setText(fname)
            self.check_disable_download(fname)
        #else:
        #    print('User cancel')

    @Slot()
    def check_disable_download(self, s):

        if self.url.text().strip(
        ) and self.browse_folder_value and self.folder_or_filename.text():
            self.add.setEnabled(True)
        else:
            self.add.setEnabled(False)

    def task_done(self, retVal):
        self.add.setEnabled(True)
        self.stop_me.setEnabled(False)

    @Slot()
    def stop_download(self):
        if self.q:
            self.q.close()
        if self.pool:
            self.pool.terminate()
        self.add.setEnabled(True)
        self.stop_me.setEnabled(False)
        print('下载停止。')

    @Slot()
    def start_download(self):

        if self.fromEpSpinBox.value() > self.toEpSpinBox.value():
            self.log_area.setPlainText('[!] 从第几集必须小于或等于到第几集。')
            return

        #No need worry click twice too fast, it seems already handle by PySide2
        self.add.setEnabled(False)
        self.stop_me.setEnabled(True)
        self.log_area.clear()

        dest_full_path = os.path.join(self.browse_folder_value,
                                      self.folder_or_filename.text())
        '''
        print('dest_full_path: ' + repr(dest_full_path))
        print('self.url.text(): ' + repr(self.url.text()))
        print('self.fromEpSpinBox.value(): ' + repr(self.fromEpSpinBox.value()))
        print('self.toEpSpinBox.value(): ' + repr(self.toEpSpinBox.value()))
        '''

        import duboku_console

        #Windows can't set like that bcoz not update for args.url, must put explicitly
        #duboku_console.redirect_stdout_to_custom_stdout(arg_url, ...etc, LoggerWriter())

        #failed other process
        handler = LogHandlerOtherProcess()
        handler.emitter.sigLog.connect(self.log_area.appendPlainText)
        ''' #ref current process:
        logger = logging.getLogger(__name__)
        handler2 = LoggerWriter()
        logger.addHandler(handler2)
        logger.setLevel(logging.DEBUG)
        handler2.emitter.sigLog.connect(self.log_area.appendPlainText)
        sys.stdout = handler2 #LoggerWriter()
        #handler2.emitter.sigLog.emit('hihi')
        '''

        #handler = LoggerWriter()
        #handler.emitter.sigLog.connect(self.log_area.appendPlainText)

        self.q = multiprocessing.Queue()
        self.ql = QueueListener(self.q, handler)
        self.ql.start()

        self.pool = multiprocessing.Pool(1, worker_init, [self.q])

        if self.radioButtonMov.isChecked():
            self.pool.apply_async(duboku_console.main,
                                  args=(None, dest_full_path,
                                        self.fromEpSpinBox.value(),
                                        self.toEpSpinBox.value(),
                                        self.url.text().strip(),
                                        LoggerWriterOtherProcess(), False,
                                        self.proxy.text()),
                                  callback=self.task_done)
        else:
            self.pool.apply_async(duboku_console.main,
                                  args=(dest_full_path, None,
                                        self.fromEpSpinBox.value(),
                                        self.toEpSpinBox.value(),
                                        self.url.text().strip(),
                                        LoggerWriterOtherProcess(), False,
                                        self.proxy.text()),
                                  callback=self.task_done)
コード例 #3
1
    def __init__(self, name, type, data=""):
        QGroupBox.__init__(self)

        if name.find(": ") != -1: name = name.split(": ")[0]
        self.name, self.type = name, type
        self.data = data

        self.defaultElement = QGroupBox()
        mainElementLayout = QVBoxLayout()
        elementLayout = QHBoxLayout()
        if self.data == "": self.lName = QLabel(str(name))
        else: self.lName = QLabel(str(name) + ": " + str(self.data))
        self.lName.setMinimumSize(10, 10)
        duplicate = QPushButton("❐")
        duplicate.clicked.connect(lambda: self.duplicateElement())
        edit = QPushButton("✎")
        edit.clicked.connect(lambda: self.editText())
        remove = QPushButton("×")
        remove.clicked.connect(lambda: self.delElement())
        elementLayout.addWidget(self.lName)
        elementLayout.addWidget(duplicate)
        elementLayout.addWidget(edit)
        elementLayout.addWidget(remove)
        elementLayout.setStretch(0, 2)
        mainElementLayout.addLayout(elementLayout)
        mainElementLayout.addSpacing(10)
        self.defaultElement.setLayout(mainElementLayout)
        self.defaultElement.setFixedHeight(80)
コード例 #4
0
    def testMoveLayout(self):
        l = QHBoxLayout()
        self.assertEqual(getrefcount(self.widget1), 2)
        l.addWidget(self.widget1)
        self.assertEqual(getrefcount(self.widget1), 3)

        w = QWidget()
        w.setLayout(l)
        self.assertEqual(getrefcount(self.widget1), 3)
コード例 #5
0
ファイル: camera.py プロジェクト: amirkogit/QtTestGround
    def __init__(self, previewImage, fileName):
        super(ImageView, self).__init__()

        self.fileName = fileName

        mainLayout = QVBoxLayout(self)
        self.imageLabel = QLabel()
        self.imageLabel.setPixmap(QPixmap.fromImage(previewImage))
        mainLayout.addWidget(self.imageLabel)

        topLayout = QHBoxLayout()
        self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName))
        self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)

        topLayout.addWidget(self.fileNameLabel)
        topLayout.addStretch()
        copyButton = QPushButton("Copy")
        copyButton.setToolTip("Copy file name to clipboard")
        topLayout.addWidget(copyButton)
        copyButton.clicked.connect(self.copy)
        launchButton = QPushButton("Launch")
        launchButton.setToolTip("Launch image viewer")
        topLayout.addWidget(launchButton)
        launchButton.clicked.connect(self.launch)
        mainLayout.addLayout(topLayout)
コード例 #6
0
ファイル: contextinfo.py プロジェクト: amirkogit/QtTestGround
 def __init__(self):
     super(MainWindow, self).__init__()
     hBoxLayout = QHBoxLayout(self)
     self.plainTextEdit = QPlainTextEdit()
     self.plainTextEdit.setMinimumWidth(400)
     self.plainTextEdit.setReadOnly(True)
     hBoxLayout.addWidget(self.plainTextEdit)
     self.renderWindow = RenderWindow(QSurfaceFormat())
     container = QWidget.createWindowContainer(self.renderWindow)
     container.setMinimumSize(QSize(400, 400))
     hBoxLayout.addWidget(container)
コード例 #7
0
    def test_setLayout(self):
        layout = QVBoxLayout()
        btn1 = QPushButton("button_v1")
        layout.addWidget(btn1)

        btn2 = QPushButton("button_v2")
        layout.addWidget(btn2)

        layout2 = QHBoxLayout()

        btn1 = QPushButton("button_h1")
        layout2.addWidget(btn1)

        btn2 = QPushButton("button_h2")
        layout2.addWidget(btn2)

        layout.addLayout(layout2)

        widget = QWidget()
        widget.setLayout(layout)
コード例 #8
0
class MultipleAdd(UsesQApplication):
    '''Test case to check if refcount is incremented only once when multiple
    calls to addWidget are made with the same widget'''

    qapplication = True

    def setUp(self):
        #Acquire resources
        super(MultipleAdd, self).setUp()
        self.widget = QPushButton('click me')
        self.win = QWidget()
        self.layout = QHBoxLayout(self.win)

    def tearDown(self):
        #Release resources
        del self.widget
        del self.layout
        del self.win
        super(MultipleAdd, self).tearDown()

    def testRefCount(self):
        #Multiple QLayout.addWidget calls on the same widget
        self.assertEqual(getrefcount(self.widget), 2)
        self.layout.addWidget(self.widget)
        self.assertEqual(getrefcount(self.widget), 3)
        self.layout.addWidget(self.widget)
        self.assertEqual(getrefcount(self.widget), 3)
        self.layout.addWidget(self.widget)
        self.assertEqual(getrefcount(self.widget), 3)
コード例 #9
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)
コード例 #10
0
ファイル: help.py プロジェクト: strohne/Facepager
    def __init__(self, parent=None):
        super(HelpWindow,self).__init__(parent)

        self.setWindowTitle("Facepager 3.0 - Help")
        self.setMinimumWidth(600);
        self.setMinimumHeight(600);
        central = QWidget()
        self.setCentralWidget(central)
        vLayout = QVBoxLayout(central)

        self.page = MyQWebEnginePage()
        self.browser = QWebEngineView(central)
        self.browser.setPage(self.page)

        vLayout.addWidget(self.browser)
        hLayout = QHBoxLayout()
        vLayout.addLayout(hLayout)
        hLayout.addStretch(5)
        dismiss = QPushButton(central)
        dismiss.setText("Close")
        dismiss.clicked.connect(self.hide)
        hLayout.addWidget(dismiss)
コード例 #11
0
ファイル: audiooutput.py プロジェクト: amirkogit/QtTestGround
    def initializeWindow(self):
        layout = QVBoxLayout()

        self.m_deviceBox = QComboBox()
        self.m_deviceBox.activated[int].connect(self.deviceChanged)
        for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        layout.addWidget(self.m_deviceBox)

        self.m_modeButton = QPushButton()
        self.m_modeButton.clicked.connect(self.toggleMode)
        self.m_modeButton.setText(self.PUSH_MODE_LABEL)

        layout.addWidget(self.m_modeButton)

        self.m_suspendResumeButton = QPushButton(
                clicked=self.toggleSuspendResume)
        self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)

        layout.addWidget(self.m_suspendResumeButton)

        volumeBox = QHBoxLayout()
        volumeLabel = QLabel("Volume:")
        self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100,
                singleStep=10)
        self.m_volumeSlider.valueChanged.connect(self.volumeChanged)

        volumeBox.addWidget(volumeLabel)
        volumeBox.addWidget(self.m_volumeSlider)

        layout.addLayout(volumeBox)

        window = QWidget()
        window.setLayout(layout)

        self.setCentralWidget(window)
コード例 #12
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
コード例 #13
0
    def __init__(self):
        QWidget.__init__(self)

        self.setWindowTitle("Backend Discord-GUI")
        self.changeStyle('fusion')

        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(53, 53, 53))
        palette.setColor(QPalette.WindowText, Qt.white)
        palette.setColor(QPalette.Text, Qt.white)
        palette.setColor(QPalette.Button, QColor(60, 60, 60))
        palette.setColor(QPalette.ButtonText, Qt.white)
        palette.setColor(QPalette.Base, QColor(40, 40, 40))
        palette.setColor(QPalette.ToolTipBase, QColor(60, 60, 60))
        palette.setColor(QPalette.ToolTipText, Qt.white)
        palette.setColor(QPalette.PlaceholderText, Qt.white)
        palette.setColor(QPalette.BrightText, Qt.white)
        palette.setColor(QPalette.Highlight, QColor(106, 13, 173))
        palette.setColor(QPalette.HighlightedText, Qt.white)

        topButtonLayout = QGroupBox("Configurations")
        topStatsLayout = QGroupBox("Statistics")

        layoutLeft = QHBoxLayout()

        botConfigButton = QPushButton("Bot Config")
        botConfigButton.clicked.connect(lambda: CommentPopup())
        serverSettingsButton = QPushButton("Server Settings")
        settingsButton = QPushButton("Settings")

        layoutLeft.addWidget(botConfigButton)
        layoutLeft.addWidget(serverSettingsButton)
        layoutLeft.addWidget(settingsButton)

        layoutRight = QVBoxLayout()

        botReadyLabel = QLabel("Bot_Ready: False")
        botStatusLabel = QLabel("Bot_Status: Off")
        # botDatabaseLabel = QLabel("Bot_Database: None")
        # botStandbyLabel = QLabel("Bot_Standby: False")

        layoutRight.addWidget(botReadyLabel)
        layoutRight.addWidget(botStatusLabel)
        # layoutRight.addWidget(botDatabaseLabel)
        # layoutRight.addWidget(botStandbyLabel)

        topButtonLayout.setLayout(layoutLeft)
        topStatsLayout.setLayout(layoutRight)

        self.createLeftSide()
        self.createRightSide()
        self.createProgressBar()

        topLayout = QGridLayout()
        topLayout.addWidget(topButtonLayout, 0, 0)
        topLayout.addWidget(topStatsLayout, 0, 1)
        topLayout.setColumnStretch(0, 1)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.leftSideGB, 1, 0)
        mainLayout.addWidget(self.topRightGroupBox, 1, 1)
        mainLayout.addWidget(self.progressBar, 3, 0, 1, 2)
        mainLayout.setRowStretch(1, 2)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 2)
        self.setLayout(mainLayout)

        QApplication.setPalette(palette)
コード例 #14
0
 def setup_xmlviewer(self):
     wf_layout = QHBoxLayout()
     wf_layout.addWidget(self.xml_display)
     self.xmlviewer.setLayout(wf_layout)
コード例 #15
0
    def __init__(self, prevData=None):
        super().__init__()
        self.setWindowFlags(Qt.CustomizeWindowHint)
        self.setLayout(QVBoxLayout())
        mainLayout = QGroupBox("Comment Settings")
        self.resize(600, 400)

        layout = QHBoxLayout()
        button_save = QPushButton('Save')
        button_close = QPushButton('Close')
        layout.addWidget(button_save)
        layout.addWidget(button_close)

        topLayout = QVBoxLayout()
        middleLayout = QHBoxLayout()
        if prevData == None: self.entry = QLineEdit()
        else: self.entry = QLineEdit(prevData)
        label = QLabel("Text:")
        middleLayout.addWidget(label)
        middleLayout.addWidget(self.entry)
        help = QLabel(
            "<b>Comment</b>: Used for nothing more than a reminder, it does not directly affect the code<br>"
            +
            "itself. It will be shown when exporting a bot to a coded langauge."
        )
        topLayout.addLayout(middleLayout)
        topLayout.addWidget(help)
        topLayout.setAlignment(middleLayout, Qt.AlignTop)
        topLayout.setAlignment(help, Qt.AlignBottom)
        mainLayout.setLayout(topLayout)

        self.layout().addWidget(mainLayout)
        self.layout().addLayout(layout)

        button_save.clicked.connect(lambda: self.saveElement())
        button_close.clicked.connect(self.close)
        self.exec_()

        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.center())
コード例 #16
0
    def init_ui(self):

        layout = QVBoxLayout()

        x_pos_layout = QHBoxLayout()
        x_pos_layout.addWidget(QLabel("<b>X : </b>"))
        x_pos_layout.addWidget(self.x_position_label)
        x_pos_layout.addStretch()

        y_pos_layout = QHBoxLayout()
        y_pos_layout.addWidget(QLabel("<b>Y : </b>"))
        y_pos_layout.addWidget(self.y_position_label)
        y_pos_layout.addStretch()

        alt_layout = QHBoxLayout()
        alt_layout.addWidget(QLabel("<b>Alt : </b>"))
        alt_layout.addWidget(self.alt_label)
        alt_layout.addStretch()

        name_layout = QHBoxLayout()
        name_layout.addWidget(QLabel("<b>Name : </b>"))
        name_layout.addWidget(self.name_label)
        name_layout.addStretch()

        desc_layout = QHBoxLayout()
        desc_layout.addWidget(QLabel("<b>Description : </b>"))
        desc_layout.addWidget(self.desc_label)
        desc_layout.addStretch()

        # layout.addLayout(name_layout)
        layout.addLayout(x_pos_layout)
        layout.addLayout(y_pos_layout)
        layout.addLayout(alt_layout)
        layout.addLayout(desc_layout)

        self.setLayout(layout)
コード例 #17
0
class SoundBoard(QDialog):
    def __init__(self):
        super(SoundBoard, self).__init__()
        self.title = '=== SoundBoard ==='
        # positionnement de la fenêtre à l'ouverture
        self.left = 50
        self.top = 50
        # initialisation de la largeur et hauteur par défaut
        self.width = 500
        self.height = 500
        self.currFileName = ""
        self.pbPosToModify = -1
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.windowLayout = QHBoxLayout()
        self.tableWidget = QTableWidget()
        self.tableWidget.horizontalHeader().hide()
        self.tableWidget.verticalHeader().hide()
        self.initIcons()
        self.initMenu()
        self.initColorPicker()
        self.initButtons()
        self.windowLayout.setStretch(1, 0)
        self.setLayout(self.windowLayout)
        self.show()

    def initIcons(self):
        self.iEdit = QIcon()
        self.iEdit.addPixmap(QPixmap("./icons/edit.png"), QIcon.Normal,
                             QIcon.Off)

        self.iPlus = QIcon()
        self.iPlus.addPixmap(QPixmap("./icons/plus.png"), QIcon.Normal,
                             QIcon.Off)

        self.iMinus = QIcon()
        self.iMinus.addPixmap(QPixmap("./icons/minus.png"), QIcon.Normal,
                              QIcon.Off)

        self.iParam = QIcon()
        self.iParam.addPixmap(QPixmap("./icons/cog.png"), QIcon.Normal,
                              QIcon.Off)

    def initMenu(self):
        layout = QVBoxLayout()
        hlayout = QHBoxLayout()

        # bouton ajout
        self.tbPlus = QToolButton()
        self.tbPlus.setGeometry(QRect(0, 0, 32, 32))
        self.tbPlus.setIcon(self.iPlus)
        self.tbPlus.setObjectName("tbPlus")

        hlayout.addWidget(self.tbPlus)
        self.tbPlus.clicked.connect(self.add)

        # bouton suppression
        self.tbMinus = QToolButton()
        self.tbMinus.setGeometry(QRect(0, 0, 32, 32))
        self.tbMinus.setIcon(self.iMinus)
        self.tbMinus.setObjectName("tbMinus")

        hlayout.addWidget(self.tbMinus)
        self.tbMinus.clicked.connect(self.delete)

        # bouton édition
        self.tbEdit = QToolButton()
        self.tbEdit.setGeometry(QRect(0, 0, 32, 32))
        self.tbEdit.setIcon(self.iEdit)
        self.tbEdit.setObjectName("tbEdit")

        hlayout.addWidget(self.tbEdit)
        self.tbEdit.clicked.connect(self.editBtn)

        # bouton paramètres
        self.tbParam = QToolButton()
        self.tbParam.setGeometry(QRect(0, 0, 32, 32))
        self.tbParam.setIcon(self.iParam)
        self.tbParam.setObjectName("tbParam")

        hlayout.addWidget(self.tbParam)
        self.tbParam.clicked.connect(self.settings)

        layout.addLayout(hlayout)

        self.pbStop = QPushButton("Don't STOP\n\nthe\n\nSoundBoard")
        self.pbStop.setStyleSheet("font-weight: bold;")
        self.pbStop.setMinimumSize(QSize(100, 100))
        self.pbStop.setGeometry(QRect(0, 0, 100, 100))
        layout.addWidget(self.pbStop)
        self.pbStop.clicked.connect(self.stop)

        spacerMenu = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        layout.addItem(spacerMenu)

        self.windowLayout.addLayout(layout)

    def startInitButtons(self):
        self.tableWidget.clear()
        self.tableWidget.clearSpans()
        self.tableWidget.setColumnWidth(0, 100)
        self.tableWidget.setColumnWidth(2, 100)
        self.cdColorPicker.setVisible(False)

        self.tableWidget.horizontalHeader().hide()
        # import des informations boutons contenues dans le json
        with open('buttons.json', encoding='utf-8') as json_file:
            self.data_buttons = json.load(json_file)

        # stockage de la position la plus élevée pour le cadrage
        self.positions = [p['position'] for p in self.data_buttons['buttons']]
        self.max_pos = max(self.positions)

        # calcul du nombre de boutons par hauteur et largeur
        self.BtnH = self.data_buttons['buttons_grid']['height']
        self.BtnW = self.data_buttons['buttons_grid']['width']
        self.setGeometry(self.left, self.top, 140 + self.BtnW * 100,
                         175 if self.BtnH * 31 < 175 else 25 + self.BtnH * 30)
        self.tableWidget.setColumnCount(self.BtnW)
        self.tableWidget.setRowCount(self.BtnH)

    def endInitButtons(self):
        buttonsLayout = QVBoxLayout()
        buttonsLayout.setStretch(0, 1)
        buttonsLayout.addWidget(self.tableWidget)

        self.windowLayout.addLayout(buttonsLayout)

        self.setGeometry(self.left, self.top, 140 + self.BtnW * 100,
                         175 if self.BtnH * 31 < 175 else 25 + self.BtnH * 30)

    def initButtons(self):
        self.startInitButtons()

        # positionnement des boutons en fonction des positions du json
        for ligne in range(self.BtnH):
            for colonne in range(self.BtnW):
                if (ligne * self.BtnW) + (colonne + 1) in self.positions:
                    for b in self.data_buttons['buttons']:
                        if b['position'] == (ligne * self.BtnW) + (colonne +
                                                                   1):
                            pb = QPushButton(b['name'][:9])
                            pb.setProperty('pbPos', b['position'])
                            # si fond clair, font noire, si sombre, font blanche
                            if (b['r'] * 0.299 + b['g'] * 0.587 +
                                    b['b'] * 0.114) > 186:
                                pb.setStyleSheet(
                                    f"background-color: rgb({b['r']},{b['g']},{b['b']}); color: #000000;"
                                )
                            else:
                                pb.setStyleSheet(
                                    f"background-color: rgb({b['r']},{b['g']},{b['b']}); color: #ffffff;"
                                )
                            self.tableWidget.setCellWidget(ligne, colonne, pb)
                            pb.clicked.connect(self.play)
                else:
                    pb = QPushButton('Nouveau')
                    calcPos = self.BtnW * ligne + colonne + 1
                    pb.setProperty('pbPos', f"nouveau,{calcPos}")
                    pb.clicked.connect(self.add)
                    self.tableWidget.setCellWidget(ligne, colonne, pb)
                colonne += 1
            ligne += 1

        self.endInitButtons()

    def initColorPicker(self):
        self.lColorPicker = QVBoxLayout()
        self.cdColorPicker = QColorDialog()
        self.cdColorPicker.setOption(self.cdColorPicker.NoButtons, True)
        self.colorSelected = self.cdColorPicker.currentColor()

        self.lColorPicker.addWidget(self.cdColorPicker)
        self.cdColorPicker.setVisible(False)
        self.cdColorPicker.currentColorChanged.connect(self.colorChanged)

        self.windowLayout.addLayout(self.lColorPicker)

    def play(self):
        pb = self.sender()
        pbPos = pb.property('pbPos')
        for b in self.data_buttons['buttons']:
            if pbPos == b['position']:
                pbFile = b['file']
        if (p.get_state() == vlc.State.Playing):
            p.stop()
            media = instance.media_new(soundRep + pbFile)
            if (self.currFileName != pbFile):
                p.set_media(media)
                p.play()
                self.currFileName = pbFile
        else:
            media = instance.media_new(soundRep + pbFile)
            p.set_media(media)
            p.play()
            self.currFileName = pbFile

    def stop(self):
        p.stop()

    def add(self):
        self.cdColorPicker.setVisible(True)
        self.tableWidget.clear()
        self.tableWidget.clearSpans()
        self.tableWidget.setColumnWidth(2, 100)

        self.tableWidget.setColumnCount(6)
        self.tableWidget.setRowCount(len(self.data_buttons['buttons']) + 1)

        self.tableWidget.horizontalHeader().show()

        self.tableWidget.setHorizontalHeaderItem(0, QTableWidgetItem())
        self.tableWidget.horizontalHeaderItem(0).setText('Nom')
        self.tableWidget.setHorizontalHeaderItem(1, QTableWidgetItem())
        self.tableWidget.horizontalHeaderItem(1).setText('Fichier')
        self.tableWidget.setHorizontalHeaderItem(2, QTableWidgetItem())
        self.tableWidget.horizontalHeaderItem(2).setText('')
        self.tableWidget.setColumnWidth(2, 22)
        self.tableWidget.setHorizontalHeaderItem(3, QTableWidgetItem())
        self.tableWidget.horizontalHeaderItem(3).setText('Position')
        self.tableWidget.setHorizontalHeaderItem(4, QTableWidgetItem())
        self.tableWidget.horizontalHeaderItem(4).setText('Couleur')
        self.tableWidget.setHorizontalHeaderItem(5, QTableWidgetItem())
        self.tableWidget.horizontalHeaderItem(5).setText('')

        # nom
        self.leName = QLineEdit()
        self.leName.setPlaceholderText('Nom (10 max.)')
        self.tableWidget.setCellWidget(0, 0, self.leName)
        # fichier
        self.leFile = QLineEdit()
        self.leFile.setPlaceholderText('Fichier')
        self.tableWidget.setCellWidget(0, 1, self.leFile)
        # browse
        pbBrowser = QPushButton('...')
        pbBrowser.setMinimumSize(QSize(21, 21))
        pbBrowser.clicked.connect(self.browseMedia)
        self.tableWidget.setCellWidget(0, 2, pbBrowser)
        # position
        self.lePos = QLineEdit()
        self.lePos.setPlaceholderText('Position')
        self.tableWidget.setCellWidget(0, 3, self.lePos)
        # couleur
        self.leColor = QLineEdit()
        self.leColor.setPlaceholderText('255,255,255')
        self.leColor.setText(
            str(self.colorSelected.red()) + "," +
            str(self.colorSelected.green()) + "," +
            str(self.colorSelected.blue()))
        self.tableWidget.setCellWidget(0, 4, self.leColor)
        # validation
        pbValid = QPushButton('Valider')
        pbValid.clicked.connect(self.addValid)
        self.tableWidget.setCellWidget(0, 5, pbValid)

        pb = self.sender()
        pbPos = pb.property('pbPos')
        if pbPos is not None:
            if str(pbPos)[:8] == 'nouveau,':
                self.lePos.setText(pbPos[8:])

        def sortByPos(val):
            return val['position']

        self.data_buttons['buttons'].sort(key=sortByPos)
        for ligne, b in enumerate(self.data_buttons['buttons'], start=1):
            self.tableWidget.setSpan(ligne, 1, 1, 2)
            self.tableWidget.setCellWidget(ligne, 0, QLabel(b['name']))
            self.tableWidget.setCellWidget(ligne, 1, QLabel(b['file']))
            self.tableWidget.setCellWidget(ligne, 3,
                                           QLabel(str(b['position'])))
            self.tableWidget.setCellWidget(ligne, 4, QLabel('Couleur'))

        # 530 color picker width
        self.setGeometry(self.left, self.top, 690 + 530, 300)

    def addValid(self):
        gName = self.leName.text()
        self.leName.setStyleSheet("color: rgb(0,0,0);")
        gFile = self.leFile.text()
        self.leFile.setStyleSheet("color: rgb(0,0,0);")
        gPos = self.lePos.text()
        self.lePos.setStyleSheet("color: rgb(0,0,0);")
        gColor = self.leColor.text()
        self.leColor.setStyleSheet("color: rgb(0,0,0);")
        # si champs vides
        if ((gName == '' or gName == 'Obligatoire !')
                or (gFile == '' or gFile == 'Obligatoire !')
                or (gPos == '' or gColor == 'Obligatoire !')
                or (gColor == '' or gColor == 'Obligatoire !')):
            if gName == '' or gName == 'Obligatoire !':
                self.leName.setText('Obligatoire !')
                self.leName.setStyleSheet(
                    "color: rgb(255,0,0); font-weight: bold;")
            if gFile == '' or gFile == 'Obligatoire !':
                self.leFile.setText('Obligatoire !')
                self.leFile.setStyleSheet(
                    "color: rgb(255,0,0); font-weight: bold;")
            if gPos == '' or gColor == 'Obligatoire !':
                self.lePos.setText('Obligatoire !')
                self.lePos.setStyleSheet(
                    "color: rgb(255,0,0); font-weight: bold;")
            if gColor == '' or gColor == 'Obligatoire !':
                self.leColor.setText('Obligatoire !')
                self.leColor.setStyleSheet(
                    "color: rgb(255,0,0); font-weight: bold;")
        else:
            # vérif si champ position est un nombre
            try:
                flag = 0
                flag = int(gPos)
            except ValueError:
                self.lePos.setText(f"{str(gPos)} n'est pas un nombre")
                self.lePos.setStyleSheet(
                    "color: rgb(255,0,0); font-weight: bold;")
            # si position est un nombre
            if flag != 0:
                # si position hors grille
                if int(gPos) < 0 or int(gPos) > self.data_buttons[
                        'buttons_grid']['height'] * self.data_buttons[
                            'buttons_grid']['width']:
                    self.lePos.setText(f"{str(gPos)} hors grille")
                    self.lePos.setStyleSheet(
                        "color: rgb(255,0,0); font-weight: bold;")
                else:
                    dictToAppend = {
                        "name": gName,
                        "file": gFile,
                        "position": int(gPos),
                        "r": self.colorSelected.red(),
                        "g": self.colorSelected.green(),
                        "b": self.colorSelected.blue()
                    }
                    # si c'est une modification
                    if self.pbPosToModify != -1:
                        for b in self.data_buttons['buttons']:
                            if b['position'] == self.pbPosToModify:
                                self.data_buttons['buttons'].remove(b)
                        self.data_buttons['buttons'].append(dictToAppend)
                        with open('buttons.json', 'w',
                                  encoding='utf-8') as outfile:
                            json.dump(self.data_buttons, outfile, indent=4)
                        self.initButtons()
                    else:
                        # si position déjà prise
                        if int(gPos) in self.positions:
                            self.lePos.setText(f"{str(gPos)} déjà prise")
                            self.lePos.setStyleSheet(
                                "color: rgb(255,0,0); font-weight: bold;")
                        else:
                            self.data_buttons['buttons'].append(dictToAppend)
                            with open('buttons.json', 'w',
                                      encoding='utf-8') as outfile:
                                json.dump(self.data_buttons, outfile, indent=4)
                            self.initButtons()

    def delete(self):
        self.startInitButtons()

        # positionnement des boutons en fonction des positions du json
        for ligne in range(self.BtnH):
            for colonne in range(self.BtnW):
                if (ligne * self.BtnW) + (colonne + 1) in self.positions:
                    for b in self.data_buttons['buttons']:
                        if b['position'] == (ligne * self.BtnW) + (colonne +
                                                                   1):
                            pb = QPushButton(b['name'][:9])
                            pb.setProperty('pbPos', b['position'])
                            pb.setIcon(self.iMinus)
                            # si fond clair, font noire, si sombre, font blanche
                            if (b['r'] * 0.299 + b['g'] * 0.587 +
                                    b['b'] * 0.114) > 186:
                                pb.setStyleSheet(
                                    f"background-color: rgb({b['r']},{b['g']},{b['b']}); color: #000000;"
                                )
                            else:
                                pb.setStyleSheet(
                                    f"background-color: rgb({b['r']},{b['g']},{b['b']}); color: #ffffff;"
                                )
                            self.tableWidget.setCellWidget(ligne, colonne, pb)
                            pb.clicked.connect(self.deleteTw)
                else:
                    pb = QPushButton('Nouveau')
                    calcPos = self.BtnW * ligne + colonne + 1
                    pb.setProperty('pbPos', f"nouveau,{calcPos}")
                    pb.clicked.connect(self.add)
                    self.tableWidget.setCellWidget(ligne, colonne, pb)
                colonne += 1
            ligne += 1

        self.endInitButtons()

    def deleteTw(self):
        pb = self.sender()
        pbPos = pb.property('pbPos')
        for b in self.data_buttons['buttons']:
            if b['position'] == pbPos:
                self.data_buttons['buttons'].remove(b)
                with open('buttons.json', 'w', encoding='utf-8') as outfile:
                    json.dump(self.data_buttons, outfile, indent=4)
                self.delete()

    def editBtn(self):
        self.startInitButtons()

        # positionnement des boutons en fonction des positions du json
        for ligne in range(self.BtnH):
            for colonne in range(self.BtnW):
                if (ligne * self.BtnW) + (colonne + 1) in self.positions:
                    for b in self.data_buttons['buttons']:
                        if b['position'] == (ligne * self.BtnW) + (colonne +
                                                                   1):
                            pb = QPushButton(b['name'][:9])
                            pb.setProperty('pbPos', b['position'])
                            pb.setIcon(self.iEdit)
                            # si fond clair, font noire, si sombre, font blanche
                            if (b['r'] * 0.299 + b['g'] * 0.587 +
                                    b['b'] * 0.114) > 186:
                                pb.setStyleSheet(
                                    f"background-color: rgb({b['r']},{b['g']},{b['b']}); color: #000000;"
                                )
                            else:
                                pb.setStyleSheet(
                                    f"background-color: rgb({b['r']},{b['g']},{b['b']}); color: #ffffff;"
                                )
                            self.tableWidget.setCellWidget(ligne, colonne, pb)
                            pb.clicked.connect(self.editTw)
                else:
                    pb = QPushButton('Nouveau')
                    pb.setIcon(self.iEdit)
                    calcPos = self.BtnW * ligne + colonne + 1
                    pb.setProperty('pbPos', f"nouveau,{calcPos}")
                    pb.clicked.connect(self.add)
                    self.tableWidget.setCellWidget(ligne, colonne, pb)
                colonne += 1
            ligne += 1

        self.endInitButtons()

    def editTw(self):
        pb = self.sender()
        pbPos = pb.property('pbPos')
        self.pbPosToModify = pbPos
        self.add()
        for b in self.data_buttons['buttons']:
            if b['position'] == pbPos:
                self.leName.setText(b['name'])
                self.leFile.setText(b['file'])
                self.lePos.setText(str(b['position']))
                self.cdColorPicker.setCurrentColor(
                    QColor(b['r'], b['g'], b['b']))

    def settings(self):
        self.tableWidget.clear()
        self.tableWidget.clearSpans()
        self.tableWidget.setColumnWidth(2, 100)

        self.cdColorPicker.setVisible(False)

        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(4)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.Stretch)

        self.tableWidget.horizontalHeader().hide()

        # bouton validation
        pb = QPushButton('Valider')
        self.tableWidget.setCellWidget(3, 0, pb)
        pb.clicked.connect(self.saveSettings)

        # bouton annulation
        pb = QPushButton('Annuler')
        self.tableWidget.setCellWidget(3, 1, pb)
        pb.clicked.connect(self.refreshUI)

        # parameters
        self.tableWidget.setSpan(0, 0, 1, 2)
        self.lAlert = QLabel("La modification de ces valeurs entrainera la "
                             "modification de position des boutons")
        self.lAlert.setStyleSheet("font-weight: bold;")
        self.tableWidget.setCellWidget(0, 0, self.lAlert)
        self.tableWidget.setCellWidget(1, 0,
                                       QLabel('Nombre de boutons en Hauteur'))
        self.leH = QLineEdit(str(self.data_buttons['buttons_grid']['height']))
        self.tableWidget.setCellWidget(1, 1, self.leH)
        self.tableWidget.setCellWidget(2, 0,
                                       QLabel('Nombre de boutons en Largeur'))
        self.leW = QLineEdit(str(self.data_buttons['buttons_grid']['width']))
        self.tableWidget.setCellWidget(2, 1, self.leW)

        settingsLayout = QVBoxLayout()
        settingsLayout.setStretch(0, 1)
        settingsLayout.addWidget(self.tableWidget)

        self.windowLayout.addLayout(settingsLayout)

        self.setGeometry(self.left, self.top, 600, 300)

    def saveSettings(self):
        h = int(self.leH.text())
        w = int(self.leW.text())
        if h * w < self.max_pos:
            self.lAlert.setText(f"Le bouton à la position {str(self.max_pos)} "
                                f"est en dehors de la grille {h} x {w}")
            self.lAlert.setStyleSheet(
                "color: rgb(255,0,0); font-weight: bold;")
        else:
            self.data_buttons['buttons_grid']['height'] = int(self.leH.text())
            self.data_buttons['buttons_grid']['width'] = int(self.leW.text())
            with open('buttons.json', 'w', encoding='utf-8') as outfile:
                json.dump(self.data_buttons, outfile, indent=4)
            self.initButtons()

    def refreshUI(self):
        self.initButtons()

    def browseMedia(self):
        self.openFile = QFileDialog.getOpenFileName(
            self, "Sélectionner un média...", "./sons",
            "Image Files (*.avi *.mp3 *.wav)")
        filenameSplitted = self.openFile[0].split('/')
        self.leFile.setText(filenameSplitted[-1])

    def colorChanged(self):
        self.colorSelected = self.cdColorPicker.currentColor()
        self.leColor.setText(
            str(self.colorSelected.red()) + "," +
            str(self.colorSelected.green()) + "," +
            str(self.colorSelected.blue()))
コード例 #18
0
ファイル: export.py プロジェクト: taurinclean/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)

        # 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('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():
                output.write('\ufeff')

            try:
                if self.optionAll.currentIndex() == 0:
                    self.exportAllNodes(output)
                else:
                    self.exportSelectedNodes(output)
            finally:
                output.close()
コード例 #19
0
from PySide2.QtWidgets import (
   QApplication, QWidget, QLineEdit, QPushButton, QHBoxLayout
)

import sys

app = QApplication(argc, argv);
window = QWidget()
lineEdit = QLineEdit();
button = QPushButton("Clear");
layout = QHBoxLayout();
layout->addWidget(lineEdit);
layout->addWidget(button);

QObject::connect(&button,   &QPushButton::pressed,
                 &lineEdit, &QLineEdit::clear);

window.setLayout(layout);
window.setWindowTitle("Why?");
window.show();
app.exec();
コード例 #20
0
class GridTransformerInputBand(QWidget):
    ''' Widget for specification of filename and band '''

    log_message = QtCore.Signal(str)
    # tuple with band name, filename, band index
    band_selected = QtCore.Signal(object)

    def __init__(self, band_name: str, parent=None):
        QWidget.__init__(self, parent=parent)
        self.band_name = band_name
        self.filename = None
        self.file_info = None

        self.layout = QHBoxLayout()
        self.layout.setSpacing(16)
        self.layout.setMargin(8)
        self.setLayout(self.layout)

        label = QLabel(self.band_name)
        label.setMinimumWidth(125)
        self.layout.addWidget(label)

        input_file_layout = QHBoxLayout()
        input_file_layout.setSpacing(4)
        self.input_file_input = QLineEdit()
        # can only be set by file selection dialog
        self.input_file_input.setReadOnly(True)
        self.input_file_input.setMinimumWidth(300)
        self.input_file_input.setSizePolicy(QSizePolicy.Expanding,
                                            QSizePolicy.Expanding)
        input_file_layout.addWidget(self.input_file_input)

        self.open_file_button = QPushButton()
        input_file_layout.addWidget(self.open_file_button)
        self.open_file_button.setIcon(qta.icon('fa.folder-open'))
        self.open_file_button.setToolTip(
            f"Select file containing {self.band_name} data")
        self.open_file_button.clicked.connect(self._click_open)
        self.layout.addLayout(input_file_layout)

        self.band_select = QComboBox()
        self.band_select.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        self.band_select.setMinimumWidth(180)
        self.band_select.setMaximumWidth(240)
        self.band_select.setToolTip(
            f"Select band containing {self.band_name} data")
        self.band_select.currentIndexChanged.connect(self._band_selected)

        self.band_select.setDisabled(True)
        self.layout.addWidget(self.band_select)

    def _band_selected(self, index):
        tpl = (self.band_name, self.filename, self.selected_band_index)
        self.band_selected.emit(tpl)

    @property
    def selected_band_index(self) -> int:
        ''' Gets the band index that has been selected by the user. This is the
        index used by gdal, not the 0 based index of the combobox selection'''
        if self.file_info is None or len(self.file_info.bands) == 0:
            return None
        selected_band = self.file_info.bands[self.band_select.currentIndex()]
        return selected_band.index

    def _update_bands(self):
        self.band_select.clear()
        if self.file_info is None or len(self.file_info.bands) == 0:
            self.band_select.setDisabled(True)
            return

        self.band_select.setDisabled(False)

        for band in self.file_info.bands:
            self.band_select.addItem(band.display_name)

        # try to find a matching band. Obviously not needed if there is only one
        # band, but wont hurt.
        index = 0
        for i, band in enumerate(self.file_info.bands):
            if self.band_name.lower() in band.display_name.lower():
                index = i
        self.band_select.setCurrentIndex(index)

    def _set_filename(self, filename):
        self.filename = filename
        self.file_info = RasterFileInfo()
        self.file_info.open(self.filename)
        self.input_file_input.setText(self.filename)
        self._update_bands()

        self.log_message.emit(str(self.file_info) + "\n")

    def _click_open(self):
        filters = ("GeoTIFF (*.tif *.tiff);;"
                   "Bathymetry Attributed Grid BAG (*.bag);;"
                   "All files (*.*)")
        selections, _ = QFileDialog.getOpenFileNames(
            self, f"Open {self.band_name} file",
            GuiSettings.settings().value(input_folder_settings), filters)
        if len(selections) == 0:
            return
        last_open_folder = os.path.dirname(selections[0])
        if os.path.exists(last_open_folder):
            GuiSettings.settings().setValue(input_folder_settings,
                                            last_open_folder)

        self._set_filename(selections[0])
コード例 #21
0
class QMissionPlanning(QDialog):
    def __init__(self, game: Game):
        super(QMissionPlanning, self).__init__()
        self.game = game
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setMinimumSize(1000, 420)
        self.setModal(True)
        self.setWindowTitle("Mission Preparation")
        self.setWindowIcon(EVENT_ICONS["strike"])
        self.init_ui()
        print("DONE")

    def init_ui(self):

        self.captured_cp = [
            cp for cp in self.game.theater.controlpoints if cp.captured
        ]

        self.layout = QGridLayout()
        self.left_bar_layout = QVBoxLayout()

        self.select_airbase = QChooseAirbase(self.game)
        self.select_airbase.selected_airbase_changed.connect(
            self.on_departure_cp_changed)
        self.planned_flight_view = QPlannedFlightsView(None)
        if self.captured_cp[0].id in self.game.planners.keys():
            self.planner = self.game.planners[self.captured_cp[0].id]
            self.planned_flight_view.set_flight_planner(self.planner)
            self.selected_cp = self.captured_cp[0]

        self.planned_flight_view.selectionModel().setCurrentIndex(
            self.planned_flight_view.indexAt(QPoint(1, 1)),
            QItemSelectionModel.Rows)
        self.planned_flight_view.selectionModel().selectionChanged.connect(
            self.on_flight_selection_change)

        if len(self.planned_flight_view.flight_planner.flights) > 0:
            self.flight_planner = QFlightPlanner(
                self.planned_flight_view.flight_planner.flights[0], self.game,
                self.planned_flight_view.flight_planner, 0)
            self.flight_planner.on_planned_flight_changed.connect(
                self.update_planned_flight_view)
        else:
            self.flight_planner = QFlightPlanner(
                None, self.game, self.planned_flight_view.flight_planner, 0)
            self.flight_planner.on_planned_flight_changed.connect(
                self.update_planned_flight_view)

        self.add_flight_button = QPushButton("Add Flight")
        self.add_flight_button.clicked.connect(self.on_add_flight)
        self.delete_flight_button = QPushButton("Delete Selected")
        self.delete_flight_button.clicked.connect(self.on_delete_flight)

        self.button_layout = QHBoxLayout()
        self.button_layout.addStretch()
        self.button_layout.addWidget(self.add_flight_button)
        self.button_layout.addWidget(self.delete_flight_button)

        self.mission_start_button = QPushButton("Take Off")
        self.mission_start_button.setProperty("style", "start-button")
        self.mission_start_button.clicked.connect(self.on_start)

        self.left_bar_layout.addWidget(self.select_airbase)
        self.left_bar_layout.addWidget(self.planned_flight_view)
        self.left_bar_layout.addLayout(self.button_layout)

        self.layout.addLayout(self.left_bar_layout, 0, 0)
        self.layout.addWidget(self.flight_planner, 0, 1)
        self.layout.addWidget(self.mission_start_button,
                              1,
                              1,
                              alignment=Qt.AlignRight)

        self.setLayout(self.layout)

    @Slot(str)
    def on_departure_cp_changed(self, cp_name):
        cps = [
            cp for cp in self.game.theater.controlpoints if cp.name == cp_name
        ]

        print(cps)

        if len(cps) == 1:
            self.selected_cp = cps[0]
            self.planner = self.game.planners[cps[0].id]
            self.planned_flight_view.set_flight_planner(self.planner)
        else:
            self.planned_flight_view.set_flight_planner(None)

    def on_flight_selection_change(self):

        print("On flight selection change")

        index = self.planned_flight_view.selectionModel().currentIndex().row()
        self.planned_flight_view.repaint()

        if self.flight_planner is not None:
            self.flight_planner.clearTabs()

        try:
            flight = self.planner.flights[index]
        except IndexError:
            flight = None
        self.flight_planner = QFlightPlanner(
            flight, self.game, self.planner,
            self.flight_planner.currentIndex())
        self.flight_planner.on_planned_flight_changed.connect(
            self.update_planned_flight_view)
        self.layout.addWidget(self.flight_planner, 0, 1)

    def update_planned_flight_view(self):
        self.planned_flight_view.update_content()

    def on_add_flight(self):
        possible_aircraft_type = list(self.selected_cp.base.aircraft.keys())

        if len(possible_aircraft_type) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText("No more aircraft are available on " +
                        self.selected_cp.name + " airbase.")
            msg.setWindowTitle("No more aircraft")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setWindowFlags(Qt.WindowStaysOnTopHint)
            msg.exec_()
        else:
            self.subwindow = QFlightCreator(self.game, self.selected_cp,
                                            possible_aircraft_type,
                                            self.planned_flight_view)
            self.subwindow.show()

    def on_delete_flight(self):
        index = self.planned_flight_view.selectionModel().currentIndex().row()
        self.planner.remove_flight(index)
        self.planned_flight_view.set_flight_planner(self.planner, index)

    def on_start(self):

        # TODO : refactor this nonsense
        self.gameEvent = None
        for event in self.game.events:
            if isinstance(event,
                          FrontlineAttackEvent) and event.is_player_attacking:
                self.gameEvent = event
        if self.gameEvent is None:
            self.gameEvent = FrontlineAttackEvent(
                self.game, self.game.theater.controlpoints[0],
                self.game.theater.controlpoints[0],
                self.game.theater.controlpoints[0].position,
                self.game.player_name, self.game.enemy_name)
        #if self.awacs_checkbox.isChecked() == 1:
        #    self.gameEvent.is_awacs_enabled = True
        #    self.game.awacs_expense_commit()
        #else:
        #    self.gameEvent.is_awacs_enabled = False
        self.gameEvent.is_awacs_enabled = True
        self.gameEvent.ca_slots = 1
        self.gameEvent.departure_cp = self.game.theater.controlpoints[0]
        self.gameEvent.player_attacking({CAS: {}, CAP: {}})
        self.gameEvent.depart_from = self.game.theater.controlpoints[0]

        self.game.initiate_event(self.gameEvent)
        waiting = QWaitingForMissionResultWindow(self.gameEvent, self.game)
        waiting.show()
        self.close()
コード例 #22
0
    def init_ui(self):

        self.captured_cp = [
            cp for cp in self.game.theater.controlpoints if cp.captured
        ]

        self.layout = QGridLayout()
        self.left_bar_layout = QVBoxLayout()

        self.select_airbase = QChooseAirbase(self.game)
        self.select_airbase.selected_airbase_changed.connect(
            self.on_departure_cp_changed)
        self.planned_flight_view = QPlannedFlightsView(None)
        if self.captured_cp[0].id in self.game.planners.keys():
            self.planner = self.game.planners[self.captured_cp[0].id]
            self.planned_flight_view.set_flight_planner(self.planner)
            self.selected_cp = self.captured_cp[0]

        self.planned_flight_view.selectionModel().setCurrentIndex(
            self.planned_flight_view.indexAt(QPoint(1, 1)),
            QItemSelectionModel.Rows)
        self.planned_flight_view.selectionModel().selectionChanged.connect(
            self.on_flight_selection_change)

        if len(self.planned_flight_view.flight_planner.flights) > 0:
            self.flight_planner = QFlightPlanner(
                self.planned_flight_view.flight_planner.flights[0], self.game,
                self.planned_flight_view.flight_planner, 0)
            self.flight_planner.on_planned_flight_changed.connect(
                self.update_planned_flight_view)
        else:
            self.flight_planner = QFlightPlanner(
                None, self.game, self.planned_flight_view.flight_planner, 0)
            self.flight_planner.on_planned_flight_changed.connect(
                self.update_planned_flight_view)

        self.add_flight_button = QPushButton("Add Flight")
        self.add_flight_button.clicked.connect(self.on_add_flight)
        self.delete_flight_button = QPushButton("Delete Selected")
        self.delete_flight_button.clicked.connect(self.on_delete_flight)

        self.button_layout = QHBoxLayout()
        self.button_layout.addStretch()
        self.button_layout.addWidget(self.add_flight_button)
        self.button_layout.addWidget(self.delete_flight_button)

        self.mission_start_button = QPushButton("Take Off")
        self.mission_start_button.setProperty("style", "start-button")
        self.mission_start_button.clicked.connect(self.on_start)

        self.left_bar_layout.addWidget(self.select_airbase)
        self.left_bar_layout.addWidget(self.planned_flight_view)
        self.left_bar_layout.addLayout(self.button_layout)

        self.layout.addLayout(self.left_bar_layout, 0, 0)
        self.layout.addWidget(self.flight_planner, 0, 1)
        self.layout.addWidget(self.mission_start_button,
                              1,
                              1,
                              alignment=Qt.AlignRight)

        self.setLayout(self.layout)
コード例 #23
0
    def __init__(self, image, parent=None):
        super(FrequencyWidget, self).__init__(parent)

        self.split_spin = QSpinBox()
        self.split_spin.setRange(0, 100)
        self.split_spin.setValue(15)
        self.split_spin.setSuffix(self.tr(' %'))

        self.smooth_spin = QSpinBox()
        self.smooth_spin.setRange(0, 100)
        self.smooth_spin.setValue(25)
        self.smooth_spin.setSuffix(self.tr(' %'))
        self.smooth_spin.setSpecialValueText(self.tr('Off'))

        self.thr_spin = QSpinBox()
        self.thr_spin.setRange(0, 100)
        self.thr_spin.setValue(0)
        self.thr_spin.setSuffix(self.tr(' %'))
        self.thr_spin.setSpecialValueText(self.tr('Off'))

        self.zero_label = QLabel()
        modify_font(self.zero_label, italic=True)

        self.filter_spin = QSpinBox()
        self.filter_spin.setRange(0, 15)
        self.filter_spin.setValue(0)
        self.filter_spin.setSuffix(self.tr(' px'))
        self.filter_spin.setSpecialValueText(self.tr('Off'))

        self.split_spin.valueChanged.connect(self.process)
        self.smooth_spin.valueChanged.connect(self.process)
        self.thr_spin.valueChanged.connect(self.process)
        self.filter_spin.valueChanged.connect(self.process)

        self.image = image
        gray = cv.cvtColor(self.image, cv.COLOR_BGR2GRAY)
        rows, cols = gray.shape
        height = cv.getOptimalDFTSize(rows)
        width = cv.getOptimalDFTSize(cols)
        padded = cv.copyMakeBorder(gray, 0, height - rows, 0, width - cols, cv.BORDER_CONSTANT)
        self.dft = np.fft.fftshift(cv.dft(padded.astype(np.float32), flags=cv.DFT_COMPLEX_OUTPUT))
        self.magnitude, self.phase = cv.cartToPolar(self.dft[:, :, 0], self.dft[:, :, 1])
        self.magnitude = cv.normalize(cv.log(self.magnitude), None, 0, 255, cv.NORM_MINMAX)
        self.phase = cv.normalize(self.phase, None, 0, 255, cv.NORM_MINMAX)

        self.low_viewer = ImageViewer(self.image, self.image, self.tr('Low frequency'), export=True)
        self.high_viewer = ImageViewer(self.image, self.image, self.tr('High frequency'), export=True)
        self.mag_viewer = ImageViewer(self.image, None, self.tr('DFT Magnitude'), export=True)
        self.phase_viewer = ImageViewer(self.image, None, self.tr('DFT Phase'), export=True)
        self.process()

        self.low_viewer.viewChanged.connect(self.high_viewer.changeView)
        self.high_viewer.viewChanged.connect(self.low_viewer.changeView)
        self.mag_viewer.viewChanged.connect(self.phase_viewer.changeView)
        self.phase_viewer.viewChanged.connect(self.mag_viewer.changeView)

        top_layout = QHBoxLayout()
        top_layout.addWidget(QLabel(self.tr('Separation:')))
        top_layout.addWidget(self.split_spin)
        top_layout.addWidget(QLabel(self.tr('Smooth:')))
        top_layout.addWidget(self.smooth_spin)
        top_layout.addWidget(QLabel(self.tr('Threshold:')))
        top_layout.addWidget(self.thr_spin)
        top_layout.addWidget(QLabel(self.tr('Filter:')))
        top_layout.addWidget(self.filter_spin)
        top_layout.addWidget(self.zero_label)
        top_layout.addStretch()

        center_layout = QGridLayout()
        center_layout.addWidget(self.low_viewer, 0, 0)
        center_layout.addWidget(self.high_viewer, 0, 1)
        center_layout.addWidget(self.mag_viewer, 1, 0)
        center_layout.addWidget(self.phase_viewer, 1, 1)

        main_layout = QVBoxLayout()
        main_layout.addLayout(top_layout)
        main_layout.addLayout(center_layout)
        self.setLayout(main_layout)
コード例 #24
0
    def __init__(self):
        QMainWindow.__init__(self)

        self.title = 'test'
        self.left = 10
        self.top = 10
        self.width = 1920
        self.height = 1080

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

        self.statusBar().showMessage('Ready')

        mainMenu = self.menuBar()
        mainMenu.setNativeMenuBar(False)
        fileMenu = mainMenu.addMenu('File')
        helpMenu = mainMenu.addMenu('Help')

        exitButton = QAction(QIcon('exit24.png'), 'Exit', self)
        exitButton.setShortcut('Ctrl+Q')
        exitButton.setStatusTip('Exit application')
        exitButton.triggered.connect(self.close)
        fileMenu.addAction(exitButton)

        widget = QWidget(self)
        self.setCentralWidget(widget)
        vlay = QVBoxLayout(widget)
        hlay = QHBoxLayout()
        vlay.addLayout(hlay)

        self.nameLabel = QLabel('Name:', self)
        self.line = QLineEdit(self)
        self.nameLabel2 = QLabel('Result', self)

        hlay.addWidget(self.nameLabel)
        hlay.addWidget(self.line)
        hlay.addWidget(self.nameLabel2)
        hlay.addItem(QSpacerItem(1000, 10, QSizePolicy.Expanding))

        pybutton = QPushButton('Click me', self)
        pybutton.clicked.connect(self.clickMethod)
        hlay2 = QHBoxLayout()
        hlay2.addWidget(pybutton)
        hlay2.addItem(QSpacerItem(1000, 10, QSizePolicy.Expanding))
        vlay.addLayout(hlay2)
        m = WidgetPlot(self)
        vlay.addWidget(m)
コード例 #25
0
class VfsNodeTableWidget(QWidget):
    def __init__(self, vfs_view, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.vnode_2click_selected = None

        # Getting the Model
        self.model = VfsNodeTableModel()

        # Creating a QTableView
        self.table_view = QTableView()
        self.table_view.clicked.connect(self.clicked)
        self.table_view.doubleClicked.connect(self.double_clicked)
        font = self.table_view.font()
        font.setPointSize(8)
        self.table_view.setFont(font)
        # self.table_view.setSortingEnabled(True)
        self.table_view.setModel(self.model)

        # QTableView Headers
        self.horizontal_header = self.table_view.horizontalHeader()
        self.vertical_header = self.table_view.verticalHeader()
        self.horizontal_header.setSectionResizeMode(QHeaderView.Interactive)
        self.vertical_header.setSectionResizeMode(QHeaderView.Interactive)
        self.horizontal_header.setStretchLastSection(True)

        # QWidget Layout
        self.main_layout = QHBoxLayout()
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        # Left layout
        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)
        self.main_layout.addWidget(self.table_view)

        # Set the layout to the QWidget
        self.setLayout(self.main_layout)

        self.model.vfs_view_set(vfs_view)

    def show_all_set(self, v):
        self.model.show_all = v
        self.model.update_model()

    def vfs_view_get(self):
        return self.model.vfs_view_get()

    def clicked(self, index):
        if index.isValid():
            if self.model.vfs_view is not None:
                items = list(
                    set([
                        self.model.uid_table[idx.row()]
                        for idx in self.table_view.selectedIndexes()
                    ]))
                items = [self.model.vfs_view.node_where_uid(i) for i in items]
                self.model.vfs_view.paths_set(items)

    def double_clicked(self, index):
        if index.isValid():
            if self.vnode_2click_selected is not None:
                uids = [self.model.uid_table[index.row()]]
                self.vnode_2click_selected(uids)
コード例 #26
0
    def setup_validator(self):
        self.directory_indexer = None  # aecg.indexing.DirectoryIndexer()
        self.validator_layout_container = QWidget()
        self.validator_layout = QFormLayout()
        self.validator_form_layout = QFormLayout(
            self.validator_layout_container)
        self.validator_grid_layout = QGridLayout()
        self.study_info_file = QLineEdit()
        self.study_info_file.setToolTip("Study index file")
        self.study_info_description = QLineEdit()
        self.study_info_description.setToolTip("Description")
        self.app_type = QLineEdit()
        self.app_type.setToolTip("Application type (e.g., NDA, IND, BLA, IDE)")
        self.app_num = QLineEdit()
        self.app_num.setToolTip("Six-digit application number")
        self.app_num.setValidator(QIntValidator(self.app_num))
        self.study_id = QLineEdit()
        self.study_id.setToolTip("Study identifier")
        self.study_sponsor = QLineEdit()
        self.study_sponsor.setToolTip("Sponsor of the study")

        self.study_annotation_aecg_cb = QComboBox()
        self.study_annotation_aecg_cb.addItems(
            ["Rhythm", "Derived beat", "Holter-rhythm", "Holter-derived"])
        self.study_annotation_aecg_cb.setToolTip(
            "Waveforms used to perform the ECG measurements (i.e., "
            "annotations)\n"
            "\tRhythm: annotations in a rhythm strip or discrete ECG "
            "extraction (e.g., 10-s strips)\n"
            "\tDerived beat: annotations in a representative beat derived "
            "from a rhythm strip\n"
            "\tHolter-rhythm: annotations in a the analysis window of a "
            "continuous recording\n"
            "\tHolter-derived: annotations in a representative beat derived "
            "from analysis window of a continuous recording\n")
        self.study_annotation_lead_cb = QComboBox()
        self.ui_leads = ["GLOBAL"] + aecg.STD_LEADS[0:12] +\
            [aecg.KNOWN_NON_STD_LEADS[1]] + aecg.STD_LEADS[12:15] + ["Other"]
        self.study_annotation_lead_cb.addItems(self.ui_leads)
        self.study_annotation_lead_cb.setToolTip(
            "Primary analysis lead annotated per protocol. There could be "
            "annotations in other leads also, but only the primary lead should"
            " be selected here.\n"
            "Select global if all leads were used at the "
            "same time (e.g., superimposed on screen).\n"
            "Select other if the primary lead used is not in the list.")

        self.study_numsubjects = QLineEdit()
        self.study_numsubjects.setToolTip(
            "Number of subjects with ECGs in the study")
        self.study_numsubjects.setValidator(
            QIntValidator(self.study_numsubjects))

        self.study_aecgpersubject = QLineEdit()
        self.study_aecgpersubject.setToolTip(
            "Number of scheduled ECGs (or analysis windows) per subject as "
            "specified in the study protocol.\n"
            "Enter average number of ECGs "
            "per subject if the protocol does not specify a fixed number of "
            "ECGs per subject.")
        self.study_aecgpersubject.setValidator(
            QIntValidator(self.study_aecgpersubject))

        self.study_numaecg = QLineEdit()
        self.study_numaecg.setToolTip(
            "Total number of aECG XML files in the study")
        self.study_numaecg.setValidator(QIntValidator(self.study_numaecg))

        self.study_annotation_numbeats = QLineEdit()
        self.study_annotation_numbeats.setToolTip(
            "Minimum number of beats annotated in each ECG or analysis window"
            ".\nEnter 1 if annotations were done in the derived beat.")
        self.study_annotation_numbeats.setValidator(
            QIntValidator(self.study_annotation_numbeats))

        self.aecg_numsubjects = QLineEdit()
        self.aecg_numsubjects.setToolTip(
            "Number of subjects found across the provided aECG XML files")
        self.aecg_numsubjects.setReadOnly(True)

        self.aecg_aecgpersubject = QLineEdit()
        self.aecg_aecgpersubject.setToolTip(
            "Average number of ECGs per subject found across the provided "
            "aECG XML files")
        self.aecg_aecgpersubject.setReadOnly(True)

        self.aecg_numaecg = QLineEdit()
        self.aecg_numaecg.setToolTip(
            "Number of aECG XML files found in the study aECG directory")
        self.aecg_numaecg.setReadOnly(True)

        self.subjects_less_aecgs = QLineEdit()
        self.subjects_less_aecgs.setToolTip(
            "Percentage of subjects with less aECGs than specified per "
            "protocol")
        self.subjects_less_aecgs.setReadOnly(True)

        self.subjects_more_aecgs = QLineEdit()
        self.subjects_more_aecgs.setToolTip(
            "Percentage of subjects with more aECGs than specified per "
            "protocol")
        self.subjects_more_aecgs.setReadOnly(True)

        self.aecgs_no_annotations = QLineEdit()
        self.aecgs_no_annotations.setToolTip(
            "Percentage of aECGs with no annotations")
        self.aecgs_no_annotations.setReadOnly(True)

        self.aecgs_less_qt_in_primary_lead = QLineEdit()
        self.aecgs_less_qt_in_primary_lead.setToolTip(
            "Percentage of aECGs with less QT intervals in the primary lead "
            "than specified per protocol")
        self.aecgs_less_qt_in_primary_lead.setReadOnly(True)

        self.aecgs_less_qts = QLineEdit()
        self.aecgs_less_qts.setToolTip(
            "Percentage of aECGs with less QT intervals than specified per "
            "protocol")
        self.aecgs_less_qts.setReadOnly(True)

        self.aecgs_annotations_multiple_leads = QLineEdit()
        self.aecgs_annotations_multiple_leads.setToolTip(
            "Percentage of aECGs with QT annotations in multiple leads")
        self.aecgs_annotations_multiple_leads.setReadOnly(True)

        self.aecgs_annotations_no_primary_lead = QLineEdit()
        self.aecgs_annotations_no_primary_lead.setToolTip(
            "Percentage of aECGs with QT annotations not in the primary lead")
        self.aecgs_annotations_no_primary_lead.setReadOnly(True)

        self.aecgs_with_errors = QLineEdit()
        self.aecgs_with_errors.setToolTip("Number of aECG files with errors")
        self.aecgs_with_errors.setReadOnly(True)

        self.aecgs_potentially_digitized = QLineEdit()
        self.aecgs_potentially_digitized.setToolTip(
            "Number of aECG files potentially digitized (i.e., with more than "
            "5% of samples missing)")
        self.aecgs_potentially_digitized.setReadOnly(True)

        self.study_dir = QLineEdit()
        self.study_dir.setToolTip("Directory containing the aECG files")
        self.study_dir_button = QPushButton("...")
        self.study_dir_button.clicked.connect(self.select_study_dir)
        self.study_dir_button.setToolTip("Open select directory dialog")

        self.validator_form_layout.addRow("Application Type", self.app_type)
        self.validator_form_layout.addRow("Application Number", self.app_num)
        self.validator_form_layout.addRow("Study name/ID", self.study_id)
        self.validator_form_layout.addRow("Sponsor", self.study_sponsor)
        self.validator_form_layout.addRow("Study description",
                                          self.study_info_description)

        self.validator_form_layout.addRow("Annotations in",
                                          self.study_annotation_aecg_cb)
        self.validator_form_layout.addRow("Annotations primary lead",
                                          self.study_annotation_lead_cb)

        self.validator_grid_layout.addWidget(QLabel(""), 0, 0)
        self.validator_grid_layout.addWidget(
            QLabel("Per study protocol or report"), 0, 1)
        self.validator_grid_layout.addWidget(QLabel("Found in aECG files"), 0,
                                             2)

        self.validator_grid_layout.addWidget(QLabel("Number of subjects"), 1,
                                             0)
        self.validator_grid_layout.addWidget(self.study_numsubjects, 1, 1)
        self.validator_grid_layout.addWidget(self.aecg_numsubjects, 1, 2)

        self.validator_grid_layout.addWidget(
            QLabel("Number of aECG per subject"), 2, 0)
        self.validator_grid_layout.addWidget(self.study_aecgpersubject, 2, 1)
        self.validator_grid_layout.addWidget(self.aecg_aecgpersubject, 2, 2)

        self.validator_grid_layout.addWidget(QLabel("Total number of aECG"), 3,
                                             0)
        self.validator_grid_layout.addWidget(self.study_numaecg, 3, 1)
        self.validator_grid_layout.addWidget(self.aecg_numaecg, 3, 2)

        self.validator_grid_layout.addWidget(
            QLabel("Number of beats per aECG"), 4, 0)
        self.validator_grid_layout.addWidget(self.study_annotation_numbeats, 4,
                                             1)

        self.validator_grid_layout.addWidget(
            QLabel("Subjects with fewer ECGs"), 5, 1)
        self.validator_grid_layout.addWidget(self.subjects_less_aecgs, 5, 2)
        self.validator_grid_layout.addWidget(QLabel("Subjects with more ECGs"),
                                             6, 1)
        self.validator_grid_layout.addWidget(self.subjects_more_aecgs, 6, 2)
        self.validator_grid_layout.addWidget(
            QLabel("aECGs without annotations"), 7, 1)
        self.validator_grid_layout.addWidget(self.aecgs_no_annotations, 7, 2)
        self.validator_grid_layout.addWidget(
            QLabel("aECGs without expected number of QTs in primary lead"), 8,
            1)
        self.validator_grid_layout.addWidget(
            self.aecgs_less_qt_in_primary_lead, 8, 2)
        self.validator_grid_layout.addWidget(
            QLabel("aECGs without expected number of QTs"), 9, 1)
        self.validator_grid_layout.addWidget(self.aecgs_less_qts, 9, 2)

        self.validator_grid_layout.addWidget(
            QLabel("aECGs annotated in multiple leads"), 10, 1)
        self.validator_grid_layout.addWidget(
            self.aecgs_annotations_multiple_leads, 10, 2)
        self.validator_grid_layout.addWidget(
            QLabel("aECGs with annotations not in primary lead"), 11, 1)
        self.validator_grid_layout.addWidget(
            self.aecgs_annotations_no_primary_lead, 11, 2)
        self.validator_grid_layout.addWidget(QLabel("aECGs with errors"), 12,
                                             1)
        self.validator_grid_layout.addWidget(self.aecgs_with_errors, 12, 2)

        self.validator_grid_layout.addWidget(
            QLabel("Potentially digitized aECGs"), 13, 1)
        self.validator_grid_layout.addWidget(self.aecgs_potentially_digitized,
                                             13, 2)

        self.validator_form_layout.addRow(self.validator_grid_layout)

        tmp = QHBoxLayout()
        tmp.addWidget(self.study_dir)
        tmp.addWidget(self.study_dir_button)
        self.validator_form_layout.addRow("Study aECGs directory", tmp)

        self.validator_form_layout.addRow("Study index file",
                                          self.study_info_file)

        self.validator_layout.addWidget(self.validator_layout_container)
        self.validator_effective_dirs = QLabel("")
        self.validator_effective_dirs.setWordWrap(True)
        self.validator_layout.addWidget(self.validator_effective_dirs)

        self.val_button = QPushButton("Generate/update study index")
        self.val_button.clicked.connect(self.importstudy_dialog)
        self.validator_layout.addWidget(self.val_button)
        self.cancel_val_button = QPushButton("Cancel study index generation")
        self.cancel_val_button.clicked.connect(self.cancel_validator)
        self.cancel_val_button.setEnabled(False)
        self.validator_layout.addWidget(self.cancel_val_button)
        self.validator_pl = QLabel("")
        self.validator_layout.addWidget(self.validator_pl)
        self.validator_pb = QProgressBar()
        self.validator_layout.addWidget(self.validator_pb)
        self.validator.setLayout(self.validator_layout)
        self.stop_indexing = False

        self.lastindexing_starttime = None

        self.update_validator_effective_dirs()
コード例 #27
0
    def __init__(self):
        QWidget.__init__(self)

        self.selected_author_index = -1
        self.selected_author_name = ""

        self.author_table = QTableWidget()
        self.author_table.setColumnCount(2)
        self.author_table.setHorizontalHeaderLabels(['Name', 'Publications'])
        self.author_table.horizontalHeader().setSectionsMovable(True)
        self.author_table.setColumnWidth(0, 200)
        self.author_table.setColumnWidth(1, 75)
        self.author_table.setSortingEnabled(False)
        # self.author_table.horizontalHeader().setMaximumWidth(225)
        self.author_table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        # self.author_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        # self.author_table.setStyleSheet

        self.pubs_table = QTableWidget()
        self.pubs_table.setColumnCount(4)
        self.pubs_table.setHorizontalHeaderLabels(
            ['Title', 'Authors', 'Tags', 'Year'])
        self.pubs_table.horizontalHeader().setSectionsMovable(True)
        self.pubs_table.setColumnWidth(0, 300)
        self.pubs_table.setColumnWidth(1, 300)
        self.pubs_table.setColumnWidth(2, 300)
        self.pubs_table.setColumnWidth(3, 100)
        self.pubs_table.setSortingEnabled(False)

        self.authors_dict = {}
        self.pubs_per_author = {}
        for json in Index.gPapers:
            # print(json)
            if 'authors' in json:
                for author in json['authors']:
                    name = PapersWindow.getAuthorName(author)
                    if name not in self.authors_dict:
                        self.authors_dict[name] = {}
                        self.authors_dict[name]['pubs'] = 1
                        self.pubs_per_author[name] = []
                        self.pubs_per_author[name].append(json)
                    else:
                        self.authors_dict[name][
                            'pubs'] = self.authors_dict[name]['pubs'] + 1
                        self.pubs_per_author[name].append(json)

        # print(self.authors_tmp)
        self.authors = []
        for author in self.authors_dict:
            self.authors.append({
                'name': author,
                'pubs': self.authors_dict[author]['pubs']
            })

        self.author_table.setRowCount(len(self.authors))
        self.update_authors()

        self.sort_by_first_name = QPushButton('Sort by Name')
        self.sort_by_last_name = QPushButton('Sort by last name')
        self.sort_by_pubs = QPushButton('Sort by Publications')
        self.sort_by_title = QPushButton('Sort by Title')
        self.sort_by_year = QPushButton('Sort by Year')
        self.sort_by_recent = QPushButton('Sort by Recent')
        self.current_author_sort = 'default'
        self.current_pub_sort = 'default'

        self.author_sorting = QHBoxLayout()
        self.author_sorting.addWidget(self.sort_by_first_name)
        # self.sorting.addWidget(self.sort_by_last_name)
        self.author_sorting.addWidget(self.sort_by_pubs)

        self.pubs_sorting = QHBoxLayout()
        self.pubs_sorting.addWidget(self.sort_by_title)
        self.pubs_sorting.addWidget(self.sort_by_year)
        self.pubs_sorting.addWidget(self.sort_by_recent)

        self.sorting = QHBoxLayout()
        self.sorting.addLayout(self.author_sorting)
        self.sorting.addLayout(self.pubs_sorting)

        self.tables = QHBoxLayout()
        self.tables.addWidget(self.author_table)
        self.tables.addWidget(self.pubs_table)
        # self.layout.addLayout(self.tables)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.sorting)
        self.layout.addLayout(self.tables)

        self.setLayout(self.layout)

        self.author_table.selectionModel().currentRowChanged.connect(
            self.authors_row_changed)
        self.pubs_table.cellDoubleClicked.connect(self.pubs_cell_double_click)

        self.sort_by_first_name.clicked.connect(self.sort_by_first_name_click)
        self.sort_by_last_name.clicked.connect(self.sort_by_last_name_click)
        self.sort_by_pubs.clicked.connect(self.sort_by_pubs_click)
        self.sort_by_title.clicked.connect(self.sort_by_title_click)
        self.sort_by_year.clicked.connect(self.sort_by_year_click)
        self.sort_by_recent.clicked.connect(self.sort_by_recent_click)
コード例 #28
0
    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.style_combo = QComboBox()
        self.markers = [
            ',', '.', 'o', '8', 's', 'p', 'P', '*', 'h', 'H', 'X', 'D'
        ]
        self.style_combo.addItems([
            'pixel', 'point', 'circle', 'octa', 'square', 'penta', 'plus',
            'star', 'hexa1', 'hexa2', 'cross', 'diamond'
        ])
        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.style_combo.currentIndexChanged.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 style:')), 2, 2)
        # params_layout.addWidget(self.style_combo, 3, 4)
        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)
コード例 #29
0
 def setUp(self):
     #Acquire resources
     super(MultipleAdd, self).setUp()
     self.widget = QPushButton('click me')
     self.win = QWidget()
     self.layout = QHBoxLayout(self.win)
コード例 #30
0
    def _add_process(self):
        process_groupbox = QGroupBox("Process")
        process_groupbox.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        process_layout = QVBoxLayout()
        process_layout.setSpacing(0)
        process_groupbox.setLayout(process_layout)

        pbar_frame = QFrame()
        pbar_frame.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        pbar_hbox = QHBoxLayout()
        pbar_hbox.setContentsMargins(QtCore.QMargins(0, 0, 0, 16))
        pbar_hbox.setSpacing(16)

        # Run and stop buttons
        hbox = QHBoxLayout()
        hbox.setSpacing(8)
        self.run_button = QPushButton()
        # is only enabled when validation passes
        self.run_button.setEnabled(False)
        self.run_button.setText("Run")
        self.run_button.setFixedWidth(100)
        run_icon = qta.icon('fa.play', color='green')
        self.run_button.setIcon(run_icon)
        self.run_button.clicked.connect(self._click_run)
        hbox.addWidget(self.run_button)

        self.stop_button = QPushButton()
        self.stop_button.setEnabled(False)
        self.stop_button.setText("Stop")
        self.stop_button.setFixedWidth(100)
        stop_icon = qta.icon('fa.stop', color='red')
        self.stop_button.setIcon(stop_icon)
        self.stop_button.clicked.connect(self._click_stop)
        hbox.addWidget(self.stop_button)

        self.progress_bar = QProgressBar()
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setAlignment(QtCore.Qt.AlignCenter)
        self.progress_bar.setValue(0)
        self.progress_bar.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)

        pbar_hbox.addLayout(hbox)
        pbar_hbox.addWidget(self.progress_bar)
        pbar_frame.setLayout(pbar_hbox)
        process_layout.addWidget(pbar_frame)

        self.warning_frame = QFrame()
        self.warning_frame.setVisible(False)
        self.warning_frame.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
        hbox = QHBoxLayout()

        warning_icon_widget = qta.IconWidget('fa.warning', color='red')
        warning_icon_widget.setIconSize(QtCore.QSize(48, 48))
        warning_icon_widget.update()
        hbox.addWidget(warning_icon_widget)
        warning_label = QLabel(
            "Grid Transformer did not complete successfully. Please refer to "
            "log output.")
        warning_label.setStyleSheet("QLabel { color: red; }")
        warning_label.setWordWrap(True)
        warning_label.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Preferred)
        hbox.addWidget(warning_label)
        self.warning_frame.setLayout(hbox)
        process_layout.addWidget(self.warning_frame)

        self.success_frame = QFrame()
        self.success_frame.setVisible(False)
        self.success_frame.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
        hbox = QHBoxLayout()

        success_icon_widget = qta.IconWidget('fa.check', color='green')
        success_icon_widget.setIconSize(QtCore.QSize(48, 48))
        success_icon_widget.update()
        hbox.addWidget(success_icon_widget)
        success_label = QLabel("Grid Transformer completed successfully.")
        success_label.setStyleSheet("QLabel { color: green; }")
        success_label.setWordWrap(True)
        success_label.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Preferred)
        hbox.addWidget(success_label)
        self.success_frame.setLayout(hbox)
        process_layout.addWidget(self.success_frame)

        log_layout = QVBoxLayout()
        log_layout.setSpacing(4)
        log_label = QLabel("Log messages")
        log_label.setStyleSheet("QLabel { color: grey; }")
        log_layout.addWidget(log_label)

        self.log_messages = QPlainTextEdit()
        log_font = QFont("monospace")
        log_font.setStyleHint(QFont.TypeWriter)
        self.log_messages.setFont(log_font)
        self.log_messages.setReadOnly(True)
        self.log_messages.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        # self.log_messages.sizePolicy.setVerticalStretch(1)
        log_layout.addWidget(self.log_messages)
        process_layout.addLayout(log_layout)

        self.layout.addWidget(process_groupbox)
コード例 #31
0
class AuthorsTab(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.selected_author_index = -1
        self.selected_author_name = ""

        self.author_table = QTableWidget()
        self.author_table.setColumnCount(2)
        self.author_table.setHorizontalHeaderLabels(['Name', 'Publications'])
        self.author_table.horizontalHeader().setSectionsMovable(True)
        self.author_table.setColumnWidth(0, 200)
        self.author_table.setColumnWidth(1, 75)
        self.author_table.setSortingEnabled(False)
        # self.author_table.horizontalHeader().setMaximumWidth(225)
        self.author_table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        # self.author_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        # self.author_table.setStyleSheet

        self.pubs_table = QTableWidget()
        self.pubs_table.setColumnCount(4)
        self.pubs_table.setHorizontalHeaderLabels(
            ['Title', 'Authors', 'Tags', 'Year'])
        self.pubs_table.horizontalHeader().setSectionsMovable(True)
        self.pubs_table.setColumnWidth(0, 300)
        self.pubs_table.setColumnWidth(1, 300)
        self.pubs_table.setColumnWidth(2, 300)
        self.pubs_table.setColumnWidth(3, 100)
        self.pubs_table.setSortingEnabled(False)

        self.authors_dict = {}
        self.pubs_per_author = {}
        for json in Index.gPapers:
            # print(json)
            if 'authors' in json:
                for author in json['authors']:
                    name = PapersWindow.getAuthorName(author)
                    if name not in self.authors_dict:
                        self.authors_dict[name] = {}
                        self.authors_dict[name]['pubs'] = 1
                        self.pubs_per_author[name] = []
                        self.pubs_per_author[name].append(json)
                    else:
                        self.authors_dict[name][
                            'pubs'] = self.authors_dict[name]['pubs'] + 1
                        self.pubs_per_author[name].append(json)

        # print(self.authors_tmp)
        self.authors = []
        for author in self.authors_dict:
            self.authors.append({
                'name': author,
                'pubs': self.authors_dict[author]['pubs']
            })

        self.author_table.setRowCount(len(self.authors))
        self.update_authors()

        self.sort_by_first_name = QPushButton('Sort by Name')
        self.sort_by_last_name = QPushButton('Sort by last name')
        self.sort_by_pubs = QPushButton('Sort by Publications')
        self.sort_by_title = QPushButton('Sort by Title')
        self.sort_by_year = QPushButton('Sort by Year')
        self.sort_by_recent = QPushButton('Sort by Recent')
        self.current_author_sort = 'default'
        self.current_pub_sort = 'default'

        self.author_sorting = QHBoxLayout()
        self.author_sorting.addWidget(self.sort_by_first_name)
        # self.sorting.addWidget(self.sort_by_last_name)
        self.author_sorting.addWidget(self.sort_by_pubs)

        self.pubs_sorting = QHBoxLayout()
        self.pubs_sorting.addWidget(self.sort_by_title)
        self.pubs_sorting.addWidget(self.sort_by_year)
        self.pubs_sorting.addWidget(self.sort_by_recent)

        self.sorting = QHBoxLayout()
        self.sorting.addLayout(self.author_sorting)
        self.sorting.addLayout(self.pubs_sorting)

        self.tables = QHBoxLayout()
        self.tables.addWidget(self.author_table)
        self.tables.addWidget(self.pubs_table)
        # self.layout.addLayout(self.tables)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.sorting)
        self.layout.addLayout(self.tables)

        self.setLayout(self.layout)

        self.author_table.selectionModel().currentRowChanged.connect(
            self.authors_row_changed)
        self.pubs_table.cellDoubleClicked.connect(self.pubs_cell_double_click)

        self.sort_by_first_name.clicked.connect(self.sort_by_first_name_click)
        self.sort_by_last_name.clicked.connect(self.sort_by_last_name_click)
        self.sort_by_pubs.clicked.connect(self.sort_by_pubs_click)
        self.sort_by_title.clicked.connect(self.sort_by_title_click)
        self.sort_by_year.clicked.connect(self.sort_by_year_click)
        self.sort_by_recent.clicked.connect(self.sort_by_recent_click)

    def update_authors(self):
        i = 0
        for author in self.authors:
            item1 = QTableWidgetItem()
            self.author_table.setItem(i, 0, item1)
            item1.setText(author['name'])
            item1.setFlags(Qt.ItemIsEnabled)

            item2 = QTableWidgetItem()
            self.author_table.setItem(i, 1, item2)
            item2.setText(str(author['pubs']))
            item2.setFlags(Qt.ItemIsEnabled)

            i += 1

    def update_pubs(self):
        self.pubs_table.setRowCount(
            len(self.pubs_per_author[self.selected_author_name]))

        i = 0
        for paper in self.pubs_per_author[self.selected_author_name]:
            item1 = QTableWidgetItem()
            self.pubs_table.setItem(i, 0, item1)
            item1.setText(paper['title'])
            item1.setFlags(Qt.ItemIsEnabled)

            item2 = QTableWidgetItem()
            self.pubs_table.setItem(i, 1, item2)
            item2.setText(PapersWindow.getAuthorString(paper['authors']))
            item2.setFlags(Qt.ItemIsEnabled)

            item3 = QTableWidgetItem()
            self.pubs_table.setItem(i, 2, item3)
            if 'tags' in paper:
                item3.setText(PapersWindow.getTagsString(paper['tags']))
            else:
                item3.setText('')
            item3.setFlags(Qt.ItemIsEnabled)

            item4 = QTableWidgetItem()
            self.pubs_table.setItem(i, 3, item4)
            item4.setText(str(paper['year']))
            item4.setFlags(Qt.ItemIsEnabled)

            i += 1

    # @Slot()
    # def authors_cell_click(self, row, column):
    # 	self.selected_author_index = row
    # 	self.selected_author_name = self.authors[row]['name']
    # 	self.update_pubs()

    # 	print('set selected_author_index', row)

    @Slot()
    def authors_row_changed(self, curr, prev):
        row = curr.row()
        self.selected_author_index = row
        self.selected_author_name = self.authors[row]['name']
        self.sort()
        self.update_pubs()

        print('set selected_author_index', row)

    @Slot()
    def pubs_cell_double_click(self, row, column):
        # subprocess.run(['xdg-open', self.pubs_per_author[self.selected_author_name][row]['path']], check=True)
        Index.open_paper(
            self.pubs_per_author[self.selected_author_name][row]['path'])

    def sort(self):
        if self.current_author_sort == 'name':
            self.authors.sort(key=sortByFirstName)
        if self.current_author_sort == 'name_rev':
            self.authors.sort(key=sortByFirstName, reverse=True)
            print('reverse sor tbyname')
        if self.current_author_sort == 'pubs':
            self.authors.sort(key=sortByPubs, reverse=True)
        if self.current_author_sort == 'pubs_rev':
            self.authors.sort(key=sortByPubs)

        if self.current_pub_sort == 'title':
            self.pubs_per_author[self.selected_author_name].sort(
                key=PapersWindow.sortByTitle)
        if self.current_pub_sort == 'title_rev':
            self.pubs_per_author[self.selected_author_name].sort(
                key=PapersWindow.sortByTitle, reverse=True)
        if self.current_pub_sort == 'year':
            self.pubs_per_author[self.selected_author_name].sort(
                key=PapersWindow.sortByYear)
        if self.current_pub_sort == 'year_rev':
            self.pubs_per_author[self.selected_author_name].sort(
                key=PapersWindow.sortByYear, reverse=True)
        if self.current_pub_sort == 'recent':
            self.pubs_per_author[self.selected_author_name].sort(
                key=PapersWindow.sortByRecent, reverse=True)
        if self.current_pub_sort == 'recent_rev':
            self.pubs_per_author[self.selected_author_name].sort(
                key=PapersWindow.sortByRecent)

    @Slot()
    def sort_by_first_name_click(self):
        if self.current_author_sort == 'name':
            self.current_author_sort = 'name_rev'
        else:
            self.current_author_sort = 'name'
        self.sort()
        self.update_authors()
        self.update_pubs()

    @Slot()
    def sort_by_last_name_click(self):
        if self.current_author_sort == 'name':
            self.current_author_sort = 'name_rev'
        else:
            self.current_author_sort = 'name'
        self.sort()
        self.update_authors()
        self.update_pubs()

    @Slot()
    def sort_by_pubs_click(self):
        if self.current_author_sort == 'pubs':
            self.current_author_sort = 'pubs_rev'
        else:
            self.current_author_sort = 'pubs'
        self.sort()
        self.update_authors()
        self.update_pubs()

    @Slot()
    def sort_by_title_click(self):
        if self.current_pub_sort == 'title':
            self.current_pub_sort = 'title_rev'
        else:
            self.current_pub_sort = 'title'
        self.sort()
        self.update_authors()
        self.update_pubs()

    @Slot()
    def sort_by_year_click(self):
        if self.current_pub_sort == 'year':
            self.current_pub_sort = 'year_rev'
        else:
            self.current_pub_sort = 'year'
        self.sort()
        self.update_authors()
        self.update_pubs()

    @Slot()
    def sort_by_recent_click(self):
        if self.current_pub_sort == 'recent':
            self.current_pub_sort = 'recent_rev'
        else:
            self.current_pub_sort = 'recent'
        self.sort()
        self.update_authors()
        self.update_pubs()
コード例 #32
0
    def run_tests(self):
        """run the tests selected on the table and show the results"""
        from TestManager.commands.test import test

        test_list = []

        use_selected = True
        for row in self.table.selectionModel().selectedRows():
            if self.table.isRowHidden(row.row()):
                continue

            test_name = self.table.item(row.row(), 0).text()
            test_list.append(test_name)

        if not test_list:
            use_selected = False
            for i in range(0, self.table.rowCount()):
                if self.table.isRowHidden(i):
                    continue

                test_name = self.table.item(i, 0).text()
                test_list.append(test_name)

            if not test_list:
                test_list = ["all"]

        results = test(self.session, test_list)

        cell_widgets = []

        for name in results:
            widget = QWidget()
            widget_layout = QHBoxLayout(widget)
            widget_layout.setContentsMargins(0, 0, 0, 0)

            success_button = get_button("success")
            fail_button = get_button("fail")
            skip_button = get_button("skip")
            error_button = get_button("error")
            expected_fail_button = get_button("expected fail")
            unexpected_success_button = get_button("unexpected success")

            success_count = 0
            fail_count = 0
            error_count = 0
            unexpected_success_count = 0
            expected_fail_count = 0
            skip_count = 0

            success_tooltip = "Successes:\n"
            fail_tooltip = "Failed tests:\n"
            error_tooltip = "Errors during test:\n"
            unexpected_success_tooltip = "Unexpected successes:\n"
            expected_fail_tooltip = "Expected fails:\n"
            skip_tooltip = "Skipped tests:\n"

            for case in results[name]:
                result, msg = results[name][case]
                if result == "success":
                    success_count += 1
                    success_tooltip += "%s.%s: %s\n" % (
                        case.__class__.__qualname__, case._testMethodName, msg)

                elif result == "fail":
                    fail_count += 1
                    fail_tooltip += "%s.%s failed: %s\n" % (
                        case.__class__.__qualname__, case._testMethodName, msg)

                elif result == "error":
                    error_count += 1
                    error_tooltip += "error during %s.%s: %s\n" % (
                        case.__class__.__qualname__, case._testMethodName, msg)

                elif result == "expected_failure":
                    expected_fail_count += 1
                    expected_fail_tooltip += "intended failure during %s.%s: %s\n" % (
                        case.__class__.__qualname__, case._testMethodName, msg)

                elif result == "skip":
                    skip_count += 1
                    skip_tooltip += "%s.%s\n" % (case.__class__.__qualname__,
                                                 case._testMethodName)

                elif result == "unexpected_success":
                    unexpected_success_count += 1
                    unexpected_success_tooltip += "%s.%s should not have worked, but did\n" % (
                        case.__class__.__qualname__, case._testMethodName)

            success_tooltip = success_tooltip.strip()
            fail_tooltip = fail_tooltip.strip()
            error_tooltip = error_tooltip.strip()
            expected_fail_tooltip = expected_fail_tooltip.strip()
            skip_tooltip = skip_tooltip.strip()
            unexpected_success_tooltip = unexpected_success_tooltip.strip()

            icon_count = 0
            if success_count:
                success_button.setText("%i" % success_count)
                success_button.setToolTip(success_tooltip)
                success_button.clicked.connect(
                    lambda *args, t_name=name, res=success_tooltip: self.
                    tool_window.create_child_window(
                        "successes for %s" % t_name,
                        text=res,
                        window_class=ResultsWindow,
                    ))
                widget_layout.insertWidget(icon_count, success_button, 1)
                icon_count += 1

            if fail_count:
                fail_button.setText("%i" % fail_count)
                fail_button.setToolTip(fail_tooltip)
                fail_button.clicked.connect(
                    lambda *args, res=fail_tooltip: self.tool_window.
                    create_child_window(
                        "failures for %s" % name,
                        text=res,
                        window_class=ResultsWindow,
                    ))
                widget_layout.insertWidget(icon_count, fail_button, 1)
                icon_count += 1

            if error_count:
                error_button.setText("%i" % error_count)
                error_button.setToolTip(error_tooltip)
                error_button.clicked.connect(
                    lambda *args, res=error_tooltip: self.tool_window.
                    create_child_window(
                        "errors for %s" % name,
                        text=res,
                        window_class=ResultsWindow,
                    ))
                widget_layout.insertWidget(icon_count, error_button, 1)
                icon_count += 1

            if unexpected_success_count:
                unexpected_success_button.setText("%i" %
                                                  unexpected_success_count)
                unexpected_success_button.setToolTip(
                    unexpected_success_tooltip)
                unexpected_success_button.clicked.connect(
                    lambda *args, res=unexpected_success_tooltip: self.
                    tool_window.create_child_window(
                        "unexpected successes for %s" % name,
                        text=res,
                        window_class=ResultsWindow,
                    ))
                widget_layout.insertWidget(icon_count,
                                           unexpected_success_button, 1)
                icon_count += 1

            if expected_fail_count:
                expected_fail_button.setText("%i" % expected_fail_count)
                expected_fail_button.setToolTip(expected_fail_tooltip)
                expected_fail_button.clicked.connect(
                    lambda *args, res=expected_fail_tooltip: self.tool_window.
                    create_child_window(
                        "expected failures for %s" % name,
                        text=res,
                        window_class=ResultsWindow,
                    ))
                widget_layout.insertWidget(icon_count, expected_fail_button, 1)
                icon_count += 1

            if skip_count:
                skip_button.setText("%i" % skip_count)
                skip_button.setToolTip(skip_tooltip)
                skip_button.clicked.connect(
                    lambda *args, res=skip_tooltip: self.tool_window.
                    create_child_window(
                        "skipped tests for %s" % name,
                        text=res,
                        window_class=ResultsWindow,
                    ))
                widget_layout.insertWidget(icon_count, skip_button, 1)

            cell_widgets.append(widget)

        widget_count = 0
        if use_selected:
            for row in self.table.selectionModel().selectedRows():
                if self.table.isRowHidden(row.row()):
                    continue

                self.table.setCellWidget(row.row(), 1,
                                         cell_widgets[widget_count])
                self.table.resizeRowToContents(row.row())
                widget_count += 1

        else:
            for i in range(0, self.table.rowCount()):
                if self.table.isRowHidden(i):
                    continue

                self.table.setCellWidget(i, 1, cell_widgets[widget_count])
                # self.table.resizeRowToContents(i)
                widget_count += 1
コード例 #33
0
ファイル: ColorEdit.py プロジェクト: goph-R/TilePad
    def __init__(self, parent=None):
        super(ColorEdit, self).__init__(parent)

        self.color = QColor('#FF00FF')

        self.edit = QLineEdit()
        self.edit.setText('FF00FF')
        self.edit.setMaximumWidth(70)
        self.edit.textEdited.connect(self.editChanged)
        self.edit.returnPressed.connect(self.editChanged)

        self.box = QPushButton()
        self.box.setFlat(True)
        self.box.setFixedSize(18, 18)
        self.box.setStyleSheet('background-color: #FF00FF; border: 1px solid black;')
        self.box.setCursor(Qt.PointingHandCursor)
        self.box.clicked.connect(self.boxClicked)

        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(0, 0, 0, 0)
        hlayout.setSpacing(0)
        hlayout.addWidget(QLabel('#'))
        hlayout.addWidget(self.edit)
        hlayout.addSpacing(5)
        hlayout.addWidget(self.box)
        hlayout.addStretch()

        self.setLayout(hlayout)
コード例 #34
0
 def __init__(self, parent, name, data):
     global instance_id
     QWidget.__init__(self, parent)
     DockContextHandler.__init__(self, self, name)
     self.actionHandler = UIActionHandler()
     self.actionHandler.setupActionHandler(self)
     offset_layout = QHBoxLayout()
     offset_layout.addWidget(QLabel("Offset: "))
     self.offset = QLabel(hex(0))
     offset_layout.addWidget(self.offset)
     offset_layout.setAlignment(QtCore.Qt.AlignCenter)
     datatype_layout = QHBoxLayout()
     datatype_layout.addWidget(QLabel("Data Type: "))
     self.datatype = QLabel("")
     datatype_layout.addWidget(self.datatype)
     datatype_layout.setAlignment(QtCore.Qt.AlignCenter)
     layout = QVBoxLayout()
     title = QLabel(name, self)
     title.setAlignment(QtCore.Qt.AlignCenter)
     instance = QLabel("Instance: " + str(instance_id), self)
     instance.setAlignment(QtCore.Qt.AlignCenter)
     layout.addStretch()
     layout.addWidget(title)
     layout.addWidget(instance)
     layout.addLayout(datatype_layout)
     layout.addLayout(offset_layout)
     layout.addStretch()
     self.setLayout(layout)
     instance_id += 1
     self.data = data
コード例 #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
class DataViewerImage(DataViewer):
    def __init__(self):
        DataViewer.__init__(self)

        self.ddsc = None

        self.image_display = PhotoViewer(self)
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.image_display.setSizePolicy(size)

        self.select_dropdown = QComboBox()
        self.select_dropdown.setEditable(False)
        self.select_dropdown.addItem('A')
        self.select_dropdown.addItem('B')
        self.select_dropdown.addItem('C')
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.select_dropdown.setSizePolicy(size)
        self.select_dropdown.currentIndexChanged.connect(self.select_dropdown_current_index_changed)

        self.checkbox_opaque = QCheckBox(self)
        self.checkbox_opaque.setText('Opaque')
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.checkbox_opaque.setSizePolicy(size)
        self.checkbox_opaque.setChecked(True)
        self.checkbox_opaque.clicked.connect(self.color_control_clicked)

        self.checkbox_show_r = QCheckBox(self)
        self.checkbox_show_r.setText('Red')
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.checkbox_show_r.setSizePolicy(size)
        self.checkbox_show_r.setChecked(True)
        self.checkbox_show_r.clicked.connect(self.color_control_clicked)

        self.checkbox_show_g = QCheckBox(self)
        self.checkbox_show_g.setText('Green')
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.checkbox_show_g.setSizePolicy(size)
        self.checkbox_show_g.setChecked(True)
        self.checkbox_show_g.clicked.connect(self.color_control_clicked)

        self.checkbox_show_b = QCheckBox(self)
        self.checkbox_show_b.setText('Blue')
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        self.checkbox_show_b.setSizePolicy(size)
        self.checkbox_show_b.setChecked(True)
        self.checkbox_show_b.clicked.connect(self.color_control_clicked)

        self.color_layout = QHBoxLayout()
        self.color_layout.addWidget(self.checkbox_opaque)
        self.color_layout.addWidget(self.checkbox_show_r)
        self.color_layout.addWidget(self.checkbox_show_g)
        self.color_layout.addWidget(self.checkbox_show_b)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.image_display)
        self.main_layout.addWidget(self.select_dropdown)
        self.main_layout.addLayout(self.color_layout)
        self.setLayout(self.main_layout)

        self.update_image()

    def update_image(self):
        v = self.select_dropdown.currentIndex()
        if self.ddsc is not None and 0 <= v < len(self.ddsc.mips):
            npimp = self.ddsc.mips[v].data
            if npimp is not None:
                npimp = npimp.copy()
                if self.checkbox_opaque.isChecked() and npimp.shape[2] == 4:
                    npimp[:, :, 3] = 0xFF
                if not self.checkbox_show_r.isChecked():
                    npimp[:, :, 0] = 0
                if not self.checkbox_show_g.isChecked():
                    npimp[:, :, 1] = 0
                if not self.checkbox_show_b.isChecked():
                    npimp[:, :, 2] = 0

                if npimp.shape[2] == 3:
                    frmt = QImage.Format_RGB888
                elif npimp.shape[2] == 4:
                    frmt = QImage.Format_RGBA8888
                else:
                    raise Exception('Unhandled byte counts for image')

                qimg = QImage(npimp.data, npimp.shape[1], npimp.shape[0], npimp.shape[1] * npimp.shape[2], frmt)
                pixmap = QPixmap.fromImage(qimg)
                self.image_display.setPhoto(pixmap)

    def select_dropdown_current_index_changed(self, v):
        self.update_image()

    def color_control_clicked(self, checked):
        self.update_image()

    def vnode_process(self, vfs: VfsProcessor, vnode: VfsNode):
        self.ddsc = None
        self.select_dropdown.clear()

        if vnode.file_type in {FTYPE_BMP, FTYPE_DDS, FTYPE_AVTX, FTYPE_ATX, FTYPE_HMDDSC}:
            self.ddsc = deca.ff_avtx.image_load(vfs, vnode)

        if self.ddsc is not None and self.ddsc.mips is not None:
            first_valid = None
            for i in range(len(self.ddsc.mips)):
                mip = self.ddsc.mips[i]
                if first_valid is None and mip.data is not None:
                    first_valid = i
                depth_info = ''
                if mip.depth_idx is not None and mip.depth_cnt is not None:
                    depth_info = 'd:{}/{} '.format(mip.depth_idx, mip.depth_cnt)
                self.select_dropdown.addItem('{}x{} {}({})'.format(mip.size_y, mip.size_x, depth_info, mip.itype))

            self.select_dropdown.setCurrentIndex(first_valid)
コード例 #37
0
ファイル: ela.py プロジェクト: weskerfoot/sherloq
    def __init__(self, image, parent=None):
        super(ElaWidget, self).__init__(parent)

        self.quality_spin = QSpinBox()
        self.quality_spin.setRange(0, 100)
        self.quality_spin.setSuffix(self.tr(' %'))
        self.quality_spin.setToolTip(self.tr('JPEG reference quality level'))
        self.scale_spin = QSpinBox()
        self.scale_spin.setRange(1, 100)
        self.scale_spin.setSuffix(' %')
        self.scale_spin.setToolTip(self.tr('Output multiplicative gain'))
        self.contrast_spin = QSpinBox()
        self.contrast_spin.setRange(0, 100)
        self.contrast_spin.setSuffix(' %')
        self.contrast_spin.setToolTip(self.tr('Output tonality compression'))
        self.equalize_check = QCheckBox(self.tr('Equalized'))
        self.equalize_check.setToolTip(self.tr('Apply histogram equalization'))
        self.gray_check = QCheckBox(self.tr('Grayscale'))
        self.gray_check.setToolTip(self.tr('Desaturated output'))
        default_button = QPushButton(self.tr('Default'))
        default_button.setToolTip(self.tr('Revert to default parameters'))

        params_layout = QHBoxLayout()
        params_layout.addWidget(QLabel(self.tr('Quality:')))
        params_layout.addWidget(self.quality_spin)
        params_layout.addWidget(QLabel(self.tr('Scale:')))
        params_layout.addWidget(self.scale_spin)
        params_layout.addWidget(QLabel(self.tr('Contrast:')))
        params_layout.addWidget(self.contrast_spin)
        params_layout.addWidget(self.equalize_check)
        params_layout.addWidget(self.gray_check)
        params_layout.addWidget(default_button)
        params_layout.addStretch()

        self.image = image
        self.original = image.astype(np.float32) / 255
        self.viewer = ImageViewer(self.image, self.image)
        self.default()

        self.quality_spin.valueChanged.connect(self.process)
        self.scale_spin.valueChanged.connect(self.process)
        self.contrast_spin.valueChanged.connect(self.process)
        self.equalize_check.stateChanged.connect(self.process)
        self.gray_check.stateChanged.connect(self.process)
        default_button.clicked.connect(self.default)

        main_layout = QVBoxLayout()
        main_layout.addLayout(params_layout)
        main_layout.addWidget(self.viewer)
        self.setLayout(main_layout)
コード例 #38
0
    def __init__(self, filename, image, parent=None):
        super(ComparisonWidget, self).__init__(parent)

        load_button = QPushButton(self.tr('Load reference image...'))
        self.comp_label = QLabel(self.tr('Comparison:'))
        self.normal_radio = QRadioButton(self.tr('Normal'))
        self.normal_radio.setToolTip(self.tr('Show reference (raw pixels)'))
        self.normal_radio.setChecked(True)
        self.difference_radio = QRadioButton(self.tr('Difference'))
        self.difference_radio.setToolTip(
            self.tr('Show evidence/reference difference'))
        self.ssim_radio = QRadioButton(self.tr('SSIM Map'))
        self.ssim_radio.setToolTip(self.tr('Structure similarity quality map'))
        self.butter_radio = QRadioButton(self.tr('Butteraugli'))
        self.butter_radio.setToolTip(
            self.tr('Butteraugli spatial changes heatmap'))
        self.gray_check = QCheckBox(self.tr('Grayscale'))
        self.gray_check.setToolTip(self.tr('Show desaturated output'))
        self.equalize_check = QCheckBox(self.tr('Equalized'))
        self.equalize_check.setToolTip(self.tr('Apply histogram equalization'))
        self.last_radio = self.normal_radio
        self.metric_button = QPushButton(self.tr('Compute'))
        self.metric_button.setToolTip(
            self.tr('Image quality assessment metrics'))

        self.evidence = image
        self.reference = self.difference = self.ssim_map = self.butter_map = None
        basename = os.path.basename(filename)
        self.evidence_viewer = ImageViewer(
            self.evidence, None, self.tr('Evidence: {}'.format(basename)))
        self.reference_viewer = ImageViewer(np.full_like(self.evidence, 127),
                                            None, self.tr('Reference'))

        self.table_widget = QTableWidget(21, 3)
        self.table_widget.setHorizontalHeaderLabels(
            [self.tr('Metric'),
             self.tr('Value'),
             self.tr('Better')])
        self.table_widget.setItem(0, 0, QTableWidgetItem(self.tr('RMSE')))
        self.table_widget.setItem(
            0, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(0, 0).setToolTip(
            self.
            tr('Root Mean Square Error (RMSE) is commonly used to compare \n'
               'the difference between the reference and evidence images \n'
               'by directly computing the variation in pixel values. \n'
               'The combined image is close to the reference image when \n'
               'RMSE value is zero. RMSE is a good indicator of the spectral \n'
               'quality of the reference image.'))
        self.table_widget.setItem(1, 0, QTableWidgetItem(self.tr('SAM')))
        self.table_widget.setItem(
            1, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(1, 0).setToolTip(
            self.
            tr('It computes the spectral angle between the pixel, vector of the \n'
               'evidence image and reference image. It is worked out in either \n'
               'degrees or radians. It is performed on a pixel-by-pixel base. \n'
               'A SAM equal to zero denotes the absence of spectral distortion.'
               ))
        self.table_widget.setItem(2, 0, QTableWidgetItem(self.tr('ERGAS')))
        self.table_widget.setItem(
            2, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(2, 0).setToolTip(
            self.
            tr('It is used to compute the quality of reference image in terms \n'
               'of normalized average error of each band of the reference image. \n'
               'Increase in the value of ERGAS indicates distortion in the \n'
               'reference image, lower value of ERGAS indicates that it is \n'
               'similar to the reference image.'))
        self.table_widget.setItem(3, 0, QTableWidgetItem(self.tr('MB')))
        self.table_widget.setItem(
            3, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(3, 0).setToolTip(
            self.
            tr('Mean Bias is the difference between the mean of the evidence \n'
               'image and reference image. The ideal value is zero and indicates \n'
               'that the evidence and reference images are similar. Mean value \n'
               'refers to the grey level of pixels in an image.'))
        self.table_widget.setItem(4, 0, QTableWidgetItem(self.tr('PFE')))
        self.table_widget.setItem(
            4, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(4, 0).setToolTip(
            self.
            tr('It computes the norm of the difference between the corresponding \n'
               'pixels of the reference and fused image to the norm of the reference \n'
               'image. When the calculated value is zero, it indicates that both the \n'
               'reference and fused images are similar and value will be increased \n'
               'when the merged image is not similar to the reference image.'))
        self.table_widget.setItem(5, 0, QTableWidgetItem(self.tr('PSNR')))
        self.table_widget.setItem(
            5, 2,
            QTableWidgetItem(QIcon('icons/high.svg'), '(+' + u'\u221e' + ')'))
        self.table_widget.item(5, 0).setToolTip(
            self.
            tr('It is widely used metric it is computed by the number of gray levels \n'
               'in the image divided by the corresponding pixels in the evidence and \n'
               'the reference images. When the value is high, both images are similar.'
               ))
        self.table_widget.setItem(6, 0, QTableWidgetItem(self.tr('PSNR-B')))
        self.table_widget.setItem(
            6, 2,
            QTableWidgetItem(QIcon('icons/high.svg'), '(+' + u'\u221e' + ')'))
        self.table_widget.item(6, 0).setToolTip(
            self.tr('PSNR with Blocking Effect Factor.'))
        self.table_widget.setItem(7, 0, QTableWidgetItem(self.tr('SSIM')))
        self.table_widget.setItem(
            7, 2, QTableWidgetItem(QIcon('icons/high.svg'), '(1)'))
        self.table_widget.item(7, 0).setToolTip(
            self.
            tr('SSIM is used to compare the local patterns of pixel intensities between \n'
               ' the reference and fused images. The range varies between -1 to 1. \n'
               'The value 1 indicates the reference and fused images are similar.'
               ))
        self.table_widget.setItem(8, 0, QTableWidgetItem(self.tr('MS-SSIM')))
        self.table_widget.setItem(
            8, 2, QTableWidgetItem(QIcon('icons/high.svg'), '(1)'))
        self.table_widget.item(8, 0).setToolTip(
            self.tr('Multiscale version of SSIM.'))
        self.table_widget.setItem(9, 0, QTableWidgetItem(self.tr('RASE')))
        self.table_widget.setItem(
            9, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(9, 0).setToolTip(
            self.tr('Relative average spectral error'))
        self.table_widget.setItem(10, 0, QTableWidgetItem(self.tr('SCC')))
        self.table_widget.setItem(
            10, 2, QTableWidgetItem(QIcon('icons/high.svg'), '(1)'))
        self.table_widget.item(10, 0).setToolTip(
            self.tr('Spatial Correlation Coefficient'))
        self.table_widget.setItem(11, 0, QTableWidgetItem(self.tr('UQI')))
        self.table_widget.setItem(
            11, 2, QTableWidgetItem(QIcon('icons/high.svg'), '(1)'))
        self.table_widget.item(11, 0).setToolTip(
            self.tr('Universal Image Quality Index'))
        self.table_widget.setItem(12, 0, QTableWidgetItem(self.tr('VIF-P')))
        self.table_widget.setItem(
            12, 2, QTableWidgetItem(QIcon('icons/high.svg'), '(1)'))
        self.table_widget.item(12, 0).setToolTip(
            self.tr('Pixel-based Visual Information Fidelity'))
        self.table_widget.setItem(13, 0,
                                  QTableWidgetItem(self.tr('SSIMulacra')))
        self.table_widget.setItem(
            13, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(13, 0).setToolTip(
            self.tr('Structural SIMilarity Unveiling Local '
                    'And Compression Related Artifacts'))
        self.table_widget.setItem(14, 0,
                                  QTableWidgetItem(self.tr('Butteraugli')))
        self.table_widget.setItem(
            14, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(14, 0).setToolTip(
            self.tr('Estimate psychovisual error'))
        self.table_widget.setItem(15, 0,
                                  QTableWidgetItem(self.tr('Correlation')))
        self.table_widget.setItem(
            15, 2, QTableWidgetItem(QIcon('icons/high.svg'), '(1)'))
        self.table_widget.item(15,
                               0).setToolTip(self.tr('Histogram correlation'))
        self.table_widget.setItem(16, 0,
                                  QTableWidgetItem(self.tr('Chi-Square')))
        self.table_widget.setItem(
            16, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(16,
                               0).setToolTip(self.tr('Histogram Chi-Square'))
        self.table_widget.setItem(17, 0,
                                  QTableWidgetItem(self.tr('Chi-Square 2')))
        self.table_widget.setItem(
            17, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(17,
                               0).setToolTip(self.tr('Alternative Chi-Square'))
        self.table_widget.setItem(18, 0,
                                  QTableWidgetItem(self.tr('Intersection')))
        self.table_widget.setItem(
            18, 2,
            QTableWidgetItem(QIcon('icons/high.svg'), '(+' + u'\u221e' + ')'))
        self.table_widget.item(18,
                               0).setToolTip(self.tr('Histogram intersection'))
        self.table_widget.setItem(19, 0,
                                  QTableWidgetItem(self.tr('Hellinger')))
        self.table_widget.setItem(
            19, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(19, 0).setToolTip(
            self.tr('Histogram Hellinger distance'))
        self.table_widget.setItem(20, 0,
                                  QTableWidgetItem(self.tr('Divergence')))
        self.table_widget.setItem(
            20, 2, QTableWidgetItem(QIcon('icons/low.svg'), '(0)'))
        self.table_widget.item(20, 0).setToolTip(
            self.tr('Kullback-Leibler divergence'))

        for i in range(self.table_widget.rowCount()):
            modify_font(self.table_widget.item(i, 0), bold=True)
        self.table_widget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table_widget.resizeColumnsToContents()
        self.table_widget.setMaximumWidth(250)
        self.table_widget.setAlternatingRowColors(True)
        self.stopped = False

        self.comp_label.setEnabled(False)
        self.normal_radio.setEnabled(False)
        self.difference_radio.setEnabled(False)
        self.ssim_radio.setEnabled(False)
        self.butter_radio.setEnabled(False)
        self.gray_check.setEnabled(False)
        self.equalize_check.setEnabled(False)
        self.metric_button.setEnabled(False)
        self.table_widget.setEnabled(False)

        load_button.clicked.connect(self.load)
        self.normal_radio.clicked.connect(self.change)
        self.difference_radio.clicked.connect(self.change)
        self.butter_radio.clicked.connect(self.change)
        self.gray_check.stateChanged.connect(self.change)
        self.equalize_check.stateChanged.connect(self.change)
        self.ssim_radio.clicked.connect(self.change)
        self.evidence_viewer.viewChanged.connect(
            self.reference_viewer.changeView)
        self.reference_viewer.viewChanged.connect(
            self.evidence_viewer.changeView)
        self.metric_button.clicked.connect(self.metrics)

        top_layout = QHBoxLayout()
        top_layout.addWidget(load_button)
        top_layout.addStretch()
        top_layout.addWidget(self.comp_label)
        top_layout.addWidget(self.normal_radio)
        top_layout.addWidget(self.difference_radio)
        top_layout.addWidget(self.ssim_radio)
        top_layout.addWidget(self.butter_radio)
        top_layout.addWidget(self.gray_check)
        top_layout.addWidget(self.equalize_check)

        metric_layout = QVBoxLayout()
        index_label = QLabel(self.tr('Image Quality Assessment'))
        index_label.setAlignment(Qt.AlignCenter)
        modify_font(index_label, bold=True)
        metric_layout.addWidget(index_label)
        metric_layout.addWidget(self.table_widget)
        metric_layout.addWidget(self.metric_button)

        center_layout = QHBoxLayout()
        center_layout.addWidget(self.evidence_viewer)
        center_layout.addWidget(self.reference_viewer)
        center_layout.addLayout(metric_layout)

        main_layout = QVBoxLayout()
        main_layout.addLayout(top_layout)
        main_layout.addLayout(center_layout)
        self.setLayout(main_layout)
コード例 #39
0
    def __init__(self, app, appname, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.hide()
        #self.setMinimumSize(640, 480)
        self.setFixedSize(self.geometry().width(), self.geometry().height())
        self.setWindowIcon(QIcon('icon.ico'))
        self.setWindowTitle(appname)

        # Create menu bar
        menu_bar = QMenuBar()

        help_menu = menu_bar.addAction('&Help')
        about_menu = menu_bar.addAction('A&bout')
        exit_menu = menu_bar.addAction('&Exit')

        self.setMenuBar(menu_bar)

        # Make interface layouts
        window = QWidget()
        layout = QVBoxLayout()

        top_section = QVBoxLayout()

        buttons = QGridLayout()
        middle_section = QHBoxLayout()

        label_section = QHBoxLayout()
        range_section = QGridLayout()
        clarity_section = QHBoxLayout()
        plot_section = QHBoxLayout()
        bottom_section = QVBoxLayout()

        status_layout = QHBoxLayout()

        # Create widgets and items
        figure = plt.figure()
        canvas = FigureCanvas(figure)

        label = QLabel(f'''Welcome to {appname}!
Plot any equation of the form y = f(x).
Use the options below to plot your own equation!''')

        help_message = QMessageBox()
        help_message.setTextFormat(Qt.RichText)
        help_message.setText(f'''<h3>Help</h3>
{appname} lets you plot any equation of the form y = f(x).
<br/>
Enter the function f(x), specify the range of x, and click Plot!
<br/><br/>
Operators : <code>+, -, *, /</code><br/>
Variable : <code>x</code><br/>
Functions : <code>sin, cos, tan</code><br/>
<code>pi</code> : π<br/>
<code>e</code> : Exponential e<br/>
<code>c</code> : Speed of Light<br/>''')
        help_message.setStandardButtons(QMessageBox.Ok)
        help_message.setWindowTitle(f'{appname} - Help')
        self.help = help_message

        help_button = QPushButton('Help...')
        help_button.clicked.connect(self.help.exec_)

        about_message = QMessageBox()
        about_message.setWindowTitle(f'{appname} - About')
        about_message.setTextFormat(Qt.RichText)
        about_message.setText(f'''<h3>About</h3>
{appname} is created in PySide2 (Qt), using \
the Matplotlib and Equation PyPI modules for plotting and parsing expressions respectively.
<br/><br/>
Created by <a href="http://paramsid.com">Param Siddharth</a>.''')
        about_message.setStandardButtons(QMessageBox.Ok)
        self.about = about_message

        about_button = QPushButton('About...')
        about_button.clicked.connect(self.about.exec_)

        expr_label = QLabel('f(x) =')
        expr_input = QLineEdit()

        range_label1 = QLabel('Minimum (x):')
        range_min = QLineEdit()
        range_label2 = QLabel('Maximum (x):')
        range_max = QLineEdit()

        clarity_label = QLabel('Clarity:')
        clarity_spinbox = QSpinBox()
        clarity_spinbox.setRange(1, 10000)
        clarity_spinbox.setValue(100)

        plot_button = QPushButton('Plot')
        plot_button.setMaximumWidth(200)

        status = QStatusBar()
        status_text = QLabel('')
        status_text.setStyleSheet('color: #999999;')

        attribution = QLabel(
            'Made with <span style="color: red;">❤</span> by <a href="http://paramsid.com">Param</a>'
        )
        attribution.setTextFormat(Qt.RichText)
        attribution.setStyleSheet('color: #555555; font-size: 20px;')
        attribution.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        help_menu.triggered.connect(self.help.exec_)
        about_menu.triggered.connect(self.about.exec_)
        exit_menu.triggered.connect(self.close)

        # Configure backend
        backmath.configure(canvas=canvas,
                           figure=figure,
                           btn=plot_button,
                           text=expr_input,
                           limits=(range_min, range_max),
                           status=status_text,
                           range_text=(range_min, range_max),
                           clarity=clarity_spinbox)

        # Finalize and display
        top_section.addWidget(canvas)

        buttons.addWidget(help_button, 0, 0, 1, 1)
        buttons.addWidget(about_button, 0, 1, 1, 1)

        middle_section.addWidget(label)
        middle_section.addLayout(buttons)

        label_section.addWidget(expr_label)
        label_section.addWidget(expr_input)

        equally_spaced = QSizePolicy(QSizePolicy.Preferred,
                                     QSizePolicy.Preferred)
        equally_spaced.setHorizontalStretch(1)

        range_label1.setSizePolicy(equally_spaced)
        range_min.setSizePolicy(equally_spaced)
        range_label2.setSizePolicy(equally_spaced)
        range_max.setSizePolicy(equally_spaced)

        range_label1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        range_label2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        range_section.addWidget(range_label1, 0, 0, 1, 1)
        range_section.addWidget(range_min, 0, 1, 1, 1)
        range_section.addWidget(range_label2, 0, 2, 1, 1)
        range_section.addWidget(range_max, 0, 3, 1, 1)

        clarity_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        clarity_section.addWidget(clarity_label)
        clarity_section.addWidget(clarity_spinbox)

        plot_section.addWidget(plot_button)

        status.addWidget(status_text)
        status.addPermanentWidget(attribution)

        status_layout.addWidget(status)

        bottom_section.addLayout(label_section)
        bottom_section.addLayout(range_section)
        bottom_section.addLayout(clarity_section)
        bottom_section.addLayout(plot_section)

        layout.addLayout(top_section)
        layout.addLayout(middle_section)
        layout.addLayout(bottom_section)
        layout.addLayout(status_layout)

        window.setLayout(layout)
        self.setCentralWidget(window)
        self.show()

        status_text.setText('READY ')
コード例 #40
0
    def initUI(self):

        ui = FreeCADGui.UiLoader()

        # create our window
        # define window		xLoc,yLoc,xDim,yDim
        self.setGeometry(	250, 250, 640, 480)
        self.setWindowTitle(translate('Rocket', "Ejection Charge Calculator"))
        self.resize(QtCore.QSize(100,100).expandedTo(self.minimumSizeHint())) # sets size of the widget
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

        self.warningLabel = QtGui.QTextEdit()
        self.warningLabel.setLineWrapMode(QtGui.QTextEdit.WidgetWidth)
        self.warningLabel.setHtml(translate('Rocket','''
        <html>
        <h1>WARNING</h1>
        <p>This calculator is an estimate only. Ground test your ejection system before flying. In certain cases this calculation may overestimate the amount of powder required</p>
        </html>
        '''))
        # self.warningLabel.setFixedWidth(250)
        self.warningLabel.setReadOnly(True)

        self.diameterLabel = QtGui.QLabel(translate('Rocket', "Body Tube Diameter"), self)

        self.diameterInput = ui.createWidget("Gui::InputField")
        self.diameterInput.unit = 'mm'
        self.diameterInput.setFixedWidth(100)
        self.diameterInput.setText("98.0 mm")
        self.diameterInput.textEdited.connect(self.onDiameter)

        self.lengthLabel = QtGui.QLabel(translate('Rocket', "Body Tube Length"), self)

        self.lengthInput = ui.createWidget("Gui::InputField")
        self.lengthInput.unit = 'mm'
        self.lengthInput.setText("300.0 mm")
        self.lengthInput.setFixedWidth(100)
        self.lengthInput.textEdited.connect(self.onLength)

        self.forceLabel = QtGui.QLabel(translate('Rocket', "Force"), self)

        self.forceInput = ui.createWidget("Gui::InputField")
        self.forceInput.unit = 'N'
        self.forceInput.setText("667.233 N")
        self.forceInput.setFixedWidth(100)
        self.forceInput.textEdited.connect(self.onForce)

        self.pressureLabel = QtGui.QLabel(translate('Rocket', "Pressure"), self)

        self.pressureInput = ui.createWidget("Gui::InputField")
        self.pressureInput.unit = 'kPa'
        self.pressureInput.setText("1034.25 kPa")
        self.pressureInput.setFixedWidth(100)
        self.pressureInput.textEdited.connect(self.onPressure)

        self.forceTypes = (
            FORCE_CUSTOM,
            FORCE_LOW,
            FORCE_HIGH
        )
        self.forceCombo = QtGui.QComboBox(self)
        self.forceCombo.addItems(self.forceTypes)
        self.forceCombo.setCurrentText(FORCE_LOW)
        self.forceCombo.currentTextChanged.connect(self.onForceCombo)

        self.powderLabel = QtGui.QLabel(translate('Rocket', "FFFFg Powder"), self)

        self.powderInput = QtGui.QLineEdit()
        self.powderInput.setText("49.0 g")
        self.powderInput.setFixedWidth(100)
        self.powderInput.setReadOnly(True)

        # OK button
        okButton = QtGui.QPushButton('OK', self)
        okButton.setDefault(False)
        okButton.setAutoDefault(False)
        okButton.clicked.connect(self.onOk)

        layout = QVBoxLayout()

        line = QHBoxLayout()
        line.addWidget(self.warningLabel)
        layout.addLayout(line)

        line = QGridLayout()

        row = 0
        line.addWidget(self.diameterLabel, row, 0, 1, 2)
        line.addWidget(self.diameterInput, row, 1)
        row += 1

        line.addWidget(self.lengthLabel, row, 0)
        line.addWidget(self.lengthInput, row, 1)
        row += 1

        line.addWidget(self.forceLabel, row, 0)
        line.addWidget(self.forceInput, row, 1)
        line.addWidget(self.forceCombo, row, 2)
        row += 1

        line.addWidget(self.pressureLabel, row, 0)
        line.addWidget(self.pressureInput, row, 1)
        row += 1

        line.addWidget(self.powderLabel, row, 0)
        line.addWidget(self.powderInput, row, 1)

        layout.addLayout(line)

        line = QHBoxLayout()
        line.addStretch()
        line.addWidget(okButton)
        layout.addLayout(line)

        self.setLayout(layout)

        self._setPressureFromForce()
        self._calc()

        # now make the window visible
        self.show()
コード例 #41
0
    def __init__(self, targetImage=None, axeSize=500, layer=None, parent=None):
        super().__init__(layer=layer, targetImage=targetImage, parent=parent)

        #######################################
        # Libraw correspondences:
        # rgb_xyz_matrix is libraw cam_xyz
        # camera_whitebalance is libraw cam_mul
        # daylight_whitebalance is libraw pre_mul
        # dng correspondences:
        # ASSHOTNEUTRAL tag value is (X,Y,Z) =  1 / rawpyObj.camera_whitebalance
        ##########################################
        rawpyObj = layer.parentImage.rawImage

        # constants and as shot values
        self.XYZ2CameraMatrix = rawpyObj.rgb_xyz_matrix[:3, :]
        self.XYZ2CameraInverseMatrix = np.linalg.inv(self.XYZ2CameraMatrix)
        # initial post processing multipliers (as shot)
        m1, m2, m3, m4 = rawpyObj.camera_whitebalance
        self.asShotMultipliers = (m1/m2, 1.0, m3/m2, m4/m2)  # normalization is mandatory : for nef files white balance is around 256
        self.asShotTemp, self.asShotTint = multipliers2TemperatureAndTint(*1 / np.array(self.asShotMultipliers[:3]), self.XYZ2CameraMatrix)
        self.rawMultipliers = self.asShotMultipliers  # rawpyObj.camera_whitebalance # = 1/(dng ASSHOTNEUTRAL tag value)
        self.sampleMultipliers = False
        self.samples = []
        ########################################
        # XYZ-->Camera conversion matrix:
        # Last row is zero for RGB cameras (cf. rawpy and libraw docs).
        # type ndarray, shape (4,3)
        #########################################

        # attributes initialized in setDefaults, declared here for the sake of correctness
        self.tempCorrection, self.tintCorrection, self.expCorrection, self.highCorrection,\
                                                   self.contCorrection, self.satCorrection, self.brCorrection = [None] * 7
        # contrast spline vie (initialized by setContrastSpline)
        self.contrastForm = None
        # tone spline view (initialized by setToneSpline)
        self.toneForm = None
        # dock containers for contrast and tome forms
        self.dockC, self.dockT = None, None
        # options
        optionList0, optionNames0 = ['Auto Brightness', 'Preserve Highlights'], ['Auto Expose', 'Preserve Highlights']
        optionList1, optionNames1 = ['Auto WB', 'Camera WB', 'User WB'], ['Auto', 'Camera (As Shot)', 'User']
        optionList2, optionNames2 = ['cpLookTable', 'cpToneCurve', 'manualCurve'], ['Use Camera Profile Look Table',
                                                                                    'Show Tone Curves', 'Show Contrast Curve']
        self.listWidget1 = optionsWidget(options=optionList0, optionNames=optionNames0, exclusive=False,
                                         changed=lambda: self.dataChanged.emit(1))
        self.listWidget2 = optionsWidget(options=optionList1, optionNames=optionNames1,  exclusive=True,
                                         changed=lambda: self.dataChanged.emit(1))
        self.listWidget3 = optionsWidget(options=optionList2, optionNames=optionNames2, exclusive=False,
                                         changed=lambda: self.dataChanged.emit(2))
        self.options = UDict((self.listWidget1.options, self.listWidget2.options, self.listWidget3.options))
        # display the 'as shot' temperature
        item = self.listWidget2.item(1)
        item.setText(item.text() + ' : %d' % self.asShotTemp)

        # temperature slider
        self.sliderTemp = QbLUeSlider(Qt.Horizontal)
        self.sliderTemp.setStyleSheet(QbLUeSlider.bLueSliderDefaultColorStylesheet)
        self.sliderTemp.setRange(0, 100)
        self.sliderTemp.setSingleStep(1)

        self.tempLabel = QLabel()
        self.tempLabel.setText("Temp")

        self.tempValue = QLabel()
        font = self.tempValue.font()
        metrics = QFontMetrics(font)
        w = metrics.width("10000")
        h = metrics.height()
        self.tempValue.setMinimumSize(w, h)
        self.tempValue.setMaximumSize(w, h)
        self.tempValue.setText(str("{:.0f}".format(self.slider2Temp(self.sliderTemp.value()))))

        self.sliderTemp.valueChanged.connect(self.tempUpdate)  # signal send new value as parameter
        self.sliderTemp.sliderReleased.connect(lambda: self.tempUpdate(self.sliderTemp.value()))  # signal pass no parameter

        # tint slider
        self.sliderTint = QbLUeSlider(Qt.Horizontal)
        self.sliderTint.setStyleSheet(QbLUeSlider.bLueSliderDefaultIMGColorStylesheet)
        self.sliderTint.setRange(0, 150)

        self.sliderTint.setSingleStep(1)

        self.tintLabel = QLabel()
        self.tintLabel.setText("Tint")

        self.tintValue = QLabel()
        font = self.tempValue.font()
        metrics = QFontMetrics(font)
        w = metrics.width("100")
        h = metrics.height()
        self.tintValue.setMinimumSize(w, h)
        self.tintValue.setMaximumSize(w, h)
        self.tintValue.setText(str("{:.0f}".format(self.sliderTint2User(self.sliderTint.value()))))

        self.sliderTint.valueChanged.connect(self.tintUpdate)
        self.sliderTint.sliderReleased.connect(lambda: self.tintUpdate(self.sliderTint.value()))  # signal pass no parameter)

        ######################
        # From libraw and dcraw sources:
        # Exposure and brightness are curve transformations.
        # Exposure curve is y = alpha*x, with cubic root ending; it is applied before demosaicing.
        # Brightness is (similar to) y = x**alpha and part of gamma transformation from linear sRGB to RGB.
        # Exposure and brightness both dilate the histogram towards highlights.
        # Exposure dilatation is uniform (homothety), brightness dilataion is
        # maximum for the midtones and the highlghts are preserved.
        # As a consequence, normal workflow begins with the adjustment of exposure,
        # to fill the entire range of the histogram and to adjust the highlights. Next,
        # one adjusts the brightness to put the midtones at the level we want them to be.
        # Cf. https://www.cambridgeincolour.com/forums/thread653.htm
        #####################

        # profile combo
        self.dngDict = self.setCameraProfilesCombo()
        # cameraProfilesCombo index changed event handler

        def cameraProfileUpdate(value):
            self.dngDict = self.cameraProfilesCombo.itemData(value)
            if self.options['cpToneCurve']:
                toneCurve = dngProfileToneCurve(self.dngDict.get('ProfileToneCurve', []))
                self.toneForm.baseCurve = [QPointF(x * axeSize, -y * axeSize) for x, y in zip(toneCurve.dataX, toneCurve.dataY)]
                self.toneForm.update()
            # recompute as shot temp and tint using new profile
            self.asShotTemp, self.asShotTint = multipliers2TemperatureAndTint(*1 / np.array(self.asShotMultipliers[:3]),
                                                                              self.XYZ2CameraMatrix, self.dngDict)
            # display updated as shot temp
            item = self.listWidget2.item(1)
            item.setText(item.text().split(":")[0] + ': %d' % self.asShotTemp)
            # invalidate cache
            self.layer.bufCache_HSV_CV32 = None
            self.dataChanged.emit(2)  # 2 = no postprocessing

        self.cameraProfilesCombo.currentIndexChanged.connect(cameraProfileUpdate)

        # denoising combo
        self.denoiseCombo = QComboBox()
        items = OrderedDict([('Off', 0), ('Medium', 1), ('Full', 2)])
        for key in items:
            self.denoiseCombo.addItem(key, items[key])

        # denoiseCombo index changed event handler
        def denoiseUpdate(value):
            self.denoiseValue = self.denoiseCombo.itemData(value)
            self.dataChanged.emit(1)

        self.denoiseCombo.currentIndexChanged.connect(denoiseUpdate)

        # overexposed area restoration
        self.overexpCombo = QComboBox()
        items = OrderedDict([('Clip', 0), ('Ignore', 1), ('Blend', 2), ('Reconstruct', 3)])
        for key in items:
            self.overexpCombo.addItem(key, items[key])

        # overexpCombo index changed event handler
        def overexpUpdate(value):
            self.overexpValue = self.overexpCombo.itemData(value)
            self.dataChanged.emit(1)

        self.overexpCombo.currentIndexChanged.connect(overexpUpdate)

        # exp slider
        self.sliderExp = QbLUeSlider(Qt.Horizontal)
        self.sliderExp.setStyleSheet(QbLUeSlider.bLueSliderDefaultBWStylesheet)
        self.sliderExp.setRange(0, 100)

        self.sliderExp.setSingleStep(1)

        self.expLabel = QLabel()
        self.expLabel.setText("Exp.")

        self.expValue = QLabel()
        font = self.expValue.font()
        metrics = QFontMetrics(font)
        w = metrics.width("+1.0")
        h = metrics.height()
        self.expValue.setMinimumSize(w, h)
        self.expValue.setMaximumSize(w, h)
        self.expValue.setText(str("{:.1f}".format(self.slider2Exp(self.sliderExp.value()))))

        # exp done event handler
        def expUpdate(value):
            self.expValue.setText(str("{:+.1f}".format(self.sliderExp2User(self.sliderExp.value()))))
            # move not yet terminated or value not modified
            if self.sliderExp.isSliderDown() or self.slider2Exp(value) == self.expCorrection:
                return
            try:
                self.sliderExp.valueChanged.disconnect()
                self.sliderExp.sliderReleased.disconnect()
            except RuntimeError:
                pass
            # rawpy: expCorrection range is -2.0...3.0, boiling down to exp_shift range 2**(-2)=0.25...2**3=8.0
            self.expCorrection = self.slider2Exp(self.sliderExp.value())
            self.dataChanged.emit(1)
            self.sliderExp.valueChanged.connect(expUpdate)  # send new value as parameter
            self.sliderExp.sliderReleased.connect(lambda: expUpdate(self.sliderExp.value()))  # signal pass no parameter
        self.sliderExp.valueChanged.connect(expUpdate)  # send new value as parameter
        self.sliderExp.sliderReleased.connect(lambda: expUpdate(self.sliderExp.value()))      # signal pass no parameter

        # brightness slider
        brSlider = QbLUeSlider(Qt.Horizontal)
        brSlider.setRange(1, 101)

        self.sliderExp.setSingleStep(1)

        brSlider.setStyleSheet(QbLUeSlider.bLueSliderDefaultBWStylesheet)

        self.sliderBrightness = brSlider
        brLabel = QLabel()
        brLabel.setText("Bright.")

        self.brValue = QLabel()
        font = self.expValue.font()
        metrics = QFontMetrics(font)
        w = metrics.width("+99")
        h = metrics.height()
        self.brValue.setMinimumSize(w, h)
        self.brValue.setMaximumSize(w, h)
        self.brValue.setText(str("{:+d}".format(int(self.brSlider2User(self.sliderBrightness.value())))))

        # brightness done event handler
        def brUpdate(value):
            self.brValue.setText(str("{:+d}".format(int(self.brSlider2User(self.sliderBrightness.value())))))
            # move not yet terminated or value not modified
            if self.sliderBrightness.isSliderDown() or self.slider2Br(value) == self.brCorrection:
                return
            try:
                self.sliderBrightness.valueChanged.disconnect()
                self.sliderBrightness.sliderReleased.disconnect()
            except RuntimeError:
                pass
            self.brCorrection = self.slider2Br(self.sliderBrightness.value())
            self.dataChanged.emit(1)
            self.sliderBrightness.sliderReleased.connect(lambda: brUpdate(self.sliderBrightness.value()))
            self.sliderBrightness.valueChanged.connect(brUpdate)  # send new value as parameter
        self.sliderBrightness.valueChanged.connect(brUpdate)  # send new value as parameter
        self.sliderBrightness.sliderReleased.connect(lambda: brUpdate(self.sliderBrightness.value()))

        # contrast slider
        self.sliderCont = QbLUeSlider(Qt.Horizontal)
        self.sliderCont.setStyleSheet(QbLUeSlider.bLueSliderDefaultBWStylesheet)
        self.sliderCont.setRange(0, 20)

        self.sliderCont.setSingleStep(1)

        self.contLabel = QLabel()
        self.contLabel.setText("Cont.")

        self.contValue = QLabel()
        font = self.contValue.font()
        metrics = QFontMetrics(font)
        w = metrics.width("100")
        h = metrics.height()
        self.contValue.setMinimumSize(w, h)
        self.contValue.setMaximumSize(w, h)
        self.contValue.setText(str("{:.0f}".format(self.slider2Cont(self.sliderCont.value()))))

        # cont done event handler
        def contUpdate(value):
            self.contValue.setText(str("{:.0f}".format(self.slider2Cont(self.sliderCont.value()))))
            # move not yet terminated or value not modified
            if self.sliderCont.isSliderDown() or self.slider2Cont(value) == self.tempCorrection:
                return
            try:
                self.sliderCont.valueChanged.disconnect()
                self.sliderCont.sliderReleased.disconnect()
            except RuntimeError:
                pass
            self.contCorrection = self.slider2Cont(self.sliderCont.value())
            self.contValue.setText(str("{:+d}".format(self.contCorrection)))
            # force to recalculate the spline
            self.layer.autoSpline = True
            self.dataChanged.emit(3)  # no postprocessing and no camera profile stuff
            self.sliderCont.valueChanged.connect(contUpdate)  # send new value as parameter
            self.sliderCont.sliderReleased.connect(lambda: contUpdate(self.sliderCont.value()))  # signal has no parameter
        self.sliderCont.valueChanged.connect(contUpdate)  # send new value as parameter
        self.sliderCont.sliderReleased.connect(lambda: contUpdate(self.sliderCont.value()))  # signal has no parameter

        # saturation slider
        self.sliderSat = QbLUeSlider(Qt.Horizontal)
        self.sliderSat.setStyleSheet(QbLUeSlider.bLueSliderDefaultColorStylesheet)
        self.sliderSat.setRange(0, 100)

        self.sliderSat.setSingleStep(1)

        satLabel = QLabel()
        satLabel.setText("Sat.")

        self.satValue = QLabel()
        font = self.satValue.font()
        metrics = QFontMetrics(font)
        w = metrics.width("+10")
        h = metrics.height()
        self.satValue.setMinimumSize(w, h)
        self.satValue.setMaximumSize(w, h)
        self.satValue.setText(str("{:+d}".format(self.slider2Sat(self.sliderSat.value()))))

        """sat done event handler"""
        def satUpdate(value):
            self.satValue.setText(str("{:+d}".format(self.slider2Sat(self.sliderSat.value()))))
            # move not yet terminated or value not modified
            if self.sliderSat.isSliderDown() or self.slider2Sat(value) == self.satCorrection:
                return
            try:
                self.sliderSat.valueChanged.disconnect()
                self.sliderSat.sliderReleased.disconnect()
            except RuntimeError:
                pass
            self.satCorrection = self.slider2Sat(self.sliderSat.value())
            self.dataChanged.emit(3)  # no post processing and no camera profile stuff
            self.sliderSat.valueChanged.connect(satUpdate)  # send new value as parameter
            self.sliderSat.sliderReleased.connect(lambda: satUpdate(self.sliderSat.value()))  # signal has no parameter
        self.sliderSat.valueChanged.connect(satUpdate)  # send new value as parameter
        self.sliderSat.sliderReleased.connect(lambda: satUpdate(self.sliderSat.value()))  # signal has no parameter

        self.setStyleSheet("QListWidget, QLabel {font : 7pt;}")

        # layout
        l = QVBoxLayout()
        l.addWidget(self.listWidget3)
        hl01 = QHBoxLayout()
        hl01.addWidget(QLabel('Camera Profile'))
        hl01.addWidget(self.cameraProfilesCombo)
        l.addLayout(hl01)
        hl0 = QHBoxLayout()
        hl0.addWidget(QLabel('Denoising'))
        hl0.addWidget(self.denoiseCombo)
        l.addLayout(hl0)
        hl00 = QHBoxLayout()
        hl00.addWidget(QLabel('Overexp. Restoration'))
        hl00.addWidget(self.overexpCombo)
        l.addLayout(hl00)
        hl1 = QHBoxLayout()
        hl1.addWidget(self.expLabel)
        hl1.addWidget(self.expValue)
        hl1.addWidget(self.sliderExp)
        l.addLayout(hl1)
        hl8 = QHBoxLayout()
        hl8.addWidget(brLabel)
        hl8.addWidget(self.brValue)
        hl8.addWidget(self.sliderBrightness)
        l.addLayout(hl8)
        l.addWidget(self.listWidget1)
        self.listWidget2.setStyleSheet("QListWidget {border: 0px;} QListWidget::item {border: 0px; padding-left: 20px;}")
        vl1 = QVBoxLayout()
        vl1.addWidget(QLabel('White Balance'))
        vl1.addWidget(self.listWidget2)
        gb1 = QGroupBox()
        gb1.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px}")
        hl2 = QHBoxLayout()
        hl2.addWidget(self.tempLabel)
        hl2.addWidget(self.tempValue)
        hl2.addWidget(self.sliderTemp)
        hl3 = QHBoxLayout()
        hl3.addWidget(self.tintLabel)
        hl3.addWidget(self.tintValue)
        hl3.addWidget(self.sliderTint)
        vl1.addLayout(hl2)
        vl1.addLayout(hl3)
        gb1.setLayout(vl1)
        l.addWidget(gb1)
        hl4 = QHBoxLayout()
        hl4.addWidget(self.contLabel)
        hl4.addWidget(self.contValue)
        hl4.addWidget(self.sliderCont)
        hl7 = QHBoxLayout()
        hl7.addWidget(satLabel)
        hl7.addWidget(self.satValue)
        hl7.addWidget(self.sliderSat)

        # separator
        sep = QFrame()
        sep.setFrameShape(QFrame.HLine)
        sep.setFrameShadow(QFrame.Sunken)
        l.addWidget(sep)
        l.addLayout(hl4)
        l.addLayout(hl7)
        l.addStretch(1)
        self.setLayout(l)
        self.adjustSize()
        self.setDefaults()
        self.setWhatsThis(
                    """<b>Development of raw files</b><br>
                    <b>Default settings</b> are a good starting point.<br>
                    A <b>Tone Curve</b> is applied to the raw image prior to postprocessing.<br> 
                    The cuvre can be edited by checking the option
                    <b>Show Tone Curve</b>; this option works best with manual exposure.<br>
                    <b>Contrast</b> correction is based on an automatic algorithm 
                    well suited to multi-mode histograms.<br>
                    <b>Brightness, Contrast</b> and <b>Saturation</b> levels</b> are 
                    adjustable with the correponding sliders.<br>
                    The <b>Contrast Curve</b> can be edited manually by checking 
                    the option <b>Show Contrast Curve</b>.<br>
                    Uncheck <b>Auto Expose</b> to adjust the exposure manually.<br>
                    The <b>OverExp. Rest.</b> slider controls the mode of restoration of overexposed areas. 
                    Valid values are 0 to 3 (0=clip;1=unclip;2=blend;3=rebuild); (with Auto Exposed 
                    checked the mode is clip).<br>
                    """
                        )  # end of setWhatsThis
コード例 #42
0
class TagsCheckboxWindow(QWidget):
    def __init__(self, path, owner):
        QWidget.__init__(self)
        self.path = path
        self.scroll_area = QScrollArea()
        self.num_columns = 3
        self.owner = owner
        # self.checkboxes_widget = QWidget()

        for paper in Index.gPapers:
            if paper['path'] == self.path:
                self.paper = paper

        self.columns = []
        for i in range(self.num_columns):
            layout = QVBoxLayout()
            layout.setSpacing(0)
            layout.setMargin(0)
            self.columns.append(layout)

        self.checkboxes = []
        self.tags_copy = Index.gTags.copy()
        self.tags_copy.sort(key=lambda s: s)

        count = 0
        for tag in self.tags_copy:
            checkbox = QCheckBox(tag)
            self.checkboxes.append(checkbox)
            self.columns[int(
                (self.num_columns * count) / len(self.tags_copy))].addWidget(
                    checkbox)  #add the checkbox to the appropriate column

            if 'tags' in self.paper:
                if tag in self.paper['tags']:
                    checkbox.setChecked(True)

            checkbox.clicked.connect(self.checkbox_click_creator(checkbox))
            count += 1

        # self.checkboxes_widget.setLayout(self.layout)
        # self.scroll_area.setWidget(self.checkboxes_widget)

        self.layout = QHBoxLayout()
        for col in self.columns:
            self.layout.addLayout(col)

        self.scroll_area.setLayout(self.layout)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll_area.setWidgetResizable(True)

        self.full_layout = QHBoxLayout()
        self.full_layout.addWidget(self.scroll_area)

        self.setLayout(self.full_layout)

    def checkbox_click_creator(self, box):
        @Slot()
        def checkbox_click():
            if box.isChecked() == True:
                # print('checkbox for', self.path, 'is true')
                if 'tags' not in self.paper:
                    self.paper['tags'] = []
                if box.text() not in self.paper['tags']:
                    self.paper['tags'].append(box.text())
                    Index.save_json(Index.gJSONfilename)
                    # self.owner.PapersView = Index.gPapers.copy()
                    # self.owner.update()
                    self.owner.copy_sort_update()
                # for paper in Index.gPapers:
                # 	if paper['path'] == self.path:
                # 		if 'tags' not in paper:
                # 			paper['tags'] = []

                # 		if box.text() not in paper['tags']:
                # 			paper['tags'].append(box.text())
                # 			Index.save_json(Index.gJSONfilename)

                # 		break

            else:
                print('checkbox', box.text(), 'for', self.path, 'is false')
                if 'tags' not in self.paper:
                    self.paper['tags'] = []
                if box.text() in self.paper['tags']:
                    self.paper['tags'].remove(box.text())
                    Index.save_json(Index.gJSONfilename)
                    # self.owner.PapersView = Index.gPapers.copy()
                    # self.owner.update()
                    self.owner.copy_sort_update()
                # for paper in Index.gPapers:
                # 	if paper['path'] == self.path:
                # 		if 'tags' not in paper:
                # 			paper['tags'] = []

                # 		if box.text() in paper['tags']:
                # 			paper['tags'].remove(box.text())
                # 			Index.save_json(Index.gJSONfilename)

                # 		break

        return checkbox_click
コード例 #43
0
    def __init__(self):
        QWidget.__init__(self)

        self.q = None
        self.pool = None

        self.top = QHBoxLayout()
        self.top.setMargin(10)

        self.radioButtonMov = QRadioButton("电影")
        self.radioButtonCinema = QRadioButton("连续剧/综艺/动漫")

        self.top.addWidget(self.radioButtonMov)
        self.top.addWidget(self.radioButtonCinema)

        self.middle = QVBoxLayout()
        self.middle.setMargin(10)

        self.url_label = QLabel()
        self.url = QLineEdit()
        self.url_label.setBuddy(self.url)
        self.middle.addWidget(self.url_label)
        self.middle.addWidget(self.url)

        self.browse_folder_label = QLabel("下载到:")
        self.browseFolder = QPushButton("选择目录")
        self.browse_folder_label.setBuddy(self.browseFolder)
        self.middle.addWidget(self.browse_folder_label)
        self.middle.addWidget(self.browseFolder)
        self.browse_folder_value = ""

        self.dest_file_label = QLabel()
        # "输入电影/电视剧名 (用来命名下载的文件/目录): " title set by choose_movie_widgets() later
        self.folder_or_filename = QLineEdit()
        self.dest_file_label.setBuddy(self.folder_or_filename)
        self.middle.addWidget(self.dest_file_label)
        self.middle.addWidget(self.folder_or_filename)

        self.bk_cinemae_spin_from = 1
        self.bk_cinemae_spin_to = 1
        self.fromEpSpinBox = QSpinBox()
        self.fromEpSpinBox.setMinimum(1)
        self.fromEpSpinBox.setMaximum(2147483647)
        self.fromEpLabel = QLabel("&从第几集开始下载:")
        self.fromEpLabel.setBuddy(self.fromEpSpinBox)

        self.toEpSpinBox = QSpinBox()
        self.toEpSpinBox.setMinimum(1)
        self.toEpSpinBox.setMaximum(2147483647)
        self.toEpLabel = QLabel("&到第几集停止下载:")
        self.toEpLabel.setBuddy(self.toEpSpinBox)

        self.cinema_ly = QHBoxLayout()
        #self.cinema_ly.setMargin(10)
        self.cinema_ly.addWidget(self.fromEpLabel)
        self.cinema_ly.addWidget(self.fromEpSpinBox)
        self.cinema_ly.addWidget(self.toEpLabel)
        self.cinema_ly.addWidget(self.toEpSpinBox)
        self.middle.addLayout(self.cinema_ly)

        self.proxy_label = QLabel("(如有)代理:")
        self.proxy = QLineEdit()
        self.proxy_label.setBuddy(self.proxy)
        self.middle.addWidget(self.proxy_label)
        self.middle.addWidget(self.proxy)

        self.add = QPushButton("开始下载")
        self.add.setEnabled(False)
        self.middle.addWidget(self.add)

        self.stop_me = QPushButton("停止下载")
        self.stop_me.setEnabled(False)
        self.middle.addWidget(self.stop_me)

        self.log_area = QPlainTextEdit()
        self.log_area.setReadOnly(True)
        self.log_area.setMaximumBlockCount(1000)
        self.middle.addWidget(self.log_area)

        #self.table_view.setSizePolicy(size)
        #self.layout.addWidget(self.table)
        self.layout = QVBoxLayout()
        self.layout.addLayout(self.top)
        self.layout.addLayout(self.middle)
        self.setLayout(self.layout)

        self.radioButtonMov.toggled.connect(self.choose_movie_widgets)
        self.radioButtonCinema.toggled.connect(self.choose_cinema_widgets)
        self.url.textChanged[str].connect(self.check_disable_download)
        self.browseFolder.clicked.connect(self.add_folder)
        self.folder_or_filename.textChanged[str].connect(
            self.check_disable_download)
        self.add.clicked.connect(self.start_download)
        self.stop_me.clicked.connect(self.stop_download)

        self.radioButtonMov.setChecked(
            True)  #set default only after .connect above

        # TESTING PURPOSE
        '''
        self.radioButtonMov.setChecked(False)
        self.url.setText('https://www.duboku.net/voddetail-969.html')
        self.browse_folder_value = 'C:/Users/Administrator/Documents/duboku'
        self.folder_or_filename.setText('初恋')
        '''

        #set current process (not queue that one) log handler:
        logger = logging.getLogger(__name__)
        handler2 = LoggerWriter()
        logger.addHandler(handler2)
        logger.setLevel(logging.INFO)  #DEBUG
        handler2.emitter.sigLog.connect(self.log_area.appendPlainText)
        sys.stdout = handler2  #LoggerWriter()
コード例 #44
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)
コード例 #45
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)
コード例 #46
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])
コード例 #47
-1
ファイル: Sherlock.py プロジェクト: bakhyeonjae/Sherlock
    def __init__(self, argv, parentQWidget = None):
        QWidget.__init__(self)

        const.mode_interactive = 1
        const.mode_file = 2
        const.mode_batch = 3
        const.mode_default = const.mode_batch

        arg_file = ''
        if '-i' in argv:
            mode = const.mode_interactive
        elif '-b' in argv:
            mode = const.mode_batch
        elif '-f' in argv:
            mode = const.mode_file
            idx = argv.index('-f')
            arg_file = argv[idx+1]

        src_path = None
        if '-s' in argv:
            idx = argv.index('-s')
            src_path = argv[idx+1]

        if '-c' in argv:
            idx = argv.index('-c')
            cfg_file = argv[idx+1]

        hbox = QHBoxLayout()
        vbox = QVBoxLayout()
        scrollView = ScrollArea()
        headerView = Header.Header(self)
        scrollView.connectHeaderView(headerView)
        headerView.connectMainView(scrollView.mainView.drawer)
        vbox.addWidget(headerView)
        vbox.addWidget(scrollView)

        toolBox = ToolBox.ToolBox(mode)

        hbox.addLayout(vbox)
        hbox.addLayout(toolBox)

        self.controller = Kitchen.Kitchen(mode,arg_file,cfg_file)
        self.controller.connectView(scrollView.mainView.drawer)
        self.controller.connectToolBox(toolBox)
        self.controller.start()

        srcViewer = SourceViewer.SourceViewer()
        srcViewer.createIndex(src_path)

        toolBox.connectMsgRcv(headerView)
        toolBox.connectMsgRcv(scrollView.mainView.drawer)
        toolBox.connectMsgRcv(self.controller)
        toolBox.connectDiagramView(scrollView.mainView.drawer)

        scrollView.mainView.drawer.setToolBox(toolBox)
        scrollView.mainView.drawer.connectSourceViewer(srcViewer)

        self.setLayout(hbox)