Beispiel #1
0
 def create_widgets(self, parent):
     
     h_layout = QHBoxLayout()
     self.viewer_cbox = self.builder.checkable_combobox(parent, [], self._set_cb_changed)
     self.information_cbox = self.builder.checkable_combobox(parent, [], self._set_information_changed)
     self.information_cbox.setFixedWidth(150)
     cnt = 0
     for info in self._information_box_items:
         self.information_cbox.addItem(info)        
         new_row = self.information_cbox.count() - 1
         item = self.information_cbox.model().item(new_row, 0)
         if self._information_checked[info]:
             item.setCheckState(QtCore.Qt.Checked)
         else:
             item.setCheckState(QtCore.Qt.Unchecked)
         self._info_widget_index[cnt] = info
         cnt += 1
     
     h_layout.addWidget(self.viewer_cbox)
     h_layout.addItem(QSpacerItem(10, 10))
     h_layout.addWidget(self.information_cbox)
     
     # add ecu selection
     self.label_top = QtGui.QLabel()
     self.label_top.setText("Message View")
     self.viewDock = dockarea.Dock('view', size=(1000, 600))
     self.layout.addWidget(self.label_top)
     self.label_top.setFixedHeight(20)
     self.layout.addLayout(h_layout)        
     self.layout.addItem(QSpacerItem(10, 10))
Beispiel #2
0
class EditPane(QWidget):
    def __init__(self, model):
        QWidget.__init__(self)
        self._setupUi()
        self.model = model
        self.model.view = self
        
        self.normalButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Normal))
        self.titleButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Title))
        self.footnoteButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Footnote))
        self.ignoreButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Ignored))
        self.tofixButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.ToFix))
        self.hideIgnoredCheckBox.stateChanged.connect(self.hideIgnoredCheckBoxStateChanged)
        self.textEdit.textChanged.connect(self.textEditTextChanged)
        self.saveEditsButton.clicked.connect(self.model.save_edits)
        self.cancelEditsButton.clicked.connect(self.model.cancel_edits)
        
    def _setupUi(self):
        self.mainLayout = QVBoxLayout(self)
        self.buttonLayout = QGridLayout()
        self.normalButton = QPushButton("Normal")
        self.buttonLayout.addWidget(self.normalButton, 0, 0)
        self.titleButton = QPushButton("Title")
        self.buttonLayout.addWidget(self.titleButton, 1, 0)
        self.footnoteButton = QPushButton("Footnote")
        self.buttonLayout.addWidget(self.footnoteButton, 2, 0)
        self.ignoreButton = QPushButton("Ignore")
        self.buttonLayout.addWidget(self.ignoreButton, 0, 1)
        self.tofixButton = QPushButton("To Fix")
        self.buttonLayout.addWidget(self.tofixButton, 1, 1)
        self.mainLayout.addLayout(self.buttonLayout)
        
        self.rightLayout = QVBoxLayout()
        self.hideIgnoredCheckBox = QCheckBox("Hide Ignored Elements")
        self.rightLayout.addWidget(self.hideIgnoredCheckBox)
        self.textEdit = QTextEdit()
        self.textEdit.setAcceptRichText(False)
        self.rightLayout.addWidget(self.textEdit)
        self.editButtonLayout = QHBoxLayout()
        self.editButtonLayout.addItem(horizontalSpacer())
        self.saveEditsButton = QPushButton("Save")
        self.editButtonLayout.addWidget(self.saveEditsButton)
        self.cancelEditsButton = QPushButton("Cancel")
        self.editButtonLayout.addWidget(self.cancelEditsButton)
        self.rightLayout.addLayout(self.editButtonLayout)
        self.mainLayout.addLayout(self.rightLayout)
        
    #--- Signals
    def hideIgnoredCheckBoxStateChanged(self, state):
        self.model.app.hide_ignored = state == Qt.Checked
    
    def textEditTextChanged(self):
        self.model.edit_text = self.textEdit.toPlainText()
    
    #--- model -> view
    def refresh_edit_text(self):
        self.textEdit.setText(self.model.edit_text)
        self.textEdit.setEnabled(self.model.edit_enabled)
        self.saveEditsButton.setEnabled(self.model.edit_enabled)
        self.cancelEditsButton.setEnabled(self.model.edit_enabled)
Beispiel #3
0
class choixSonSortieWidget(QGroupBox) :
    """Class pour faire le widget standard de sélection du format de sortie son + réglages experts"""
    def __init__(self, soxSuppFormat, parent=None) :
      super(choixSonSortieWidget, self).__init__(parent)
      self.setObjectName("groupBox")
      self.horizontalLayout = QHBoxLayout(self)
      self.horizontalLayout.setObjectName("horizontalLayout")
      self.label = QLabel(self)
      self.label.setObjectName("label")
      self.horizontalLayout.addWidget(self.label)
      self.formatSound = QComboBox(self)
      for x in soxSuppFormat :
        self.formatSound.addItem(QString(x))
      self.formatSound.setObjectName("formatSound")
      self.horizontalLayout.addWidget(self.formatSound)
      spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
      self.horizontalLayout.addItem(spacerItem)
      self.reglageExp = reglageExpert(soxSuppFormat, self.formatSound)
      self.horizontalLayout.addWidget(self.reglageExp)
      self.setTitle(_(u"Réglage du format de sortie"))
      self.label.setText(_(u"Format du fichier de sortie :"))
      self.formatSound.setToolTip(_(u"Format du fichier son de sortie"))

    def getFileExt(self) :
      return unicode(self.formatSound.currentText())
Beispiel #4
0
    def layout_widgets(self):

        vLayout1 = QVBoxLayout()
        vLayout1.addWidget(self.label1)
        vLayout1.addWidget(self.listWidget1)

        vLayout2 = QVBoxLayout()
        vLayout2.addWidget(self.button1)
        vLayout2.addWidget(self.button2)

        vLayout3 = QVBoxLayout()
        vLayout3.addWidget(self.label2)
        vLayout3.addWidget(self.listWidget2)

        hLayout1 = QHBoxLayout()
        hLayout1.addLayout(vLayout1)
        hLayout1.addLayout(vLayout2)
        hLayout1.addLayout(vLayout3)

        hButtonLayout = QHBoxLayout()
        hButtonLayout.addItem(self.spacer)
        hButtonLayout.addWidget(self.buttonBox)

        hFinalLayout = QGridLayout()
        hFinalLayout.addLayout(hLayout1, 0, 0)
        hFinalLayout.addLayout(hButtonLayout, 1, 0)

        self.setLayout(hFinalLayout)
 def setup_ui(self):
     self.openDir = QPushButton("下载目录")
     self.openDir.setFocusPolicy(Qt.NoFocus)
     self.openDir.setIcon(QIcon(":/iconSources/icons/openDir.png"))
     self.netSpeedInfo = QLabel("当前网速:0.0 kB/s")
     self.netSpeedInfo.setAlignment(Qt.AlignRight and Qt.AlignVCenter)
     self.downloadModel = DownloadModel()
     self.downloadModel.initial_model()
     self.downloadTable = DownloadTable()
     self.downloadTable.initial_view(self.downloadModel)
     self.downloadTable.selectRow(0)
     self.myDelegate = MyDelegate()
     self.downloadTable.setItemDelegate(self.myDelegate)
     
     spacerItem  =  QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
     firstLayout = QHBoxLayout()
     firstLayout.addWidget(self.openDir)
     firstLayout.addItem(spacerItem)
     firstLayout.addWidget(self.netSpeedInfo)
     
     mainLayout = QVBoxLayout(self)
     mainLayout.setMargin(2)
     mainLayout.setSpacing(1)
     mainLayout.addWidget(self.downloadTable)
     mainLayout.addLayout(firstLayout)
    def __init__(self, vm, parent = None):
        super (VmInfoWidget, self).__init__(parent)
        self.vm = vm
        layout = QHBoxLayout ()

        self.on_icon = VmStatusIcon(vm)
        self.upd_info = VmUpdateInfoWidget(vm, show_text=False)
        self.error_icon = VmIconWidget(":/warning.png")
        self.blk_icon = VmIconWidget(":/mount.png")
        self.rec_icon = VmIconWidget(":/mic.png")

        layout.addWidget(self.on_icon)
        layout.addWidget(self.upd_info)
        layout.addWidget(self.error_icon)
        layout.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))
        layout.addWidget(self.blk_icon)
        layout.addWidget(self.rec_icon)

        layout.setContentsMargins(5,0,5,0)
        self.setLayout(layout)

        self.rec_icon.setVisible(False)
        self.blk_icon.setVisible(False)
        self.error_icon.setVisible(False)

        self.tableItem = self.VmInfoItem(self.upd_info.tableItem, vm)
Beispiel #7
0
    def showImageTab(self):

        items = ['Use Imageinfo', 'VistaSP0x64', 'VistaSP0x86', 'VistaSP1x64', 'VistaSP2x64', \
                 'VistaSP2x86', 'Win2003SP0x86', 'Win2003SP1x64', 'Win2003SP1x86', 'Win2003SP2x64', \
                 'Win2003SP2x86', 'Win2008R2SP0x64', 'Win2008R2SP1x64', 'Win2008SP1x64', 'Win2008SP1x86', \
                 'Win2008SP2x64', 'Win7SP0x64', 'Win7SP0x86', 'Win7SP1x64', 'Win7SP1x86', 'WinXPSP1x64', \
                 'WinXPSP2x64', 'WinXPSP2x86', 'WinXPSP3x86']

        fileNameLabel = QLabel("Image: ")
        profileLabel = QLabel("Profile: ")
        fileName = QLabel(self.filename)
        self.profileSelector = QComboBox()
        self.profileSelector.addItems(items)

        #
        index = items.index(self.profile)

        self.profileSelector.setCurrentIndex(index)
        horizontalLayout = QHBoxLayout()
        grid = QGridLayout()
        grid.addWidget(fileNameLabel, 1, 0)
        grid.addWidget(fileName, 1, 1)
        grid.addWidget(profileLabel, 2, 0)
        grid.addWidget(self.profileSelector, 2, 1)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        grid.addItem(spacerItem)
        horizontalLayout.addItem(grid)
        horizontalLayout.addStretch()

        self.connect(self.profileSelector, SIGNAL("currentIndexChanged(QString)"), self.storeProfile)
        self.addTabFnc("Image", horizontalLayout)
        self.dirty = True
 def __init__(self, parent = None):
     super(SettingFrame, self).__init__(parent)
     self.setMinimumSize(370, 110)
     label = QLabel("歌曲下载到:")
     with open(Configures.settingFile,  'r') as f:
         self.oldDir = f.read()
     self.lineEdit = QLineEdit("%s"%self.oldDir)
     self.setWindowTitle("当前设置:"+self.oldDir)
     self.openDir = QToolButton(clicked = self.select_dir)
     self.openDir.setText('...')
     self.defaultButton = QPushButton("默认值", clicked = self.default)
     self.okButton = QPushButton("确定", clicked = self.confirm)
     self.cancelButton = QPushButton("取消", clicked = self.cancel)
     
     inputLayout = QHBoxLayout()
     inputLayout.addWidget(self.lineEdit)
     inputLayout.addWidget(self.openDir)
     
     buttonsLayout = QHBoxLayout()
     spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
     buttonsLayout.addItem(spacerItem)
     buttonsLayout.addWidget(self.defaultButton)
     buttonsLayout.addWidget(self.cancelButton)
     buttonsLayout.addWidget(self.okButton)
     buttonsLayout.addItem(spacerItem)
     
     mainLayout = QVBoxLayout(self)
     mainLayout.addWidget(label)
     mainLayout.addLayout(inputLayout)
     mainLayout.addLayout(buttonsLayout)
Beispiel #9
0
    def __init__(self, vm, parent=None):
        super(VmInfoWidget, self).__init__(parent)
        self.vm = vm
        layout = QHBoxLayout()

        self.on_icon = VmStatusIcon(vm)
        self.upd_info = VmUpdateInfoWidget(vm, show_text=False)
        self.error_icon = VmIconWidget(":/warning.png")
        self.blk_icon = VmIconWidget(":/mount.png")
        self.rec_icon = VmIconWidget(":/mic.png")

        layout.addWidget(self.on_icon)
        layout.addWidget(self.upd_info)
        layout.addWidget(self.error_icon)
        layout.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding,
                        QtGui.QSizePolicy.Expanding))
        layout.addWidget(self.blk_icon)
        layout.addWidget(self.rec_icon)

        layout.setContentsMargins(5, 0, 5, 0)
        self.setLayout(layout)

        self.rec_icon.setVisible(False)
        self.blk_icon.setVisible(False)
        self.error_icon.setVisible(False)

        self.tableItem = self.VmInfoItem(self.upd_info.tableItem, vm)
 def setup_ui(self):
     self.searchTable = SearchTable()
     self.searchBox = SearchBox()      
     
     self.previousPageButton = QToolButton()
     self.previousPageButton.setFixedSize(40, 31)
     icon0  =  QIcon(":/iconSources/icons/previousPage.png")
     self.previousPageButton.setIcon(icon0)
     self.previousPageButton.setIconSize(QSize(25, 25))
     self.previousPageButton.setCursor(QCursor(Qt.PointingHandCursor))
     self.previousPageButton.setToolTip('上一页')
     
     self.nextPageButton = QToolButton()
     self.nextPageButton.setFixedSize(40, 31)
     icon1  =  QIcon(":/iconSources/icons/nextPage.png")
     self.nextPageButton.setIcon(icon1)
     self.nextPageButton.setIconSize(QSize(25, 25))
     self.nextPageButton.setCursor(QCursor(Qt.PointingHandCursor))
     self.nextPageButton.setToolTip('下一页')
     
     self.jumpNum = QLineEdit('0')
     self.jumpNum.setFixedWidth(39)
     self.jumpNum.setAlignment(Qt.AlignRight)
     
     self.pageNum = QLabel("/ 0")
     self.pageNum.setFixedHeight(35)
     self.pageNum.setFixedWidth(35)
     self.pageNum.setAlignment(Qt.AlignCenter )
     self.pageNum.setToolTip('当前页码/总页数')
     
     self.controlWidget = QWidget()
     controlLayout = QHBoxLayout(self.controlWidget)
     controlLayout.setMargin(0)
     controlLayout.setSpacing(4)
     spacerItem  =  QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
     controlLayout.addItem(spacerItem)
     controlLayout.addWidget(self.previousPageButton)
     controlLayout.addWidget(self.jumpNum)
     controlLayout.addWidget(self.pageNum)
     controlLayout.addWidget(self.nextPageButton)
     controlLayout.addItem(spacerItem)
     
     self.controlSearch = QWidget()       
     controlSearchLayout = QVBoxLayout(self.controlSearch)
     controlSearchLayout.setMargin(0)
     controlSearchLayout.setSpacing(2)
     controlSearchLayout.addWidget(self.searchTable)
     controlSearchLayout.addWidget(self.controlWidget)
     
     mainLayout = QVBoxLayout(self)
     mainLayout.setMargin(2)
     mainLayout.setSpacing(2)
     mainLayout.addWidget(self.searchBox)
     mainLayout.addWidget(self.controlSearch)
             
     self.searchByType = 'all'
     self.searchBox.searchComboBox.setCurrentIndex(0)
Beispiel #11
0
class ErrorReportDialog(QDialog):
    def __init__(self, parent, github_url, error):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self._setupUi()
        name = QCoreApplication.applicationName()
        version = QCoreApplication.applicationVersion()
        errorText = "Application Name: {0}\nVersion: {1}\n\n{2}".format(
            name, version, error)
        # Under windows, we end up with an error report without linesep if we don't mangle it
        errorText = errorText.replace('\n', os.linesep)
        self.errorTextEdit.setPlainText(errorText)
        self.github_url = github_url

        self.sendButton.clicked.connect(self.goToGithub)
        self.dontSendButton.clicked.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Error Report"))
        self.resize(553, 349)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.label.setText(
            tr("Something went wrong. How about reporting the error?"))
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.errorTextEdit = QPlainTextEdit(self)
        self.errorTextEdit.setReadOnly(True)
        self.verticalLayout.addWidget(self.errorTextEdit)
        msg = tr(
            "Error reports should be reported as Github issues. You can copy the error traceback "
            "above and paste it in a new issue (bonus point if you run a search to make sure the "
            "issue doesn't already exist). What usually really helps is if you add a description "
            "of how you got the error. Thanks!"
            "\n\n"
            "Although the application should continue to run after this error, it may be in an "
            "unstable state, so it is recommended that you restart the application."
        )
        self.label2 = QLabel(msg)
        self.label2.setWordWrap(True)
        self.verticalLayout.addWidget(self.label2)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.addItem(horizontalSpacer())
        self.dontSendButton = QPushButton(self)
        self.dontSendButton.setText(tr("Close"))
        self.dontSendButton.setMinimumSize(QSize(110, 0))
        self.horizontalLayout.addWidget(self.dontSendButton)
        self.sendButton = QPushButton(self)
        self.sendButton.setText(tr("Go to Github"))
        self.sendButton.setMinimumSize(QSize(110, 0))
        self.sendButton.setDefault(True)
        self.horizontalLayout.addWidget(self.sendButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

    def goToGithub(self):
        open_url(self.github_url)
class ErrorReportDialog(QDialog):
    def __init__(self, parent, error):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self._setupUi()
        name = QCoreApplication.applicationName()
        version = QCoreApplication.applicationVersion()
        errorText = "Application Name: {0}\nVersion: {1}\n\n{2}".format(
            name, version, error)
        # Under windows, we end up with an error report without linesep if we don't mangle it
        errorText = errorText.replace('\n', os.linesep)
        self.errorTextEdit.setPlainText(errorText)

        self.sendButton.clicked.connect(self.accept)
        self.dontSendButton.clicked.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Error Report"))
        self.resize(553, 349)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.label.setText(
            tr("Something went wrong. Would you like to send the error report to Hardcoded Software?"
               ))
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.errorTextEdit = QPlainTextEdit(self)
        self.errorTextEdit.setReadOnly(True)
        self.verticalLayout.addWidget(self.errorTextEdit)
        msg = tr(
            "Although the application should continue to run after this error, it may be in an "
            "instable state, so it is recommended that you restart the application."
        )
        self.label2 = QLabel(msg)
        self.label2.setWordWrap(True)
        self.verticalLayout.addWidget(self.label2)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.addItem(horizontalSpacer())
        self.dontSendButton = QPushButton(self)
        self.dontSendButton.setText(tr("Don\'t Send"))
        self.dontSendButton.setMinimumSize(QSize(110, 0))
        self.horizontalLayout.addWidget(self.dontSendButton)
        self.sendButton = QPushButton(self)
        self.sendButton.setText(tr("Send"))
        self.sendButton.setMinimumSize(QSize(110, 0))
        self.sendButton.setDefault(True)
        self.horizontalLayout.addWidget(self.sendButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

    def accept(self):
        text = self.errorTextEdit.toPlainText()
        url = QUrl(
            "mailto:[email protected]?SUBJECT=Error Report&BODY=%s" % text)
        QDesktopServices.openUrl(url)
        QDialog.accept(self)
class ErrorReportDialog(QDialog):
    def __init__(self, parent, github_url, error):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self._setupUi()
        name = QCoreApplication.applicationName()
        version = QCoreApplication.applicationVersion()
        errorText = "Application Name: {0}\nVersion: {1}\n\n{2}".format(name, version, error)
        # Under windows, we end up with an error report without linesep if we don't mangle it
        errorText = errorText.replace('\n', os.linesep)
        self.errorTextEdit.setPlainText(errorText)
        self.github_url = github_url

        self.sendButton.clicked.connect(self.goToGithub)
        self.dontSendButton.clicked.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Error Report"))
        self.resize(553, 349)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.label.setText(tr("Something went wrong. How about reporting the error?"))
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.errorTextEdit = QPlainTextEdit(self)
        self.errorTextEdit.setReadOnly(True)
        self.verticalLayout.addWidget(self.errorTextEdit)
        msg = tr(
            "Error reports should be reported as Github issues. You can copy the error traceback "
            "above and paste it in a new issue (bonus point if you run a search to make sure the "
            "issue doesn't already exist). What usually really helps is if you add a description "
            "of how you got the error. Thanks!"
            "\n\n"
            "Although the application should continue to run after this error, it may be in an "
            "unstable state, so it is recommended that you restart the application."
        )
        self.label2 = QLabel(msg)
        self.label2.setWordWrap(True)
        self.verticalLayout.addWidget(self.label2)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.addItem(horizontalSpacer())
        self.dontSendButton = QPushButton(self)
        self.dontSendButton.setText(tr("Close"))
        self.dontSendButton.setMinimumSize(QSize(110, 0))
        self.horizontalLayout.addWidget(self.dontSendButton)
        self.sendButton = QPushButton(self)
        self.sendButton.setText(tr("Go to Github"))
        self.sendButton.setMinimumSize(QSize(110, 0))
        self.sendButton.setDefault(True)
        self.horizontalLayout.addWidget(self.sendButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

    def goToGithub(self):
        open_url(self.github_url)
    def __init__(self, parent=None):
        super(ExploreDataWidget, self).__init__(parent)
        self.setStyleSheet(OfSs.dock_style)
        # Create geometry
        self.setObjectName("ExploreData")
        self.setWindowTitle("ExploreData")
        self.dockWidgetContents = QWidget()

        self.data_label = QLabel("Data", self.dockWidgetContents)

        self.add_btn = QPushButton(u"Ajouter variable",
                                   self.dockWidgetContents)
        self.remove_btn = QPushButton(u"Retirer variable",
                                      self.dockWidgetContents)
        self.datatables_choices = []
        self.datatable_combo = MyComboBox(self.dockWidgetContents,
                                          u'Choix de la table',
                                          self.datatables_choices)

        #        self.add_btn.setDisabled(True)
        #        self.remove_btn.setDisabled(True)

        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)

        horizontalLayout = QHBoxLayout()
        horizontalLayout.addWidget(self.add_btn)
        horizontalLayout.addWidget(self.remove_btn)
        horizontalLayout.addWidget(self.datatable_combo)
        horizontalLayout.addItem(spacerItem)
        self.view = DataFrameViewWidget(self.dockWidgetContents)

        verticalLayout = QVBoxLayout(self.dockWidgetContents)
        verticalLayout.addWidget(self.data_label)

        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.view)
        self.setWidget(self.dockWidgetContents)

        # Initialize attributes
        self.parent = parent

        self.selected_vars = set()
        self.data = DataFrame()
        self.view_data = None
        self.dataframes = {}
        self.vars = set()

        self.connect(self.add_btn, SIGNAL('clicked()'), self.add_var)
        self.connect(self.remove_btn, SIGNAL('clicked()'), self.remove_var)
        self.connect(self.datatable_combo.box,
                     SIGNAL('currentIndexChanged(int)'), self.select_data)

        self.update_btns()
Beispiel #15
0
    def __init__(self, parent=None, code=''):
        super(CodePastingDialog, self).__init__(parent)
        self.setWindowTitle(self.tr("Enviar a Pastebin"))
        self.setMinimumSize(700, 500)
        self._parent = parent
        container = QVBoxLayout(self)

        # Thread
        self.thread = code_pasting.Thread()
        self.connect(self.thread, SIGNAL("finished()"),
                     self._paste_result)
        # Campos
        fields_box = QGridLayout()
        fields_box.addWidget(QLabel(self.tr("Expirar después de:")), 0, 0)
        self._spin_expire = QSpinBox()
        self._spin_expire.setSuffix(self.tr(" Días"))
        self._spin_expire.setMinimum(1)
        fields_box.addWidget(self._spin_expire, 0, 1)
        fields_box.addWidget(QLabel(self.tr("Acceso:")), 1, 0)
        self._combo_access = QComboBox()
        self._combo_access.addItems([self.tr("Público"), self.tr("Privado")])
        fields_box.addWidget(self._combo_access, 1, 1)
        fields_box.addWidget(QLabel(self.tr("Nombre:")), 2, 0)
        self._line_filename = QLineEdit()
        place_holder_text = parent.get_active_editor().filename
        self._line_filename.setPlaceholderText(place_holder_text)
        fields_box.addWidget(self._line_filename, 2, 1)
        fields_box.addWidget(QLabel(self.tr("Descripción:")), 3, 0)

        # Editor
        self._code_editor = QPlainTextEdit()
        self._set_editor_style(self._code_editor)
        self._code_editor.setPlainText(code)

        hbox = QHBoxLayout()
        hbox.addItem(QSpacerItem(0, 1, QSizePolicy.Expanding))
        btn_paste = QPushButton(self.tr("Enviar"))
        hbox.addWidget(btn_paste)
        btn_cancel = QPushButton(self.tr("Cancelar"))
        hbox.addWidget(btn_cancel)

        container.addLayout(fields_box)
        container.addWidget(self._code_editor)
        container.addLayout(hbox)

        # Loading widget
        self.loading_widget = loading_widget.LoadingWidget(self)
        self.loading_widget.hide()

        # Conexiones
        self.connect(btn_cancel, SIGNAL("clicked()"), self.close)
        self.connect(btn_paste, SIGNAL("clicked()"), self._emit_data)
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Nueva Relación"))
        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        self._line_relation_name = QLineEdit()
        hbox.addWidget(QLabel(self.tr("Nombre:")))
        hbox.addWidget(self._line_relation_name)
        vbox.addLayout(hbox)

        vbox.addWidget(QLabel(
            self.tr("La primera fila corresponde a los campos")))

        hbox = QHBoxLayout()
        btn_add_column = QPushButton(self.tr("Agregar Columna"))
        hbox.addWidget(btn_add_column)
        btn_add_tuple = QPushButton(self.tr("Agregar Tupla"))
        hbox.addWidget(btn_add_tuple)
        btn_remove_column = QPushButton(self.tr("Eliminar Columna"))
        hbox.addWidget(btn_remove_column)
        btn_remove_tuple = QPushButton(self.tr("Eliminar Tupla"))
        hbox.addWidget(btn_remove_tuple)
        vbox.addLayout(hbox)

        self._table = QTableWidget()
        vbox.addWidget(self._table)
        self._table.setRowCount(1)
        self._table.setColumnCount(2)
        self._table.setItem(0, 0, QTableWidgetItem("Campo 1"))
        self._table.setItem(0, 1, QTableWidgetItem("Campo 2"))

        hbox = QHBoxLayout()
        hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        btn_ok = QPushButton(self.tr("Aceptar"))
        hbox.addWidget(btn_ok)
        btn_cancel = QPushButton(self.tr("Cancelar"))
        hbox.addWidget(btn_cancel)
        vbox.addLayout(hbox)

        # Connections
        self.connect(btn_add_column, SIGNAL("clicked()"),
            self.__add_column)
        self.connect(btn_remove_column, SIGNAL("clicked()"),
            self.__remove_column)
        self.connect(btn_add_tuple, SIGNAL("clicked()"),
            self.__add_tuple)
        self.connect(btn_remove_tuple, SIGNAL("clicked()"),
            self.__remove_tuple)
        self.connect(btn_ok, SIGNAL("clicked()"),
            self.__create_table)
        self.connect(btn_cancel, SIGNAL("clicked()"),
            self.close)
Beispiel #17
0
def horizontalWrap(widgets):
    """Wrap all widgets in `widgets` in a horizontal layout.
    
    If, instead of placing a widget in your list, you place an int or None, an horizontal spacer
    with the width corresponding to the int will be placed (0 or None means an expanding spacer).
    """
    layout = QHBoxLayout()
    for widget in widgets:
        if widget is None or isinstance(widget, int):
            layout.addItem(horizontalSpacer(size=widget))
        else:
            layout.addWidget(widget)
    return layout
Beispiel #18
0
    def createConnSection(self, page_layout, label, combobox, num_column):
        conn_layout = QHBoxLayout()
        conn_layout.setSpacing(5)
        conn_layout.setContentsMargins(0, 0, 0, 0)
        conn_layout.addWidget(label)
        conn_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Fixed, QSizePolicy.Minimum))
        conn_layout.addWidget(combobox, 1)

        page_layout.addLayout(conn_layout, page_layout.rowCount(), 0, 1, num_column)
        page_layout.addWidget(self.createLine(), page_layout.rowCount(), 0, 1, num_column)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, page_layout.rowCount(), 0, 1, num_column)
Beispiel #19
0
 def _loadLogoWidget(self):
     """
     load logo widget
     """
     logoLayout = QHBoxLayout()
     self.imageLabel = QLabel()
     self.imageLabel.setPixmap(getpixmap("ui/images/Rosetta.png"))
     # Horizontal spacer
     hSpacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum)
     logoLayout.addItem(hSpacer)
     logoLayout.addWidget(self.imageLabel)
     logoLayout.addItem(hSpacer)
     return logoLayout
Beispiel #20
0
def h_centered(layout, item):
    l_spacer = QSpacerItem(0, 0)
    r_spacer = QSpacerItem(0, 0)
    proxy = QHBoxLayout()
    proxy.setSpacing(0)
    proxy.setMargin(0)
    proxy.addItem(l_spacer)
    if isinstance(item, QLayout):
        proxy.addLayout(item)
    else:
        proxy.addWidget(item)
    proxy.addItem(r_spacer)
    layout.addLayout(proxy)
Beispiel #21
0
def horizontalWrap(widgets):
    """Wrap all widgets in `widgets` in a horizontal layout.
    
    If, instead of placing a widget in your list, you place an int or None, an horizontal spacer
    with the width corresponding to the int will be placed (0 or None means an expanding spacer).
    """
    layout = QHBoxLayout()
    for widget in widgets:
        if widget is None or isinstance(widget, int):
            layout.addItem(horizontalSpacer(size=widget))
        else:
            layout.addWidget(widget)
    return layout
    def __init__(self, parent=None, code=''):
        super(CodePastingDialog, self).__init__(parent)
        self.setWindowTitle(self.tr("Enviar a Pastebin"))
        self.setMinimumSize(700, 500)
        self._parent = parent
        container = QVBoxLayout(self)

        # Thread
        self.thread = code_pasting.Thread()
        self.connect(self.thread, SIGNAL("finished()"), self._paste_result)
        # Campos
        fields_box = QGridLayout()
        fields_box.addWidget(QLabel(self.tr("Expirar después de:")), 0, 0)
        self._spin_expire = QSpinBox()
        self._spin_expire.setSuffix(self.tr(" Días"))
        self._spin_expire.setMinimum(1)
        fields_box.addWidget(self._spin_expire, 0, 1)
        fields_box.addWidget(QLabel(self.tr("Acceso:")), 1, 0)
        self._combo_access = QComboBox()
        self._combo_access.addItems([self.tr("Público"), self.tr("Privado")])
        fields_box.addWidget(self._combo_access, 1, 1)
        fields_box.addWidget(QLabel(self.tr("Nombre:")), 2, 0)
        self._line_filename = QLineEdit()
        place_holder_text = parent.get_active_editor().filename
        self._line_filename.setPlaceholderText(place_holder_text)
        fields_box.addWidget(self._line_filename, 2, 1)
        fields_box.addWidget(QLabel(self.tr("Descripción:")), 3, 0)

        # Editor
        self._code_editor = QPlainTextEdit()
        self._set_editor_style(self._code_editor)
        self._code_editor.setPlainText(code)

        hbox = QHBoxLayout()
        hbox.addItem(QSpacerItem(0, 1, QSizePolicy.Expanding))
        btn_paste = QPushButton(self.tr("Enviar"))
        hbox.addWidget(btn_paste)
        btn_cancel = QPushButton(self.tr("Cancelar"))
        hbox.addWidget(btn_cancel)

        container.addLayout(fields_box)
        container.addWidget(self._code_editor)
        container.addLayout(hbox)

        # Loading widget
        self.loading_widget = loading_widget.LoadingWidget(self)
        self.loading_widget.hide()

        # Conexiones
        self.connect(btn_cancel, SIGNAL("clicked()"), self.close)
        self.connect(btn_paste, SIGNAL("clicked()"), self._emit_data)
Beispiel #23
0
    def __init__(self, parent = None):
        super(ExploreDataWidget, self).__init__(parent)
        self.setStyleSheet(OfSs.dock_style)
        # Create geometry
        self.setObjectName("ExploreData")
        self.setWindowTitle("ExploreData")
        self.dockWidgetContents = QWidget()


        self.data_label = QLabel("Data", self.dockWidgetContents)

        self.add_btn = QPushButton(u"Ajouter variable",self.dockWidgetContents)
        self.remove_btn = QPushButton(u"Retirer variable",self.dockWidgetContents)
        self.datatables_choices = []
        self.datatable_combo = MyComboBox(self.dockWidgetContents, u'Choix de la table', self.datatables_choices)

#        self.add_btn.setDisabled(True)
#        self.remove_btn.setDisabled(True)

        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

        horizontalLayout = QHBoxLayout()
        horizontalLayout.addWidget(self.add_btn)
        horizontalLayout.addWidget(self.remove_btn)
        horizontalLayout.addWidget(self.datatable_combo)
        horizontalLayout.addItem(spacerItem)
        self.view = DataFrameViewWidget(self.dockWidgetContents)

        verticalLayout = QVBoxLayout(self.dockWidgetContents)
        verticalLayout.addWidget(self.data_label)

        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.view)
        self.setWidget(self.dockWidgetContents)

        # Initialize attributes
        self.parent = parent

        self.selected_vars = set()
        self.data = DataFrame()
        self.view_data = None
        self.dataframes = {}
        self.vars = set()

        self.connect(self.add_btn, SIGNAL('clicked()'), self.add_var)
        self.connect(self.remove_btn, SIGNAL('clicked()'), self.remove_var)
        self.connect(self.datatable_combo.box, SIGNAL('currentIndexChanged(int)'), self.select_data)

        self.update_btns()
class ErrorReportDialog(QDialog):
    def __init__(self, parent, error):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self._setupUi()
        name = QCoreApplication.applicationName()
        version = QCoreApplication.applicationVersion()
        errorText = "Application Name: {0}\nVersion: {1}\n\n{2}".format(name, version, error)
        # Under windows, we end up with an error report without linesep if we don't mangle it
        errorText = errorText.replace('\n', os.linesep)
        self.errorTextEdit.setPlainText(errorText)
        
        self.sendButton.clicked.connect(self.accept)
        self.dontSendButton.clicked.connect(self.reject)
    
    def _setupUi(self):
        self.setWindowTitle(tr("Error Report"))
        self.resize(553, 349)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.label.setText(tr("Something went wrong. Would you like to send the error report to Hardcoded Software?"))
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.errorTextEdit = QPlainTextEdit(self)
        self.errorTextEdit.setReadOnly(True)
        self.verticalLayout.addWidget(self.errorTextEdit)
        msg = tr("Although the application should continue to run after this error, it may be in an "
            "instable state, so it is recommended that you restart the application.")
        self.label2 = QLabel(msg)
        self.label2.setWordWrap(True)
        self.verticalLayout.addWidget(self.label2)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.addItem(horizontalSpacer())
        self.dontSendButton = QPushButton(self)
        self.dontSendButton.setText(tr("Don\'t Send"))
        self.dontSendButton.setMinimumSize(QSize(110, 0))
        self.horizontalLayout.addWidget(self.dontSendButton)
        self.sendButton = QPushButton(self)
        self.sendButton.setText(tr("Send"))
        self.sendButton.setMinimumSize(QSize(110, 0))
        self.sendButton.setDefault(True)
        self.horizontalLayout.addWidget(self.sendButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
    
    def accept(self):
        text = self.errorTextEdit.toPlainText()
        url = QUrl("mailto:[email protected]?SUBJECT=Error Report&BODY=%s" % text)
        QDesktopServices.openUrl(url)
        QDialog.accept(self)
Beispiel #25
0
    def create_widgets(self, parent):
        h_layout = QHBoxLayout()
        self.viewer_cbox = self.builder.checkable_combobox(parent, [], self._set_cb_changed)

        h_layout.addWidget(self.viewer_cbox)
        h_layout.addItem(QSpacerItem(10, 10))
        
        # add ecu selection
        self.label_top = QtGui.QLabel()
        self.label_top.setText("Message View:    green: received messages       red: send message")
        self.viewDock = dockarea.Dock('view', size=(1000, 600))
        self.layout.addWidget(self.label_top)
        self.label_top.setFixedHeight(20)
        self.layout.addLayout(h_layout)        
        self.layout.addItem(QSpacerItem(10, 10))
 def _loadLogoWidget(self):
     """
     load logo widget
     """
     logoLayout = QHBoxLayout()
     self.imageLabel = QLabel()
     self.imageLabel.setPixmap(
             getpixmap("ui/images/Rosetta.png"))
     # Horizontal spacer
     hSpacer = QSpacerItem(1, 1,
                           QSizePolicy.Expanding,
                           QSizePolicy.Minimum)
     logoLayout.addItem(hSpacer)
     logoLayout.addWidget(self.imageLabel)
     logoLayout.addItem(hSpacer)
     return logoLayout
class AccountReassignPanel(Panel):
    def __init__(self, mainwindow):
        Panel.__init__(self, mainwindow)
        self._setupUi()
        self.model = mainwindow.model.account_reassign_panel
        self.model.view = self
        self.accountComboBox = ComboboxModel(model=self.model.account_list, view=self.accountComboBoxView)

        self.continueButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

    def _setupUi(self):
        if ISWINDOWS:
            self.resize(250, 140)
        else:
            self.resize(340, 165)
        self.setWindowTitle(tr("Re-assign Account"))
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.label.setWordWrap(True)
        self.label.setText(tr(
            "You\'re about to delete a non-empty account. Select an account to re-assign its "
            "transactions to."
        ))
        self.verticalLayout.addWidget(self.label)
        self.accountComboBoxView = QComboBox(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.accountComboBoxView.sizePolicy().hasHeightForWidth())
        self.accountComboBoxView.setSizePolicy(sizePolicy)
        self.accountComboBoxView.setMinimumSize(QSize(200, 0))
        self.verticalLayout.addWidget(self.accountComboBoxView)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.horizontalLayout = QHBoxLayout()
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.cancelButton = QPushButton(self)
        self.cancelButton.setText(tr("Cancel"))
        self.cancelButton.setShortcut("Esc")
        self.horizontalLayout.addWidget(self.cancelButton)
        self.continueButton = QPushButton(self)
        self.continueButton.setDefault(True)
        self.continueButton.setText(tr("Continue"))
        self.horizontalLayout.addWidget(self.continueButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
    def __init__(self, parent, remove_text, remove_method, add_text,
                 add_method):
        QWidget.__init__(self, parent)
        layout = QHBoxLayout()
        remove_button = QPushButton(remove_text, self)
        remove_button.setIcon(qApp.style().standardIcon(QStyle.SP_TrashIcon))
        remove_button.clicked.connect(remove_method)
        layout.addWidget(remove_button)
        layout.setContentsMargins(8, 0, 8, 0)

        horizontal_spacer = QSpacerItem(50, 20, QSizePolicy.Expanding,
                                        QSizePolicy.Minimum)
        layout.addItem(horizontal_spacer)

        add_button = QPushButton(add_text, self)
        add_button.clicked.connect(add_method)
        layout.addWidget(add_button)
        self.setLayout(layout)
Beispiel #29
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        vert_layout = QVBoxLayout()

        hor_layout = QHBoxLayout()
        self.array_box = QCheckBox(_("Import as array"))
        self.array_box.setEnabled(ndarray is not FakeObject)
        self.array_box.setChecked(ndarray is not FakeObject)
        hor_layout.addWidget(self.array_box)
        h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                               QSizePolicy.Minimum)
        hor_layout.addItem(h_spacer)

        self._table_view = PreviewTable(self)
        vert_layout.addLayout(hor_layout)
        vert_layout.addWidget(self._table_view)
        self.setLayout(vert_layout)
Beispiel #30
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     
     vert_layout = QVBoxLayout()
     
     hor_layout = QHBoxLayout()
     self.array_box = QCheckBox(_("Import as array"))
     self.array_box.setEnabled(ndarray is not FakeObject)
     self.array_box.setChecked(ndarray is not FakeObject)
     hor_layout.addWidget(self.array_box)
     h_spacer = QSpacerItem(40, 20,
                            QSizePolicy.Expanding, QSizePolicy.Minimum)        
     hor_layout.addItem(h_spacer)
     
     self._table_view = PreviewTable(self)
     vert_layout.addLayout(hor_layout)
     vert_layout.addWidget(self._table_view)
     self.setLayout(vert_layout)
Beispiel #31
0
class ProblemDialog(QDialog):
    def __init__(self, parent, model):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self._setupUi()
        self.model = model
        self.model.view = self
        self.table = ProblemTable(self.model.problem_table, view=self.tableView)
        
        self.revealButton.clicked.connect(self.model.reveal_selected_dupe)
        self.closeButton.clicked.connect(self.accept)
    
    def _setupUi(self):
        self.setWindowTitle(tr("Problems!"))
        self.resize(413, 323)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        msg = tr("There were problems processing some (or all) of the files. The cause of "
            "these problems are described in the table below. Those files were not "
            "removed from your results.")
        self.label.setText(msg)
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.tableView = QTableView(self)
        self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setShowGrid(False)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.verticalHeader().setDefaultSectionSize(18)
        self.tableView.verticalHeader().setHighlightSections(False)
        self.verticalLayout.addWidget(self.tableView)
        self.horizontalLayout = QHBoxLayout()
        self.revealButton = QPushButton(self)
        self.revealButton.setText(tr("Reveal Selected"))
        self.horizontalLayout.addWidget(self.revealButton)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.closeButton = QPushButton(self)
        self.closeButton.setText(tr("Close"))
        self.closeButton.setDefault(True)
        self.horizontalLayout.addWidget(self.closeButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
Beispiel #32
0
class WidgetNome(QWidget):
    nomeModificado = pyqtSignal(str)
    def __init__(self, texto='', parent=None):
        super().__init__(parent)
        self._configurarGui(texto)

        self._lblNome.visivelModificado.connect(self._mostrarModificarGravar)
        self._lblNome.textoModificado.connect(lambda nome: self.nomeModificado.emit(nome))
        self._btnGravar.clicked.connect(self._lblNome.mudarVisivel)

    def _configurarGui(self, texto):
        layout = QHBoxLayout()
        layout.setAlignment(Qt.AlignLeft)
        layout.setMargin(0)
        
        self._spacer = QSpacerItem(0,0,QSizePolicy.Expanding,QSizePolicy.Maximum)
        self._layoutSpacer = QHBoxLayout()
        self._layoutSpacer.addItem(self._spacer)
        
        lbl = QLabel('Nome: ', self)
        self._lblNome = EditLabel(texto)
        self._btnGravar = QPushButton('Modificar')

        layout.addWidget(lbl)
        layout.addWidget(self._lblNome)
        layout.addLayout(self._layoutSpacer)
        layout.addWidget(self._btnGravar)
        self.setLayout(layout)

    def _mostrarModificarGravar(self):
        if self._lblNome.isVisible():
            self._btnGravar.setText('Modificar')
            self._layoutSpacer.addItem(self._spacer)            
        else:
            self._btnGravar.setText('Gravar')
            self._layoutSpacer.removeItem(self._spacer)

    def getNome(self):
        return self._lblNome.getTexto()

    def setNome(self, nome):
        self._lblNome.setTexto(str(nome))
Beispiel #33
0
    def __init__(self, parent=None):
        super(AggregateOutputWidget, self).__init__(parent)
        self.setStyleSheet(OfSs.dock_style)
        # Create geometry
        self.setObjectName("Aggregate_Output")
        self.setWindowTitle("Aggregate_Output")
        self.dockWidgetContents = QWidget()

        agg_label = QLabel(u"Résultat aggregé de la simulation",
                           self.dockWidgetContents)
        self.aggregate_view = DataFrameViewWidget(self.dockWidgetContents)

        self.distribution_combo = MyComboBox(self.dockWidgetContents,
                                             u"Distribution de l'impact par")
        self.distribution_combo.box.setSizeAdjustPolicy(
            self.distribution_combo.box.AdjustToContents)
        self.distribution_combo.box.setDisabled(True)

        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)

        horizontalLayout = QHBoxLayout()
        #horizontalLayout.addWidget(dist_label)
        horizontalLayout.addWidget(self.distribution_combo)
        horizontalLayout.addItem(spacerItem)

        self.distribution_view = DataFrameViewWidget(self.dockWidgetContents)

        verticalLayout = QVBoxLayout(self.dockWidgetContents)
        verticalLayout.addWidget(agg_label)
        verticalLayout.addWidget(self.aggregate_view)
        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.distribution_view)
        self.setWidget(self.dockWidgetContents)

        # Initialize attributes
        self.parent = parent
        self.varlist = [
            'irpp', 'ppe', 'af', 'cf', 'ars', 'aeeh', 'asf', 'aspa', 'aah',
            'caah', 'rsa', 'aefa', 'api', 'logt'
        ]
        self.data = DataFrame()  # Pandas DataFrame
Beispiel #34
0
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_("Downloading"))

        # Top level fixed size dialog
        self.setWindowModality(Qt.WindowModal)

        self.__page_ = QLabel(self)
        self.__progress_ = QLabel(self)
        self.__cancel_ = QPushButton(self)
        self.__downloaded_ = 0
        self.__nbr_pages_ = 0

        vboxlayout = QVBoxLayout(self)

        # Page status
        labellayout = QHBoxLayout()
        labellayout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        labellayout.addWidget(self.__page_)
        labellayout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        vboxlayout.addLayout(labellayout)

        # Progress status
        progresslayout = QHBoxLayout()
        progresslayout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        progresslayout.addWidget(self.__progress_)
        progresslayout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        vboxlayout.addLayout(progresslayout)

        # Cancel button
        cancellayout = QHBoxLayout()
        cancellayout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        cancellayout.addWidget(self.__cancel_)
        vboxlayout.addLayout(cancellayout)

        self.__cancel_.setDefault(True)
        self.__cancel_.setText("Cancel")
        QObject.connect(self.__cancel_, SIGNAL("clicked()"),
                        self.__ui_progress_canceled_)
        QObject.connect(self, SIGNAL("rejected()"),
                        self.__ui_progress_canceled_)
Beispiel #35
0
    def __init__(self, parent=None):
        super(ExploreDataWidget, self).__init__(parent)
        self.setStyleSheet(OfSs.dock_style)
        # Create geometry
        self.setObjectName("ExploreData")
        self.setWindowTitle("ExploreData")
        self.dockWidgetContents = QWidget()

        data_label = QLabel(u"Data", self.dockWidgetContents)

        self.add_btn = QPushButton(u"Ajouter variable", self.dockWidgetContents)
        self.remove_btn = QPushButton(u"Retirer variable", self.dockWidgetContents)
        self.add_btn.setDisabled(True)
        self.remove_btn.setDisabled(True)

        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

        horizontalLayout = QHBoxLayout()
        horizontalLayout.addWidget(self.add_btn)
        horizontalLayout.addWidget(self.remove_btn)
        horizontalLayout.addItem(spacerItem)
        self.view = DataFrameViewWidget(self.dockWidgetContents)

        verticalLayout = QVBoxLayout(self.dockWidgetContents)
        verticalLayout.addWidget(data_label)

        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.view)
        self.setWidget(self.dockWidgetContents)

        # Initialize attributes
        self.parent = parent
        self.selected_vars = set()
        self.data = DataFrame()  # Pandas DataFrame
        self.vars = set()

        self.connect(self.add_btn, SIGNAL("clicked()"), self.add_var)
        self.connect(self.remove_btn, SIGNAL("clicked()"), self.remove_var)

        self.update_btns()
Beispiel #36
0
class dialogMemoryFileParametersDiffer(QDialog):
    def __init__(self, parent, text, diffText):
        QDialog.__init__(self, parent)
        self.prm = self.parent().prm
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(
            self.currLocale.OmitGroupSeparator
            | self.currLocale.RejectGroupSeparator)
        self.diffText = diffText
        self.vBoxSizer = QVBoxLayout()
        self.hBoxSizer = QHBoxLayout()
        self.textTF = QLabel(text)
        self.vBoxSizer.addWidget(self.textTF)

        self.yesButt = QPushButton(self.tr("Yes"), self)
        self.noButt = QPushButton(self.tr("No"), self)
        self.showDiffButt = QPushButton(self.tr("Show Differences"), self)
        self.cancelButt = QPushButton(self.tr("Cancel"), self)
        self.hBoxSizer.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding))
        self.hBoxSizer.addWidget(self.yesButt)
        self.hBoxSizer.addWidget(self.noButt)
        self.hBoxSizer.addWidget(self.showDiffButt)
        self.hBoxSizer.addWidget(self.cancelButt)
        self.vBoxSizer.addLayout(self.hBoxSizer)
        self.showDiffButt.clicked.connect(self.onClickShowDiffButt)
        self.cancelButt.clicked.connect(self.onClickCancelButt)
        self.yesButt.clicked.connect(self.accept)
        self.noButt.clicked.connect(self.reject)

        self.setLayout(self.vBoxSizer)
        self.setWindowTitle(self.tr("Warning"))
        self.show()

    def onClickShowDiffButt(self):
        dia = dialogShowParDiff(self, self.diffText)

    def onClickCancelButt(self):
        self.parent().exitFlag = False
        self.accept()
Beispiel #37
0
    def __init__(self, duration: float, parent: QWidget = None):
        QWidget.__init__(self, parent)

        self.log = getLoggerPassFilters(LOGGER_NAMES.LIVEPLAYER)

        self.button = PlayPauseButton()
        self.button.setMaximumWidth(100)
        self.button.clicked.connect(self.onButtonClicked)

        self.timeSlider = ClickableProgressBar()
        self.timeSlider.setMinimum(0)
        self.timeSlider.setMaximum(int(duration * 1000))
        self.timeSlider.valueChanged.connect(self.onSeek)

        self.speedLabel = QLabel("Speed: 1x")

        self.speedSlider = QSlider(Qt.Horizontal)
        self.speedSlider.setMaximumWidth(300)
        self.speedSlider.setMinimum(1)
        self.speedSlider.setMaximum(10)
        self.speedSlider.valueChanged.connect(self.onSpeedChanged)

        vertical = QVBoxLayout()

        horizontal = QHBoxLayout()
        horizontal.addWidget(self.speedLabel)
        horizontal.addWidget(self.speedSlider)
        horizontal.addItem(
            QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding))
        vertical.addLayout(horizontal)

        horizontal = QHBoxLayout()
        horizontal.addWidget(self.button)
        horizontal.addWidget(self.timeSlider)
        vertical.addLayout(horizontal)

        self.setLayout(vertical)
        self.setGeometry(0, 0, 80, 60)
Beispiel #38
0
class PageController(QWidget):
    def __init__(self, model):
        QWidget.__init__(self)
        self.model = model
        self.model.view = self
        self._setupUi()
        
        self.previousPageButton.clicked.connect(self.model.prev_page)
        self.nextPageButton.clicked.connect(self.model.next_page)
        self.reorderModeCheckBox.stateChanged.connect(self.reorderModeCheckBoxStateChanged)
    
    def _setupUi(self):
        self.setWindowTitle("Grouping Dialog")
        self.resize(600, 600)
        self.mainLayout = QVBoxLayout(self)
        self.pageRepr = PageRepresentation(self.model.page_repr)
        self.mainLayout.addWidget(self.pageRepr)
        self.buttonLayout = QHBoxLayout()
        self.previousPageButton = QPushButton("<<")
        self.buttonLayout.addWidget(self.previousPageButton)
        self.pageLabel = QLabel()
        self.buttonLayout.addWidget(self.pageLabel)
        self.nextPageButton = QPushButton(">>")
        self.buttonLayout.addWidget(self.nextPageButton)
        self.reorderModeCheckBox = QCheckBox("Re-order mode")
        self.buttonLayout.addWidget(self.reorderModeCheckBox)
        self.buttonLayout.addItem(horizontalSpacer())
        self.mainLayout.addLayout(self.buttonLayout)
    
    #--- Signals
    def reorderModeCheckBoxStateChanged(self, state):
        self.model.page_repr.reorder_mode = state == Qt.Checked
    
    #--- model --> view
    def refresh_page_label(self):
        self.pageLabel.setText(self.model.page_label)
    def __init__(self, parent = None):
        super(AggregateOutputWidget, self).__init__(parent)
        self.setStyleSheet(OfSs.dock_style)
        # Create geometry
        self.setObjectName("Aggregate_Output")
        self.setWindowTitle("Aggregate_Output")
        self.dockWidgetContents = QWidget()
        
        agg_label = QLabel(u"Résultat aggregé de la simulation", self.dockWidgetContents)
        self.aggregate_view = DataFrameViewWidget(self.dockWidgetContents)


        self.distribution_combo = MyComboBox(self.dockWidgetContents, u"Distribution de l'impact par")
        self.distribution_combo.box.setSizeAdjustPolicy(self.distribution_combo.box.AdjustToContents)
        self.distribution_combo.box.setDisabled(True)
        
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

        horizontalLayout = QHBoxLayout()
        #horizontalLayout.addWidget(dist_label)
        horizontalLayout.addWidget(self.distribution_combo)
        horizontalLayout.addItem(spacerItem)

        self.distribution_view = DataFrameViewWidget(self.dockWidgetContents)

        verticalLayout = QVBoxLayout(self.dockWidgetContents)
        verticalLayout.addWidget(agg_label)
        verticalLayout.addWidget(self.aggregate_view)
        verticalLayout.addLayout(horizontalLayout)
        verticalLayout.addWidget(self.distribution_view)
        self.setWidget(self.dockWidgetContents)

        # Initialize attributes
        self.parent = parent
        self.varlist = ['irpp', 'ppe', 'af', 'cf', 'ars', 'aeeh', 'asf', 'aspa', 'aah', 'caah', 'rsa', 'aefa', 'api', 'logt']
        self.data = DataFrame() # Pandas DataFrame
class AngleGradientBoxPanel(QWidget):
    def __init__(self, parent, resoution=None):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName(
            "AngleGradientBoxPanel" +
            str(len(parent.findChildren(AngleGradientBoxPanel))))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.frameBoxPanelIn = QFrame(self.frameBoxPanel)
        self.frameBoxPanelIn.setFrameShape(QFrame.StyledPanel)
        self.frameBoxPanelIn.setFrameShadow(QFrame.Raised)
        self.frameBoxPanelIn.setObjectName(("frameBoxPanelIn"))
        self.hLayoutframeBoxPanelIn = QHBoxLayout(self.frameBoxPanelIn)
        self.hLayoutframeBoxPanelIn.setSpacing(0)
        self.hLayoutframeBoxPanelIn.setMargin(0)
        self.hLayoutframeBoxPanelIn.setObjectName(("hLayoutframeBoxPanelIn"))

        self.txtDegree = QLineEdit(self.frameBoxPanelIn)
        self.txtDegree.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtDegree.setFont(font)
        self.txtDegree.setObjectName(self.objectName() + "_txtDegree")
        self.txtDegree.setText("0.0")
        self.txtDegree.setMinimumWidth(70)
        self.txtDegree.setMaximumWidth(70)
        self.hLayoutframeBoxPanelIn.addWidget(self.txtDegree)

        self.labelDegree = QLabel(self.frameBoxPanelIn)
        self.labelDegree.setObjectName(("labelDegree"))
        self.labelDegree.setText(" " + define._degreeStr + " ")
        self.hLayoutframeBoxPanelIn.addWidget(self.labelDegree)

        self.txtPercent = QLineEdit(self.frameBoxPanelIn)
        self.txtPercent.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtPercent.setFont(font)
        self.txtPercent.setObjectName(self.objectName() + "_txtPercent")
        self.txtPercent.setText("0.0")
        self.txtPercent.setMinimumWidth(70)
        self.txtPercent.setMaximumWidth(70)
        self.hLayoutframeBoxPanelIn.addWidget(self.txtPercent)

        self.labelPercent = QLabel(self.frameBoxPanelIn)
        self.labelPercent.setObjectName(("labelPercent"))
        self.labelPercent.setText(" %")
        self.hLayoutframeBoxPanelIn.addWidget(self.labelPercent)

        self.hLayoutframeBoxPanel.addWidget(self.frameBoxPanelIn)

        # self.angleGradientBox = QLineEdit(self.frameBoxPanel)
        # self.angleGradientBox.setEnabled(True)
        # font = QFont()
        # font.setBold(False)
        # font.setWeight(50)
        # self.angleGradientBox.setFont(font)
        # self.angleGradientBox.setObjectName(("angleGradientBox"))
        # self.angleGradientBox.setText("0.0")
        # self.angleGradientBox.setMinimumWidth(70)
        # self.angleGradientBox.setMaximumWidth(70)
        # self.hLayoutframeBoxPanel.addWidget(self.angleGradientBox)

        self.imageButton = QPushButton(self.frameBoxPanel)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(0, 0, QSizePolicy.Minimum,
                                 QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)

        self.txtDegree.textChanged.connect(self.txtDegreeChanged)
        self.txtPercent.textChanged.connect(self.txtPercentChanged)
        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.numberResolution = resoution
        str0 = String.Number2String(6.6788, "0.00000")

        self.captionUnits = ""
        self.hidePercentBox()
        self.flag = 0

    def txtPercentChanged(self):
        try:
            test = float(self.txtPercent.text())
            if self.flag == 0:
                self.flag = 1
            if self.flag == 2:
                self.flag = 0
            if self.flag == 1:
                try:
                    self.txtDegree.setText(
                        str(
                            round(
                                AngleGradientSlope(
                                    float(self.txtPercent.text()),
                                    AngleGradientSlopeUnits.Percent).Degrees,
                                4)))
                except:
                    self.txtDegree.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"." % (self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            self.txtDegree.setText("0.0")

    def txtDegreeChanged(self):
        try:
            test = float(self.txtDegree.text())
            if self.flag == 0:
                self.flag = 2
            if self.flag == 1:
                self.flag = 0
            if self.flag == 2:
                try:
                    self.txtPercent.setText(
                        str(
                            round(
                                AngleGradientSlope(float(
                                    self.txtDegree.text())).Percent, 4)))
                except:
                    self.txtPercent.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"." % (self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            self.txtPercent.setText("0.0")

    def hidePercentBox(self):
        self.txtPercent.setVisible(False)
        self.labelPercent.setVisible(False)

    def showPercentBox(self):
        self.txtPercent.setVisible(True)
        self.labelPercent.setVisible(True)

    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_1"), self)

    def method_6(self, string_0):
        return "%s%s\t%f %s" % (string_0, self.Caption, self.Value,
                                self.CaptionUnits)

    def ToString(self):
        caption = self.captionLabel.text()
        value = self.txtDegree.text()
        return "{0}, {1}".format(caption, value)

    def get_CaptionUnits(self):
        return self.captionUnits

    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.captionLabel.text()
        # findIndex = caption.indexOf("(")
        # if findIndex > 0:
        #     val = caption.left(findIndex)
        #     return val
        return caption

    def set_Caption(self, captionStr):
        self.captionLabel.setText(captionStr + ":")
        # value = ""
        # if self.captionUnits == AngleGradientSlopeUnits.Degrees:
        #     value = captionStr + "(" + define._degreeStr + ")"
        # elif self.captionUnits == AngleGradientSlopeUnits.Percent:
        #     value = captionStr + "(%)"
        # elif self.captionUnits == AngleGradientSlopeUnits.Slope:
        #     value = captionStr + "(1:)"
        # self.captionLabel.setText(value + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    # def get_IsEmpty(self):
    #     return self.angleGradientBox.text() == ""
    # IsEmpty = property(get_IsEmpty, None, None, None)

    def get_Value(self):
        return AngleGradientSlope(float(self.txtDegree.text()))
        # if self.captionUnits == AngleGradientSlopeUnits.Degrees:
        #     try:
        #         return AngleGradientSlope(float(self.angleGradientBox.text()))
        #     except:
        #         return None
        # elif self.captionUnits == AngleGradientSlopeUnits.Percent:
        #     try:
        #         return AngleGradientSlope(float(self.angleGradientBox.text()), AngleGradientSlopeUnits.Percent)
        #     except:
        #         return None
        # elif self.captionUnits == AngleGradientSlopeUnits.Slope:
        #     try:
        #         return AngleGradientSlope(float(self.angleGradientBox.text()), AngleGradientSlopeUnits.Slope)
        #     except:
        #         return None

    def set_Value(self, value):
        if isinstance(value, AngleGradientSlope):
            self.txtDegree.setText(str(round(value.Degrees, 4)))
            return
            # if self.captionUnits == AngleGradientSlopeUnits.Degrees:
            #     rStr = String.Number2String(value.Degrees, self.numberResolution)
            #     self.angleGradientBox.setText(rStr)
            # elif self.captionUnits == AngleGradientSlopeUnits.Percent:
            #     rStr = String.Number2String(value.Percent, self.numberResolution)
            #     self.angleGradientBox.setText(rStr)
            # elif self.captionUnits == AngleGradientSlopeUnits.Slope:
            #     rStr = String.Number2String(value.Slope, self.numberResolution)
            #     self.angleGradientBox.setText(rStr)
            # return

        try:
            test = float(value)
            rStr = String.Number2String(test, self.numberResolution)
            self.txtDegree.setText(rStr)
        except:
            str0 = "You must put the float type in \"%s\"." % (self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            # rStr = String.Number2String(0, self.numberResolution)
            self.txtDegree.setText("0.0")

    Value = property(get_Value, set_Value, None, None)

    # def get_IsEmpty(self):
    #     return self.angleGradientBox.text() == "" or self.angleGradientBox.text() == None
    # IsEmpty = property(get_IsEmpty, None, None, None)

    def get_ReadOnly(self):
        return self.txtDegree.isReadOnly()

    def set_ReadOnly(self, bool):
        self.txtDegree.setReadOnly(bool)
        self.txtPercent.setReadOnly(bool)

    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_Enabled(self):
        return self.isEnabled()

    def set_Enabled(self, bool):
        self.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)
class AltitudeBoxPanel(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("AltitudeBoxPanel" + str(len(parent.findChildren(AltitudeBoxPanel))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0,0,0,0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.frameBoxPanelIn = QFrame(self.frameBoxPanel)
        self.frameBoxPanelIn.setFrameShape(QFrame.StyledPanel)
        self.frameBoxPanelIn.setFrameShadow(QFrame.Raised)
        self.frameBoxPanelIn.setObjectName(("frameBoxPanelIn"))
        self.hLayoutframeBoxPanelIn = QHBoxLayout(self.frameBoxPanelIn)
        self.hLayoutframeBoxPanelIn.setSpacing(0)
        self.hLayoutframeBoxPanelIn.setMargin(0)
        self.hLayoutframeBoxPanelIn.setObjectName(("hLayoutframeBoxPanelIn"))

        self.txtAltitudeM = QLineEdit(self.frameBoxPanelIn)
        self.txtAltitudeM.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtAltitudeM.setFont(font)
        self.txtAltitudeM.setObjectName(self.objectName() + "_txtAltitudeM")
        self.txtAltitudeM.setText("0.0")
        self.txtAltitudeM.setMinimumWidth(70)
        self.txtAltitudeM.setMaximumWidth(70)
        self.hLayoutframeBoxPanelIn.addWidget(self.txtAltitudeM)

        labelM = QLabel(self.frameBoxPanelIn)
        labelM.setObjectName(("labelM"))
        labelM.setText(" m ")
        self.hLayoutframeBoxPanelIn.addWidget(labelM)

        self.txtAltitudeFt = QLineEdit(self.frameBoxPanelIn)
        self.txtAltitudeFt.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtAltitudeFt.setFont(font)
        self.txtAltitudeFt.setObjectName(self.objectName() + "_txtAltitudeFt")
        self.txtAltitudeFt.setText("0.0")
        self.txtAltitudeFt.setMinimumWidth(70)
        self.txtAltitudeFt.setMaximumWidth(70)
        self.hLayoutframeBoxPanelIn.addWidget(self.txtAltitudeFt)

        labelFt = QLabel(self.frameBoxPanelIn)
        labelFt.setObjectName(("labelFt"))
        labelFt.setText(" ft")
        self.hLayoutframeBoxPanelIn.addWidget(labelFt)

        self.hLayoutframeBoxPanel.addWidget(self.frameBoxPanelIn)
        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)



        self.txtAltitudeM.textChanged.connect(self.txtAltitudeMChanged)
        self.txtAltitudeFt.textChanged.connect(self.txtAltitudeFtChanged)

        self.txtAltitudeM.editingFinished.connect(self.txtAltitude_returnPressed)
        self.txtAltitudeFt.editingFinished.connect(self.txtAltitude_returnPressed)

        self.value = 0.0
        self.captionUnits = "m"
        self.OriginalUnits = "m"

        self.flag = 0
        self.txtAltitudeM.setText("0.0")
    def mouseMoveEvent(self, mouseEvent):
        pt = mouseEvent.pos()
        c = self.childAt(pt)
        pass
    def method_8(self, string_0):
        if self.CaptionUnits == "m":
            return "%s%s\t%s %s"%(string_0, self.Caption, self.txtAltitudeM, self.CaptionUnits);
        else:
            return "%s%s\t%s %s"%(string_0, self.Caption, self.txtAltitudeFt, self.CaptionUnits);
    def txtAltitude_returnPressed(self):
        self.emit(SIGNAL("editingFinished"), self)
    def txtAltitudeFtChanged(self):
        try:
            test = float(self.txtAltitudeFt.text())
            if self.flag==0:
                self.flag=1;
            if self.flag==2:
                self.flag=0;
            if self.flag==1:
                try:
                    self.txtAltitudeM.setText(str(round(Unit.ConvertFeetToMeter(float(self.txtAltitudeFt.text())), 4)))
                except:
                    self.txtAltitudeM.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtAltitudeM.setText("0.0")


    def txtAltitudeMChanged(self):
        try:
            test = float(self.txtAltitudeM.text())
            if self.flag==0:
                self.flag=2;
            if self.flag==1:
                self.flag=0;
            if self.flag==2:
                try:
                    self.txtAltitudeFt.setText(str(round(Unit.ConvertMeterToFeet(float(self.txtAltitudeM.text())), 4)))
                except:
                    self.txtAltitudeFt.setText("0.0")
                self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtAltitudeFt.setText("0.0")

    def get_CaptionUnits(self):
        return self.captionUnits
    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits
        self.OriginalUnits = captionUnits
    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.captionLabel.text()
        val = caption.left(caption.length() - 1)
        return val
    def set_Caption(self, captionStr):
        self.captionLabel.setText(captionStr + ":")
    Caption = property(get_Caption, set_Caption, None, None)

    def get_Visible(self):
        return self.isVisible()
    def set_Visible(self, bool):
        self.setVisible(bool)
    Visible = property(get_Visible, set_Visible, None, None)

    def get_Value(self):
        try:
            return Altitude(float(self.txtAltitudeM.text()))
        except:
            return Altitude(0.0)

    def set_Value(self, altitude):
        if altitude == None:
            self.txtAltitudeM.setText(str("0.0"))
            return
        if isinstance(altitude, Altitude):
            if self.CaptionUnits == "m":
                self.txtAltitudeM.setText(str(round(altitude.Metres, 4)))
            else:
                self.txtAltitudeFt.setText(str(round(altitude.Feet, 4)))
        else:
            str0 = "You must input the type \"Altitude\" in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtAltitudeM.setText("0.0")
    Value = property(get_Value, set_Value, None, None)

    def get_IsEmpty(self):
        return self.txtAltitudeM.text() == "" or self.txtAltitudeM.text() == None
    IsEmpty = property(get_IsEmpty, None, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))
    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_ReadOnly(self):
        return self.txtAltitudeM.isReadOnly()
    def set_ReadOnly(self, bool):
        self.txtAltitudeM.setReadOnly(bool)
        self.txtAltitudeFt.setReadOnly(bool)
    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def get_Enabled(self):
        return self.txtAltitudeM.isEnabled()
    def set_Enabled(self, bool):
        self.txtAltitudeM.setEnabled(bool)
        self.txtAltitudeFt.setEnabled(bool)
    Enabled = property(get_Enabled, set_Enabled, None, None)
Beispiel #42
0
class PreferencesDialog(PreferencesDialogBase):
    def __init__(self, parent, app):
        PreferencesDialogBase.__init__(self, parent, app)
        
        self.scanTypeComboBox.currentIndexChanged[int].connect(self.scanTypeChanged)
    
    def _setupPreferenceWidgets(self):
        scanTypeLabels = [
            tr("Filename"),
            tr("Filename - Fields"),
            tr("Filename - Fields (No Order)"),
            tr("Tags"),
            tr("Contents"),
            tr("Audio Contents"),
        ]
        self._setupScanTypeBox(scanTypeLabels)
        self._setupFilterHardnessBox()
        self.widgetsVLayout.addLayout(self.filterHardnessHLayout)
        self.widget = QWidget(self)
        self.widget.setMinimumSize(QSize(0, 40))
        self.verticalLayout_4 = QVBoxLayout(self.widget)
        self.verticalLayout_4.setSpacing(0)
        self.verticalLayout_4.setMargin(0)
        self.label_6 = QLabel(self.widget)
        self.label_6.setText(tr("Tags to scan:"))
        self.verticalLayout_4.addWidget(self.label_6)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setSpacing(0)
        spacerItem1 = QSpacerItem(15, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self._setupAddCheckbox('tagTrackBox', tr("Track"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagTrackBox)
        self._setupAddCheckbox('tagArtistBox', tr("Artist"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagArtistBox)
        self._setupAddCheckbox('tagAlbumBox', tr("Album"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagAlbumBox)
        self._setupAddCheckbox('tagTitleBox', tr("Title"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagTitleBox)
        self._setupAddCheckbox('tagGenreBox', tr("Genre"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagGenreBox)
        self._setupAddCheckbox('tagYearBox', tr("Year"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagYearBox)
        self.verticalLayout_4.addLayout(self.horizontalLayout_2)
        self.widgetsVLayout.addWidget(self.widget)
        self._setupAddCheckbox('wordWeightingBox', tr("Word weighting"))
        self.widgetsVLayout.addWidget(self.wordWeightingBox)
        self._setupAddCheckbox('matchSimilarBox', tr("Match similar words"))
        self.widgetsVLayout.addWidget(self.matchSimilarBox)
        self._setupAddCheckbox('mixFileKindBox', tr("Can mix file kind"))
        self.widgetsVLayout.addWidget(self.mixFileKindBox)
        self._setupAddCheckbox('useRegexpBox', tr("Use regular expressions when filtering"))
        self.widgetsVLayout.addWidget(self.useRegexpBox)
        self._setupAddCheckbox('removeEmptyFoldersBox', tr("Remove empty folders on delete or move"))
        self.widgetsVLayout.addWidget(self.removeEmptyFoldersBox)
        self._setupAddCheckbox('ignoreHardlinkMatches', tr("Ignore duplicates hardlinking to the same file"))
        self.widgetsVLayout.addWidget(self.ignoreHardlinkMatches)
        self._setupAddCheckbox('debugModeBox', tr("Debug mode (restart required)"))
        self.widgetsVLayout.addWidget(self.debugModeBox)
        self._setupBottomPart()
    
    def _load(self, prefs, setchecked):
        scan_type_index = SCAN_TYPE_ORDER.index(prefs.scan_type)
        self.scanTypeComboBox.setCurrentIndex(scan_type_index)
        setchecked(self.tagTrackBox, prefs.scan_tag_track)
        setchecked(self.tagArtistBox, prefs.scan_tag_artist)
        setchecked(self.tagAlbumBox, prefs.scan_tag_album)
        setchecked(self.tagTitleBox, prefs.scan_tag_title)
        setchecked(self.tagGenreBox, prefs.scan_tag_genre)
        setchecked(self.tagYearBox, prefs.scan_tag_year)
        setchecked(self.matchSimilarBox, prefs.match_similar)
        setchecked(self.wordWeightingBox, prefs.word_weighting)
    
    def _save(self, prefs, ischecked):
        prefs.scan_type = SCAN_TYPE_ORDER[self.scanTypeComboBox.currentIndex()]
        prefs.scan_tag_track = ischecked(self.tagTrackBox)
        prefs.scan_tag_artist = ischecked(self.tagArtistBox)
        prefs.scan_tag_album = ischecked(self.tagAlbumBox)
        prefs.scan_tag_title = ischecked(self.tagTitleBox)
        prefs.scan_tag_genre = ischecked(self.tagGenreBox)
        prefs.scan_tag_year = ischecked(self.tagYearBox)
        prefs.match_similar = ischecked(self.matchSimilarBox)
        prefs.word_weighting = ischecked(self.wordWeightingBox)
    
    def resetToDefaults(self):
        self.load(preferences.Preferences())
    
    #--- Events
    def scanTypeChanged(self, index):
        scan_type = SCAN_TYPE_ORDER[self.scanTypeComboBox.currentIndex()]
        word_based = scan_type in (ScanType.Filename, ScanType.Fields, ScanType.FieldsNoOrder,
            ScanType.Tag)
        tag_based = scan_type == ScanType.Tag
        self.filterHardnessSlider.setEnabled(word_based)
        self.matchSimilarBox.setEnabled(word_based)
        self.wordWeightingBox.setEnabled(word_based)
        self.tagTrackBox.setEnabled(tag_based)
        self.tagArtistBox.setEnabled(tag_based)
        self.tagAlbumBox.setEnabled(tag_based)
        self.tagTitleBox.setEnabled(tag_based)
        self.tagGenreBox.setEnabled(tag_based)
        self.tagYearBox.setEnabled(tag_based)
Beispiel #43
0
class DegreesBoxPanel(QWidget):
    def __init__(self, parent , boxType = None):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("DegreesBoxPanel" + str(len(parent.findChildren(DegreesBoxPanel))))


        self.hLayoutDegreesBoxPanel = QHBoxLayout(self)
        self.hLayoutDegreesBoxPanel.setSpacing(0)
        self.hLayoutDegreesBoxPanel.setContentsMargins(0,0,0,0)
        self.hLayoutDegreesBoxPanel.setObjectName(("hLayoutDegreesBoxPanel"))
        self.frameDegreesBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frameDegreesBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameDegreesBoxPanel.setSizePolicy(sizePolicy)
        self.frameDegreesBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameDegreesBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameDegreesBoxPanel.setObjectName(("frameDegreesBoxPanel"))
        self.hLayoutFrameDegreesBoxPanel = QHBoxLayout(self.frameDegreesBoxPanel)
        self.hLayoutFrameDegreesBoxPanel.setSpacing(0)
        self.hLayoutFrameDegreesBoxPanel.setMargin(0)
        self.hLayoutFrameDegreesBoxPanel.setObjectName(("hLayoutFrameDegreesBoxPanel"))
        self.captionLabel = QLabel(self.frameDegreesBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutFrameDegreesBoxPanel.addWidget(self.captionLabel)
        self.frameDegreesBoxPanelIn = QFrame(self.frameDegreesBoxPanel)
        self.frameDegreesBoxPanelIn.setFrameShape(QFrame.StyledPanel)
        self.frameDegreesBoxPanelIn.setFrameShadow(QFrame.Raised)
        self.frameDegreesBoxPanelIn.setObjectName(("frameDegreesBoxPanelIn"))
        self.hLayoutFrameDegreesBoxPanelIn = QHBoxLayout(self.frameDegreesBoxPanelIn)
        self.hLayoutFrameDegreesBoxPanelIn.setSpacing(0)
        self.hLayoutFrameDegreesBoxPanelIn.setMargin(0)
        self.hLayoutFrameDegreesBoxPanelIn.setObjectName(("hLayoutFrameDegreesBoxPanelIn"))
        self.txtDegreeBox = QLineEdit(self.frameDegreesBoxPanelIn)
        self.txtDegreeBox.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.txtDegreeBox.setFont(font)
        self.txtDegreeBox.setObjectName(self.objectName() + "_txtDegreeBox")
        self.txtDegreeBox.setText("0.0")
        self.txtDegreeBox.setMinimumWidth(70)
        self.txtDegreeBox.setMaximumWidth(70)
        self.hLayoutFrameDegreesBoxPanelIn.addWidget(self.txtDegreeBox)
        self.btnDegreeBoxPanel = QToolButton(self.frameDegreesBoxPanelIn)
        self.btnDegreeBoxPanel.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/Calculator.bmp")), QIcon.Normal, QIcon.Off)
        self.btnDegreeBoxPanel.setIcon(icon)
        self.btnDegreeBoxPanel.setObjectName(("btnDegreeBoxPanel"))
        self.hLayoutFrameDegreesBoxPanelIn.addWidget(self.btnDegreeBoxPanel)
        self.hLayoutFrameDegreesBoxPanel.addWidget(self.frameDegreesBoxPanelIn)
        self.hLayoutDegreesBoxPanel.addWidget(self.frameDegreesBoxPanel)

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.hLayoutDegreesBoxPanel.addItem(spacerItem)


        self.btnDegreeBoxPanel.clicked.connect(self.btnDegreeBoxPanel_clicked)
        self.txtDegreeBox.textChanged.connect(self.txtDegreeBox_textChanged)

        self.boxType = boxType
        self.value = 0.0
    def txtDegreeBox_textChanged(self):
        try:
            test = float(self.txtDegreeBox.text())
            self.emit(SIGNAL("txtDegreeBox_textChanged"), self)
        except:
            str0 = "You must input the float type in \"%s\"."%(self.Caption)
            QMessageBox.warning(self, "Warning" , str0)
            self.txtDegreeBox.setText("0.0")

    def btnDegreeBoxPanel_clicked(self):
        self.emit(SIGNAL("btnDegreeBoxPanel_clicked"), self)

    def btnDegreeBoxPanel_visible(self, bool):
        self.btnDegreeBoxPanel.setVisible(bool)
    ButtonVisible = property(None, btnDegreeBoxPanel_visible, None, None)

    def get_Value(self):
        try:
            return float(self.txtDegreeBox.text())
        except:
            return 0.0

    def set_Value(self, value):
        self.txtDegreeBox.setText(str(value))
    Value = property(get_Value, set_Value, None, None)

    # def set_Enabled(self, bool):
    #     self.txtDegreeBox.setEnabled(bool)
    # Enabled = property(None, set_Enabled, None, None)
    
    def set_CaptionLabel(self, labelString):
        self.captionLabel.setText(labelString + ":")
    CaptionLabel = property(None, set_CaptionLabel, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))
    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_ReadOnly(self):
        return self.txtDegreeBox.isReadOnly()
    def set_ReadOnly(self, bool):
        self.txtDegreeBox.setReadOnly(bool)
    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def get_Enabled(self):
        return self.txtDegreeBox.isEnabled()
    def set_Enabled(self, bool):
        self.txtDegreeBox.setEnabled(bool)
    Enabled = property(get_Enabled, set_Enabled, None, None)
Beispiel #44
0
class RadioBox(QWidget):
    def __init__(self, parent=None, items=None, spread=True):
        # If spread is False, insert a spacer in the layout so that the items don't use all the
        # space they're given but rather align left.
        if items is None:
            items = []
        QWidget.__init__(self, parent)
        self._buttons = []
        self._labels = items
        self._selected_index = 0
        self._spacer = horizontalSpacer() if not spread else None
        self._layout = QHBoxLayout(self)
        self._update_buttons()
    
    #--- Private
    def _update_buttons(self):
        if self._spacer is not None:
            self._layout.removeItem(self._spacer)
        to_remove = self._buttons[len(self._labels):]
        for button in to_remove:
            self._layout.removeWidget(button)
            button.setParent(None)
        del self._buttons[len(self._labels):]
        to_add = self._labels[len(self._buttons):]
        for _ in to_add:
            button = QRadioButton(self)
            self._buttons.append(button)
            self._layout.addWidget(button)
            button.toggled.connect(self.buttonToggled)
        if self._spacer is not None:
            self._layout.addItem(self._spacer)
        if not self._buttons:
            return
        for button, label in zip(self._buttons, self._labels):
            button.setText(label)
        self._update_selection()
    
    def _update_selection(self):
        self._selected_index = max(0, min(self._selected_index, len(self._buttons)-1))
        selected = self._buttons[self._selected_index]
        selected.setChecked(True)
    
    #--- Event Handlers
    def buttonToggled(self):
        for i, button in enumerate(self._buttons):
            if button.isChecked():
                self._selected_index = i
                self.itemSelected.emit(i)
                break
    
    #--- Signals
    itemSelected = pyqtSignal(int)
    
    #--- Properties
    @property
    def buttons(self):
        return self._buttons[:]
    
    @property
    def items(self):
        return self._labels[:]
    
    @items.setter
    def items(self, value):
        self._labels = value
        self._update_buttons()
    
    @property
    def selected_index(self):
        return self._selected_index
    
    @selected_index.setter
    def selected_index(self, value):
        self._selected_index = value
        self._update_selection()
class PreferencesDialogBase(QDialog):
    def __init__(self, parent, app):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.app = app
        self._setupUi()
        
        self.connect(self.filterHardnessSlider, SIGNAL("valueChanged(int)"), self.filterHardnessLabel.setNum)
        self.connect(self.buttonBox, SIGNAL('clicked(QAbstractButton*)'), self.buttonClicked)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupScanTypeBox(self, labels):
        self.scanTypeHLayout = QHBoxLayout()
        self.scanTypeLabel = QLabel(self)
        self.scanTypeLabel.setText(tr("Scan Type:"))
        self.scanTypeLabel.setMinimumSize(QSize(100, 0))
        self.scanTypeLabel.setMaximumSize(QSize(100, 16777215))
        self.scanTypeHLayout.addWidget(self.scanTypeLabel)
        self.scanTypeComboBox = QComboBox(self)
        for label in labels:
            self.scanTypeComboBox.addItem(label)
        self.scanTypeHLayout.addWidget(self.scanTypeComboBox)
        self.widgetsVLayout.addLayout(self.scanTypeHLayout)
    
    def _setupFilterHardnessBox(self):
        self.filterHardnessHLayout = QHBoxLayout()
        self.filterHardnessLabel = QLabel(self)
        self.filterHardnessLabel.setText(tr("Filter Hardness:"))
        self.filterHardnessLabel.setMinimumSize(QSize(0, 0))
        self.filterHardnessHLayout.addWidget(self.filterHardnessLabel)
        self.filterHardnessVLayout = QVBoxLayout()
        self.filterHardnessVLayout.setSpacing(0)
        self.filterHardnessHLayoutSub1 = QHBoxLayout()
        self.filterHardnessHLayoutSub1.setSpacing(12)
        self.filterHardnessSlider = QSlider(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.filterHardnessSlider.sizePolicy().hasHeightForWidth())
        self.filterHardnessSlider.setSizePolicy(sizePolicy)
        self.filterHardnessSlider.setMinimum(1)
        self.filterHardnessSlider.setMaximum(100)
        self.filterHardnessSlider.setTracking(True)
        self.filterHardnessSlider.setOrientation(Qt.Horizontal)
        self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider)
        self.filterHardnessLabel = QLabel(self)
        self.filterHardnessLabel.setText("100")
        self.filterHardnessLabel.setMinimumSize(QSize(21, 0))
        self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel)
        self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1)
        self.filterHardnessHLayoutSub2 = QHBoxLayout()
        self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1)
        self.moreResultsLabel = QLabel(self)
        self.moreResultsLabel.setText(tr("More Results"))
        self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.filterHardnessHLayoutSub2.addItem(spacerItem)
        self.fewerResultsLabel = QLabel(self)
        self.fewerResultsLabel.setText(tr("Fewer Results"))
        self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel)
        self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2)
        self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout)
    
    def _setupBottomPart(self):
        # The bottom part of the pref panel is always the same in all editions.
        self.fontSizeLabel = QLabel(tr("Font size:"))
        self.fontSizeSpinBox = QSpinBox()
        self.fontSizeSpinBox.setMinimum(5)
        self.widgetsVLayout.addLayout(horizontalWrap([self.fontSizeLabel, self.fontSizeSpinBox, None]))
        self.languageLabel = QLabel(tr("Language:"), self)
        self.languageComboBox = QComboBox(self)
        for lang in SUPPORTED_LANGUAGES:
            self.languageComboBox.addItem(LANGNAMES[lang])
        self.widgetsVLayout.addLayout(horizontalWrap([self.languageLabel, self.languageComboBox, None]))
        self.copyMoveLabel = QLabel(self)
        self.copyMoveLabel.setText(tr("Copy and Move:"))
        self.widgetsVLayout.addWidget(self.copyMoveLabel)
        self.copyMoveDestinationComboBox = QComboBox(self)
        self.copyMoveDestinationComboBox.addItem(tr("Right in destination"))
        self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path"))
        self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path"))
        self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox)
        self.customCommandLabel = QLabel(self)
        self.customCommandLabel.setText(tr("Custom Command (arguments: %d for dupe, %r for ref):"))
        self.widgetsVLayout.addWidget(self.customCommandLabel)
        self.customCommandEdit = QLineEdit(self)
        self.widgetsVLayout.addWidget(self.customCommandEdit)
    
    def _setupAddCheckbox(self, name, label, parent=None):
        if parent is None:
            parent = self
        cb = QCheckBox(parent)
        cb.setText(label)
        setattr(self, name, cb)
    
    def _setupPreferenceWidgets(self):
        # Edition-specific
        pass
    
    def _setupUi(self):
        self.setWindowTitle(tr("Preferences"))
        self.resize(304, 263)
        self.setSizeGripEnabled(False)
        self.setModal(True)
        self.mainVLayout = QVBoxLayout(self)
        self.widgetsVLayout = QVBoxLayout()
        self._setupPreferenceWidgets()
        self.mainVLayout.addLayout(self.widgetsVLayout)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok|QDialogButtonBox.RestoreDefaults)
        self.mainVLayout.addWidget(self.buttonBox)
        if (not ISOSX) and (not ISLINUX):
            self.mainVLayout.removeWidget(self.ignoreHardlinkMatches)
            self.ignoreHardlinkMatches.setHidden(True)
    
    def _load(self, prefs, setchecked):
        # Edition-specific
        pass
    
    def _save(self, prefs, ischecked):
        # Edition-specific
        pass
    
    def load(self, prefs=None):
        if prefs is None:
            prefs = self.app.prefs
        self.filterHardnessSlider.setValue(prefs.filter_hardness)
        self.filterHardnessLabel.setNum(prefs.filter_hardness)
        setchecked = lambda cb, b: cb.setCheckState(Qt.Checked if b else Qt.Unchecked)
        setchecked(self.mixFileKindBox, prefs.mix_file_kind)
        setchecked(self.useRegexpBox, prefs.use_regexp)
        setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders)
        setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches)
        setchecked(self.debugModeBox, prefs.debug_mode)
        self.copyMoveDestinationComboBox.setCurrentIndex(prefs.destination_type)
        self.customCommandEdit.setText(prefs.custom_command)
        self.fontSizeSpinBox.setValue(prefs.tableFontSize)
        try:
            langindex = SUPPORTED_LANGUAGES.index(self.app.prefs.language)
        except ValueError:
            langindex = 0
        self.languageComboBox.setCurrentIndex(langindex)
        self._load(prefs, setchecked)
    
    def save(self):
        prefs = self.app.prefs
        prefs.filter_hardness = self.filterHardnessSlider.value()
        ischecked = lambda cb: cb.checkState() == Qt.Checked
        prefs.mix_file_kind = ischecked(self.mixFileKindBox)
        prefs.use_regexp = ischecked(self.useRegexpBox)
        prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox)
        prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches)
        prefs.debug_mode = ischecked(self.debugModeBox)
        prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex()
        prefs.custom_command = str(self.customCommandEdit.text())
        prefs.tableFontSize = self.fontSizeSpinBox.value()
        lang = SUPPORTED_LANGUAGES[self.languageComboBox.currentIndex()]
        oldlang = self.app.prefs.language
        if oldlang not in SUPPORTED_LANGUAGES:
            oldlang = 'en'
        if lang != oldlang:
            QMessageBox.information(self, "", tr("dupeGuru has to restart for language changes to take effect."))
        self.app.prefs.language = lang
        self._save(prefs, ischecked)
    
    #--- Events
    def buttonClicked(self, button):
        role = self.buttonBox.buttonRole(button)
        if role == QDialogButtonBox.ResetRole:
            self.resetToDefaults()
class TransactionPanel(Panel):
    FIELDS = [
        ("dateEdit", "date"),
        ("descriptionEdit", "description"),
        ("payeeEdit", "payee"),
        ("checkNoEdit", "checkno"),
        ("notesEdit", "notes"),
    ]

    def __init__(self, mainwindow):
        Panel.__init__(self, mainwindow)
        self.mainwindow = mainwindow
        self.model = mainwindow.model.transaction_panel
        self._setupUi()
        self.model.view = self
        self.splitTable = SplitTable(model=self.model.split_table, view=self.splitTableView)

        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.mctButton.clicked.connect(self.model.mct_balance)
        self.addSplitButton.clicked.connect(self.splitTable.model.add)
        self.removeSplitButton.clicked.connect(self.splitTable.model.delete)

    def _setupUi(self):
        self.setWindowTitle(tr("Transaction Info"))
        self.resize(462, 329)
        self.setModal(True)
        self.mainLayout = QVBoxLayout(self)
        self.tabWidget = QTabWidget(self)
        self.infoTab = QWidget()
        self.infoLayout = QVBoxLayout(self.infoTab)
        self.formLayout = QFormLayout()
        self.formLayout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        self.dateEdit = DateEdit(self.infoTab)
        self.dateEdit.setMaximumSize(QSize(120, 16777215))
        self.formLayout.addRow(tr("Date:"), self.dateEdit)
        self.descriptionEdit = DescriptionEdit(self.model.completable_edit, self.infoTab)
        self.formLayout.addRow(tr("Description:"), self.descriptionEdit)
        self.payeeEdit = PayeeEdit(self.model.completable_edit, self.infoTab)
        self.formLayout.addRow(tr("Payee:"), self.payeeEdit)
        self.checkNoEdit = QLineEdit(self.infoTab)
        self.checkNoEdit.setMaximumSize(QSize(120, 16777215))
        self.formLayout.addRow(tr("Check #:"), self.checkNoEdit)
        self.infoLayout.addLayout(self.formLayout)
        self.amountLabel = QLabel(tr("Transfers:"), self.infoTab)
        self.infoLayout.addWidget(self.amountLabel)
        self.splitTableView = TableView(self.infoTab)
        self.splitTableView.setAcceptDrops(True)
        self.splitTableView.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed)
        self.splitTableView.setDragEnabled(True)
        self.splitTableView.setDragDropMode(QAbstractItemView.InternalMove)
        self.splitTableView.setSelectionMode(QAbstractItemView.SingleSelection)
        self.splitTableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.splitTableView.horizontalHeader().setDefaultSectionSize(40)
        self.splitTableView.verticalHeader().setVisible(False)
        self.splitTableView.verticalHeader().setDefaultSectionSize(18)
        self.infoLayout.addWidget(self.splitTableView)
        self.mctButtonsLayout = QHBoxLayout()
        self.mctButtonsLayout.setMargin(0)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.mctButtonsLayout.addItem(spacerItem)
        self.mctButton = QPushButton(tr("Multi-currency balance"), self.infoTab)
        self.mctButtonsLayout.addWidget(self.mctButton)
        self.addSplitButton = QPushButton(self.infoTab)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/plus_8"), QIcon.Normal, QIcon.Off)
        self.addSplitButton.setIcon(icon)
        self.mctButtonsLayout.addWidget(self.addSplitButton)
        self.removeSplitButton = QPushButton(self.infoTab)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(":/minus_8"), QIcon.Normal, QIcon.Off)
        self.removeSplitButton.setIcon(icon1)
        self.mctButtonsLayout.addWidget(self.removeSplitButton)
        self.infoLayout.addLayout(self.mctButtonsLayout)
        self.tabWidget.addTab(self.infoTab, tr("Info"))
        self.notesTab = QWidget()
        self.notesLayout = QVBoxLayout(self.notesTab)
        self.notesEdit = QPlainTextEdit(self.notesTab)
        self.notesLayout.addWidget(self.notesEdit)
        self.tabWidget.addTab(self.notesTab, tr("Notes"))
        self.tabWidget.setCurrentIndex(0)
        self.mainLayout.addWidget(self.tabWidget)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Save)
        self.mainLayout.addWidget(self.buttonBox)

    def _loadFields(self):
        Panel._loadFields(self)
        self.tabWidget.setCurrentIndex(0)

    # --- model --> view
    def refresh_for_multi_currency(self):
        self.mctButton.setEnabled(self.model.is_multi_currency)
class QgsTextAnnotationDialog(QDialog):
    def __init__(self, item):
        QDialog.__init__(self)
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName(("gridLayout"))
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName(("horizontalLayout"))
        self.mFontComboBox = QFontComboBox(self)
        self.mFontComboBox.setObjectName(("mFontComboBox"))
        self.horizontalLayout.addWidget(self.mFontComboBox)
        spacerItem = QSpacerItem(38, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.mFontSizeSpinBox = QSpinBox(self)
        self.mFontSizeSpinBox.setObjectName(("mFontSizeSpinBox"))
        self.horizontalLayout.addWidget(self.mFontSizeSpinBox)
        self.mBoldPushButton = QPushButton(self)
        self.mBoldPushButton.setMinimumSize(QSize(50, 0))
        self.mBoldPushButton.setCheckable(True)
        self.mBoldPushButton.setObjectName(("mBoldPushButton"))
        self.horizontalLayout.addWidget(self.mBoldPushButton)
        self.mItalicsPushButton = QPushButton(self)
        self.mItalicsPushButton.setMinimumSize(QSize(50, 0))
        self.mItalicsPushButton.setCheckable(True)
        self.mItalicsPushButton.setObjectName(("mItalicsPushButton"))
        self.horizontalLayout.addWidget(self.mItalicsPushButton)
        self.mFontColorButton = QgsColorButton(self)
        self.mFontColorButton.setText((""))
        self.mFontColorButton.setAutoDefault(False)
        self.mFontColorButton.setObjectName(("mFontColorButton"))
        self.horizontalLayout.addWidget(self.mFontColorButton)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.mButtonBox = QDialogButtonBox(self)
        self.mButtonBox.setOrientation(Qt.Horizontal)
        self.mButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.mButtonBox.setObjectName(("mButtonBox"))
        self.gridLayout.addWidget(self.mButtonBox, 3, 0, 1, 1)
        self.mTextEdit = QTextEdit(self)
        self.mTextEdit.setObjectName(("mTextEdit"))
        self.gridLayout.addWidget(self.mTextEdit, 1, 0, 1, 1)
        self.mStackedWidget = QStackedWidget(self)
        self.mStackedWidget.setObjectName(("mStackedWidget"))
        self.page = QWidget()
        self.page.setObjectName(("page"))
        self.mStackedWidget.addWidget(self.page)
        self.page_2 = QWidget()
        self.page_2.setObjectName(("page_2"))
        self.mStackedWidget.addWidget(self.page_2)
        self.gridLayout.addWidget(self.mStackedWidget, 2, 0, 1, 1)
        self.setLayout(self.gridLayout)
        
        self.mStackedWidget.setCurrentIndex(0)
        QObject.connect(self.mButtonBox, SIGNAL(("accepted()")), self.accept)
        QObject.connect(self.mButtonBox, SIGNAL(("rejected()")), self.reject)
        
        self.setTabOrder(self.mFontComboBox, self.mFontSizeSpinBox)
        self.setTabOrder(self.mFontSizeSpinBox, self.mBoldPushButton)
        self.setTabOrder(self.mBoldPushButton, self.mItalicsPushButton)
        self.setTabOrder(self.mItalicsPushButton, self.mFontColorButton)
        self.setTabOrder(self.mFontColorButton, self.mTextEdit)
        self.setTabOrder(self.mTextEdit, self.mButtonBox)
        
        self.setWindowTitle("Annotation text")
        self.mBoldPushButton.setText("B")
        self.mItalicsPushButton.setText("I")
        
        self.mTextDocument = None
        self.mItem = item
        self.mEmbeddedWidget = QgsAnnotationWidget(self, self.mItem )
        self.mEmbeddedWidget.show()
        self.mStackedWidget.addWidget( self.mEmbeddedWidget )
        self.mStackedWidget.setCurrentWidget( self.mEmbeddedWidget )
        if ( self.mItem != None ):
            self.mTextDocument = self.mItem.document()
            self.mTextEdit.setDocument( self.mTextDocument )
        self.mFontColorButton.setColorDialogTitle(  "Select font color"  )
        self.mFontColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
        self.setCurrentFontPropertiesToGui()
        QObject.connect( self.mButtonBox, SIGNAL("accepted()"), self.applyTextToItem)
#         QObject.connect( self.mFontComboBox, SIGNAL( "currentFontChanged(QFont())"), self.changeCurrentFormat)
        self.mFontComboBox.currentFontChanged.connect(self.changeCurrentFormat)
        QObject.connect( self.mFontSizeSpinBox, SIGNAL( "valueChanged( int )" ), self.changeCurrentFormat ) 
        QObject.connect( self.mBoldPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mItalicsPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mTextEdit, SIGNAL( "cursorPositionChanged()" ), self.setCurrentFontPropertiesToGui )
        
#         QObject.connect( self.mButtonBox, SIGNAL( "accepted()" ), self.applySettingsToItem)
        deleteButton = QPushButton( "Delete" )
        QObject.connect( deleteButton, SIGNAL( "clicked()" ), self.deleteItem )
        self.mButtonBox.addButton( deleteButton, QDialogButtonBox.RejectRole )
    def applyTextToItem(self):
        if ( self.mItem  != None and self.mTextDocument !=None ):
            if ( self.mEmbeddedWidget != None):
                self.mEmbeddedWidget.apply()
            self.mItem.setDocument( self.mTextDocument )
            self.mItem.update()
    def changeCurrentFormat(self):
        newFont = QFont()
        newFont.setFamily( self.mFontComboBox.currentFont().family() )
        #bold
        if ( self.mBoldPushButton.isChecked() ):
            newFont.setBold( True )
        else:
            newFont.setBold( False )
        #italic
        if ( self.mItalicsPushButton.isChecked() ):
            newFont.setItalic( True )
        else:
            newFont.setItalic( False )
        #size
        newFont.setPointSize( self.mFontSizeSpinBox.value() )
        self.mTextEdit.setCurrentFont( newFont )
        #color
        self.mTextEdit.setTextColor( self.mFontColorButton.color() )
        
    def on_mFontColorButton_colorChanged(self, color ):
        self.changeCurrentFormat()
    def setCurrentFontPropertiesToGui(self):
        self.blockAllSignals( True )
        currentFont = self.mTextEdit.currentFont()
        self.mFontComboBox.setCurrentFont( currentFont )
        self.mFontSizeSpinBox.setValue( currentFont.pointSize() )
        self.mBoldPushButton.setChecked( currentFont.bold() )
        self.mItalicsPushButton.setChecked( currentFont.italic() )
        self.mFontColorButton.setColor( self.mTextEdit.textColor() )
        self.blockAllSignals( False )
        
    def blockAllSignals(self, block ):
        self.mFontComboBox.blockSignals( block )
        self.mFontSizeSpinBox.blockSignals( block )
        self.mBoldPushButton.blockSignals( block )
        self.mItalicsPushButton.blockSignals( block )
        self.mFontColorButton.blockSignals( block )
    
    def deleteItem(self):
        scene = self.mItem.scene()
        if ( scene != None ):
            scene.removeItem( self.mItem )
        self.mItem = None
Beispiel #48
0
class EkdProgress(QDialog) :
    """EkdProgress est une boite de dialog contenant l'état de la progression de chaque processus"""

    def __init__(self, parent=None, totfile=0):
        super(EkdProgress, self).__init__(parent)
        self.setupUi(self)
        self.barProgress.setMaximum(totfile)
        self.fermer.setEnabled(False)
        self.totframe=totfile
        self.value = 0
        self.connect(self.fermer,SIGNAL("clicked()"),self.tmpclose)

    def upProgress(self) :
        self.value += 1
        self.barProgress.setValue(self.value)

    def addText(self, text) :
        self.infoText.append(QString(text))

    def tmpclose(self) :
        self.emit(SIGNAL("cleantmp"))
        self.close()

    def setupUi(self, showprogress):
        showprogress.setObjectName("showprogress")
        showprogress.resize(335, 310)
        self.verticalLayout = QVBoxLayout(showprogress)
        self.verticalLayout.setObjectName("verticalLayout")
        self.barProgress = QProgressBar(showprogress)
        self.barProgress.setProperty("value", QVariant(0))
        self.barProgress.setObjectName("barProgress")
        self.verticalLayout.addWidget(self.barProgress)
        self.infoText = QTextEdit(showprogress)
        palette = QPalette()
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Text, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Base, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Text, brush)
        brush = QBrush(QColor(0, 0, 0))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Base, brush)
        brush = QBrush(QColor(126, 125, 124))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Text, brush)
        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Base, brush)
        self.infoText.setPalette(palette)
        self.infoText.setObjectName("infoText")
        self.verticalLayout.addWidget(self.infoText)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.fermer = QPushButton(showprogress)
        self.fermer.setObjectName("fermer")
        self.horizontalLayout.addWidget(self.fermer)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.retranslateUi(showprogress)
        QMetaObject.connectSlotsByName(showprogress)

    def retranslateUi(self, showprogress):
        showprogress.setWindowTitle(_(u"Progression"))
        self.barProgress.setToolTip(_(u"Progression de l\'encodage"))
        self.infoText.setToolTip(_(u"Messages"))
        self.fermer.setToolTip(_(u"Fermer la fenêtre"))
        self.fermer.setText(_(u"Fermer"))
Beispiel #49
0
class RadioBox(QWidget):
    def __init__(self, parent=None, items=None, spread=True):
        # If spread is False, insert a spacer in the layout so that the items don't use all the
        # space they're given but rather align left.
        if items is None:
            items = []
        QWidget.__init__(self, parent)
        self._buttons = []
        self._labels = items
        self._selected_index = 0
        self._spacer = horizontalSpacer() if not spread else None
        self._layout = QHBoxLayout(self)
        self._update_buttons()

    #--- Private
    def _update_buttons(self):
        if self._spacer is not None:
            self._layout.removeItem(self._spacer)
        to_remove = self._buttons[len(self._labels):]
        for button in to_remove:
            self._layout.removeWidget(button)
            button.setParent(None)
        del self._buttons[len(self._labels):]
        to_add = self._labels[len(self._buttons):]
        for _ in to_add:
            button = QRadioButton(self)
            self._buttons.append(button)
            self._layout.addWidget(button)
            button.toggled.connect(self.buttonToggled)
        if self._spacer is not None:
            self._layout.addItem(self._spacer)
        if not self._buttons:
            return
        for button, label in zip(self._buttons, self._labels):
            button.setText(label)
        self._update_selection()

    def _update_selection(self):
        self._selected_index = max(
            0, min(self._selected_index,
                   len(self._buttons) - 1))
        selected = self._buttons[self._selected_index]
        selected.setChecked(True)

    #--- Event Handlers
    def buttonToggled(self):
        for i, button in enumerate(self._buttons):
            if button.isChecked():
                self._selected_index = i
                self.itemSelected.emit(i)
                break

    #--- Signals
    itemSelected = pyqtSignal(int)

    #--- Properties
    @property
    def buttons(self):
        return self._buttons[:]

    @property
    def items(self):
        return self._labels[:]

    @items.setter
    def items(self, value):
        self._labels = value
        self._update_buttons()

    @property
    def selected_index(self):
        return self._selected_index

    @selected_index.setter
    def selected_index(self, value):
        self._selected_index = value
        self._update_selection()
Beispiel #50
0
class DirectoriesDialog(QMainWindow):
    def __init__(self, parent, app):
        QMainWindow.__init__(self, None)
        self.app = app
        self.lastAddedFolder = platform.INITIAL_FOLDER_IN_DIALOGS
        self.recentFolders = Recent(self.app, 'recentFolders')
        self._setupUi()
        self.directoriesModel = DirectoriesModel(self.app.model.directory_tree,
                                                 view=self.treeView)
        self.directoriesDelegate = DirectoriesDelegate()
        self.treeView.setItemDelegate(self.directoriesDelegate)
        self._setupColumns()
        self.app.recentResults.addMenu(self.menuLoadRecent)
        self.app.recentResults.addMenu(self.menuRecentResults)
        self.recentFolders.addMenu(self.menuRecentFolders)
        self._updateAddButton()
        self._updateRemoveButton()
        self._updateLoadResultsButton()
        self._setupBindings()

    def _setupBindings(self):
        self.scanButton.clicked.connect(self.scanButtonClicked)
        self.loadResultsButton.clicked.connect(self.actionLoadResults.trigger)
        self.addFolderButton.clicked.connect(self.actionAddFolder.trigger)
        self.removeFolderButton.clicked.connect(self.removeFolderButtonClicked)
        self.treeView.selectionModel().selectionChanged.connect(
            self.selectionChanged)
        self.app.recentResults.itemsChanged.connect(
            self._updateLoadResultsButton)
        self.recentFolders.itemsChanged.connect(self._updateAddButton)
        self.recentFolders.mustOpenItem.connect(self.app.model.add_directory)
        self.directoriesModel.foldersAdded.connect(
            self.directoriesModelAddedFolders)
        self.app.willSavePrefs.connect(self.appWillSavePrefs)

    def _setupActions(self):
        # (name, shortcut, icon, desc, func)
        ACTIONS = [
            ('actionLoadResults', 'Ctrl+L', '', tr("Load Results..."),
             self.loadResultsTriggered),
            ('actionShowResultsWindow', '', '', tr("Results Window"),
             self.app.showResultsWindow),
            ('actionAddFolder', '', '', tr("Add Folder..."),
             self.addFolderTriggered),
        ]
        createActions(ACTIONS, self)

    def _setupMenu(self):
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 42, 22))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setTitle(tr("File"))
        self.menuView = QMenu(self.menubar)
        self.menuView.setTitle(tr("View"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setTitle(tr("Help"))
        self.menuLoadRecent = QMenu(self.menuFile)
        self.menuLoadRecent.setTitle(tr("Load Recent Results"))
        self.setMenuBar(self.menubar)

        self.menuFile.addAction(self.actionLoadResults)
        self.menuFile.addAction(self.menuLoadRecent.menuAction())
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.app.actionQuit)
        self.menuView.addAction(self.app.actionPreferences)
        self.menuView.addAction(self.actionShowResultsWindow)
        self.menuView.addAction(self.app.actionIgnoreList)
        self.menuHelp.addAction(self.app.actionShowHelp)
        self.menuHelp.addAction(self.app.actionRegister)
        self.menuHelp.addAction(self.app.actionCheckForUpdate)
        self.menuHelp.addAction(self.app.actionOpenDebugLog)
        self.menuHelp.addAction(self.app.actionAbout)

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuView.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        # Recent folders menu
        self.menuRecentFolders = QMenu()
        self.menuRecentFolders.addAction(self.actionAddFolder)
        self.menuRecentFolders.addSeparator()

        # Recent results menu
        self.menuRecentResults = QMenu()
        self.menuRecentResults.addAction(self.actionLoadResults)
        self.menuRecentResults.addSeparator()

    def _setupUi(self):
        self.setWindowTitle(self.app.NAME)
        self.resize(420, 338)
        self.centralwidget = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.promptLabel = QLabel(
            tr("Select folders to scan and press \"Scan\"."),
            self.centralwidget)
        self.verticalLayout.addWidget(self.promptLabel)
        self.treeView = QTreeView(self.centralwidget)
        self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.treeView.setAcceptDrops(True)
        triggers = QAbstractItemView.DoubleClicked|QAbstractItemView.EditKeyPressed\
            |QAbstractItemView.SelectedClicked
        self.treeView.setEditTriggers(triggers)
        self.treeView.setDragDropOverwriteMode(True)
        self.treeView.setDragDropMode(QAbstractItemView.DropOnly)
        self.treeView.setUniformRowHeights(True)
        self.verticalLayout.addWidget(self.treeView)
        self.horizontalLayout = QHBoxLayout()
        self.removeFolderButton = QPushButton(self.centralwidget)
        self.removeFolderButton.setIcon(QIcon(QPixmap(":/minus")))
        self.removeFolderButton.setShortcut("Del")
        self.horizontalLayout.addWidget(self.removeFolderButton)
        self.addFolderButton = QPushButton(self.centralwidget)
        self.addFolderButton.setIcon(QIcon(QPixmap(":/plus")))
        self.horizontalLayout.addWidget(self.addFolderButton)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.loadResultsButton = QPushButton(self.centralwidget)
        self.loadResultsButton.setText(tr("Load Results"))
        self.horizontalLayout.addWidget(self.loadResultsButton)
        self.scanButton = QPushButton(self.centralwidget)
        self.scanButton.setText(tr("Scan"))
        self.scanButton.setDefault(True)
        self.horizontalLayout.addWidget(self.scanButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.setCentralWidget(self.centralwidget)

        self._setupActions()
        self._setupMenu()

        if self.app.prefs.directoriesWindowRect is not None:
            self.setGeometry(self.app.prefs.directoriesWindowRect)
        else:
            moveToScreenCenter(self)

    def _setupColumns(self):
        header = self.treeView.header()
        header.setStretchLastSection(False)
        header.setResizeMode(0, QHeaderView.Stretch)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.resizeSection(1, 100)

    def _updateAddButton(self):
        if self.recentFolders.isEmpty():
            self.addFolderButton.setMenu(None)
        else:
            self.addFolderButton.setMenu(self.menuRecentFolders)

    def _updateRemoveButton(self):
        indexes = self.treeView.selectedIndexes()
        if not indexes:
            self.removeFolderButton.setEnabled(False)
            return
        self.removeFolderButton.setEnabled(True)

    def _updateLoadResultsButton(self):
        if self.app.recentResults.isEmpty():
            self.loadResultsButton.setMenu(None)
        else:
            self.loadResultsButton.setMenu(self.menuRecentResults)

    #--- QWidget overrides
    def closeEvent(self, event):
        event.accept()
        if self.app.model.results.is_modified:
            title = tr("Unsaved results")
            msg = tr("You have unsaved results, do you really want to quit?")
            if not self.app.confirm(title, msg):
                event.ignore()
        if event.isAccepted():
            QApplication.quit()

    #--- Events
    def addFolderTriggered(self):
        title = tr("Select a folder to add to the scanning list")
        flags = QFileDialog.ShowDirsOnly
        dirpath = str(
            QFileDialog.getExistingDirectory(self, title, self.lastAddedFolder,
                                             flags))
        if not dirpath:
            return
        self.lastAddedFolder = dirpath
        self.app.model.add_directory(dirpath)
        self.recentFolders.insertItem(dirpath)

    def appWillSavePrefs(self):
        self.app.prefs.directoriesWindowRect = self.geometry()

    def directoriesModelAddedFolders(self, folders):
        for folder in folders:
            self.recentFolders.insertItem(folder)

    def loadResultsTriggered(self):
        title = tr("Select a results file to load")
        files = ';;'.join(
            [tr("dupeGuru Results (*.dupeguru)"),
             tr("All Files (*.*)")])
        destination = QFileDialog.getOpenFileName(self, title, '', files)
        if destination:
            self.app.model.load_from(destination)
            self.app.recentResults.insertItem(destination)

    def removeFolderButtonClicked(self):
        self.directoriesModel.model.remove_selected()

    def scanButtonClicked(self):
        if self.app.model.results.is_modified:
            title = tr("Start a new scan")
            msg = tr(
                "You have unsaved results, do you really want to continue?")
            if not self.app.confirm(title, msg):
                return
        self.app.model.start_scanning()

    def selectionChanged(self, selected, deselected):
        self._updateRemoveButton()
class PreferencesDialog(PreferencesDialogBase):
    def __init__(self, parent, app):
        PreferencesDialogBase.__init__(self, parent, app)

        self.scanTypeComboBox.currentIndexChanged[int].connect(self.scanTypeChanged)

    def _setupPreferenceWidgets(self):
        scanTypeLabels = [
            tr("Filename"),
            tr("Filename - Fields"),
            tr("Filename - Fields (No Order)"),
            tr("Tags"),
            tr("Contents"),
            tr("Audio Contents"),
        ]
        self._setupScanTypeBox(scanTypeLabels)
        self._setupFilterHardnessBox()
        self.widgetsVLayout.addLayout(self.filterHardnessHLayout)
        self.widget = QWidget(self)
        self.widget.setMinimumSize(QSize(0, 40))
        self.verticalLayout_4 = QVBoxLayout(self.widget)
        self.verticalLayout_4.setSpacing(0)
        self.verticalLayout_4.setMargin(0)
        self.label_6 = QLabel(self.widget)
        self.label_6.setText(tr("Tags to scan:"))
        self.verticalLayout_4.addWidget(self.label_6)
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setSpacing(0)
        spacerItem1 = QSpacerItem(15, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self._setupAddCheckbox("tagTrackBox", tr("Track"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagTrackBox)
        self._setupAddCheckbox("tagArtistBox", tr("Artist"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagArtistBox)
        self._setupAddCheckbox("tagAlbumBox", tr("Album"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagAlbumBox)
        self._setupAddCheckbox("tagTitleBox", tr("Title"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagTitleBox)
        self._setupAddCheckbox("tagGenreBox", tr("Genre"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagGenreBox)
        self._setupAddCheckbox("tagYearBox", tr("Year"), self.widget)
        self.horizontalLayout_2.addWidget(self.tagYearBox)
        self.verticalLayout_4.addLayout(self.horizontalLayout_2)
        self.widgetsVLayout.addWidget(self.widget)
        self._setupAddCheckbox("wordWeightingBox", tr("Word weighting"))
        self.widgetsVLayout.addWidget(self.wordWeightingBox)
        self._setupAddCheckbox("matchSimilarBox", tr("Match similar words"))
        self.widgetsVLayout.addWidget(self.matchSimilarBox)
        self._setupAddCheckbox("mixFileKindBox", tr("Can mix file kind"))
        self.widgetsVLayout.addWidget(self.mixFileKindBox)
        self._setupAddCheckbox("useRegexpBox", tr("Use regular expressions when filtering"))
        self.widgetsVLayout.addWidget(self.useRegexpBox)
        self._setupAddCheckbox("removeEmptyFoldersBox", tr("Remove empty folders on delete or move"))
        self.widgetsVLayout.addWidget(self.removeEmptyFoldersBox)
        self._setupAddCheckbox("ignoreHardlinkMatches", tr("Ignore duplicates hardlinking to the same file"))
        self.widgetsVLayout.addWidget(self.ignoreHardlinkMatches)
        self._setupAddCheckbox("debugModeBox", tr("Debug mode (restart required)"))
        self.widgetsVLayout.addWidget(self.debugModeBox)
        self._setupBottomPart()

    def _load(self, prefs, setchecked):
        scan_type_index = SCAN_TYPE_ORDER.index(prefs.scan_type)
        self.scanTypeComboBox.setCurrentIndex(scan_type_index)
        setchecked(self.tagTrackBox, prefs.scan_tag_track)
        setchecked(self.tagArtistBox, prefs.scan_tag_artist)
        setchecked(self.tagAlbumBox, prefs.scan_tag_album)
        setchecked(self.tagTitleBox, prefs.scan_tag_title)
        setchecked(self.tagGenreBox, prefs.scan_tag_genre)
        setchecked(self.tagYearBox, prefs.scan_tag_year)
        setchecked(self.matchSimilarBox, prefs.match_similar)
        setchecked(self.wordWeightingBox, prefs.word_weighting)

    def _save(self, prefs, ischecked):
        prefs.scan_type = SCAN_TYPE_ORDER[self.scanTypeComboBox.currentIndex()]
        prefs.scan_tag_track = ischecked(self.tagTrackBox)
        prefs.scan_tag_artist = ischecked(self.tagArtistBox)
        prefs.scan_tag_album = ischecked(self.tagAlbumBox)
        prefs.scan_tag_title = ischecked(self.tagTitleBox)
        prefs.scan_tag_genre = ischecked(self.tagGenreBox)
        prefs.scan_tag_year = ischecked(self.tagYearBox)
        prefs.match_similar = ischecked(self.matchSimilarBox)
        prefs.word_weighting = ischecked(self.wordWeightingBox)

    def resetToDefaults(self):
        self.load(preferences.Preferences())

    # --- Events
    def scanTypeChanged(self, index):
        scan_type = SCAN_TYPE_ORDER[self.scanTypeComboBox.currentIndex()]
        word_based = scan_type in (ScanType.Filename, ScanType.Fields, ScanType.FieldsNoOrder, ScanType.Tag)
        tag_based = scan_type == ScanType.Tag
        self.filterHardnessSlider.setEnabled(word_based)
        self.matchSimilarBox.setEnabled(word_based)
        self.wordWeightingBox.setEnabled(word_based)
        self.tagTrackBox.setEnabled(tag_based)
        self.tagArtistBox.setEnabled(tag_based)
        self.tagAlbumBox.setEnabled(tag_based)
        self.tagTitleBox.setEnabled(tag_based)
        self.tagGenreBox.setEnabled(tag_based)
        self.tagYearBox.setEnabled(tag_based)
class WaterBalanceWidget(QDockWidget):
    closingWidget = pyqtSignal()

    INPUT_SERIES = INPUT_SERIES

    IN_OUT_SERIES = [
        {
            'label_name': '1D-2D flow',
            'in': ['1d_2d_in'],
            'out': ['1d_2d_in'],
            'type': '1d',
        },
        {
            'label_name': '1D-2D flow',
            'in': ['1d_2d_out'],
            'out': ['1d_2d_out'],
            'type': '2d',
        },
        {
            'label_name': '1D-2D flow (all domains)',
            # does this make sense?
            'in': ['1d_2d_in', '1d_2d_out'],
            'out': ['1d_2d_in', '1d_2d_out'],
            'type': 'NETVOL',
        },
        {
            'label_name': 'net change in storage',
            'in': ['d_2d_vol'],
            'out': ['d_2d_vol'],
            'type': '2d',
        },
        {
            'label_name': 'net change in storage',
            'in': ['d_1d_vol'],
            'out': ['d_1d_vol'],
            'type': '1d',
        },
        {
            'label_name': 'net change in storage',
            'in': ['d_2d_groundwater_vol'],
            'out': ['d_2d_groundwater_vol'],
            'type': '2d_groundwater',
        },
        {
            'label_name': 'leakage',
            'in': ['leak'],
            'out': ['leak'],
            'type': '2d_groundwater',
        },
        {
            'label_name': 'simple infiltration',
            'in': ['infiltration_rate_simple'],
            'out': ['infiltration_rate_simple'],
            'type': '2d',
        },
        {
            'label_name': '2D flow',
            'in': ['2d_in'],
            'out': ['2d_out'],
            'type': '2d',
        },
        {
            'label_name': '1D flow',
            'in': ['1d_in'],
            'out': ['1d_out'],
            'type': '1d',
        },
        {
            'label_name': '2D groundwater flow',
            'in': ['2d_groundwater_in'],
            'out': ['2d_groundwater_out'],
            'type': '2d_groundwater',
        },
        {
            'label_name': '2D laterals',
            'in': ['lat_2d'],
            'out': ['lat_2d'],
            'type': '2d',
        },
        {
            'label_name': '1D laterals',
            'in': ['lat_1d'],
            'out': ['lat_1d'],
            'type': '1d',
        },
        {
            'label_name': '2D boundaries',
            'in': ['2d_bound_in'],
            'out': ['2d_bound_out'],
            'type': '2d',
        },
        {
            'label_name': '1D boundaries',
            'in': ['1d_bound_in'],
            'out': ['1d_bound_out'],
            'type': '1d',
        },
        {
            'label_name': '1D-2D exchange',
            'in': ['2d_to_1d_pos'],
            'out': ['2d_to_1d_neg'],
            'type': '1d_2d',
        },
        {
            'label_name': '1D inflow from rain',
            'in': ['inflow'],
            'out': ['inflow'],
            'type': '1d',
        },
        {
            'label_name': 'infiltration/exfiltration (domain exchange)',
            # NOTE: for the argument why pos is out and neg is in, see the
            # comment in ``WaterBalanceCalculation.get_aggregated_flows``
            'in': ['2d_vertical_infiltration_neg'],
            'out': ['2d_vertical_infiltration_pos'],
            'type': '2d_vert',
        },
        {
            'label_name': 'change in storage',
            'in': ['d_2d_vol', 'd_2d_groundwater_vol', 'd_1d_vol'],
            'out': ['d_2d_vol', 'd_2d_groundwater_vol', 'd_1d_vol'],
            'type': 'NETVOL',
        },
        {
            'label_name': 'pump',
            'in': ['pump_in'],
            'out': ['pump_out'],
            'type': '1d',
        },
        {
            'label_name': 'rain',
            'in': ['rain'],
            'out': ['rain'],
            'type': '2d',
        }
    ]

    def __init__(self,
                 parent=None,
                 iface=None,
                 ts_datasource=None,
                 wb_calc=None):
        """Constructor."""
        super(WaterBalanceWidget, self).__init__(parent)

        self.aggregation_warning_issued_on_start = False
        self.iface = iface
        self.ts_datasource = ts_datasource
        self.calc = wb_calc

        # setup ui
        self.setup_ui(self)

        self.model = WaterbalanceItemModel()
        self.wb_item_table.setModel(self.model)
        self.plot_widget.setModel(self.model)

        # link tool
        self.polygon_tool = PolygonDrawTool(self.iface.mapCanvas(),
                                            self.select_polygon_button,
                                            self.on_polygon_ready)

        # fill comboboxes with selections
        self.modelpart_combo_box.insertItems(0, ['1d 2d', '1d', '2d'])
        #  self.modelpart_combo_box.setCurrentIndex(0)
        self.source_nc_combo_box.insertItems(0, ['normal', 'aggregation'])
        self.sum_type_combo_box.insertItems(0, serie_settings.keys())

        self.agg_combo_box.insertItems(
            0,
            ['m3/s natural', 'm3 cumulative natural', 'm3/s', 'm3 cumulative'])

        # add listeners
        self.select_polygon_button.toggled.connect(self.toggle_polygon_button)
        self.reset_waterbalans_button.clicked.connect(self.reset_waterbalans)
        self.chart_button.clicked.connect(self.show_chart)
        # self.polygon_tool.deactivated.connect(self.update_wb)
        self.modelpart_combo_box.currentIndexChanged.connect(self.update_wb)
        self.source_nc_combo_box.currentIndexChanged.connect(self.update_wb)
        self.source_nc_combo_box.currentIndexChanged.connect(
            self.issue_warning)
        self.sum_type_combo_box.currentIndexChanged.connect(self.update_wb)
        self.agg_combo_box.currentIndexChanged.connect(self.update_wb)
        self.wb_item_table.hoverEnterRow.connect(
            self.hover_enter_map_visualization)
        self.wb_item_table.hoverExitAllRows.connect(
            self.hover_exit_map_visualization)

        # TODO: is this a good default?
        # initially turn on tool
        self.select_polygon_button.toggle()

        self.__current_calc = None  # cache the results of calculation

    def show_chart(self):
        if not self._current_calc:
            return
        ts, ts_series = self._current_calc

        io_series_net = [
            x for x in self.IN_OUT_SERIES if
            (x['type'] in ['2d', '1d_2d', '2d_vert', '2d_groundwater', '1d']
             and 'storage' not in x['label_name']
             and 'exchange' not in x['label_name']
             and x['label_name'] != '1D-2D flow') or x['type'] == 'NETVOL'
        ]

        io_series_2d = [
            x for x in self.IN_OUT_SERIES
            if x['type'] in ['2d', '1d_2d', '2d_vert']
        ]

        io_series_2d_groundwater = [
            x for x in self.IN_OUT_SERIES
            if x['type'] in ['2d_groundwater', '2d_vert']
        ]

        io_series_1d = [
            x for x in self.IN_OUT_SERIES if x['type'] in ['1d', '1d_2d']
        ]

        # get timeseries x range in plot widget
        viewbox_state = self.plot_widget.getPlotItem().getViewBox().getState()
        view_range = viewbox_state['viewRange']
        t1, t2 = view_range[0]

        bm_net = BarManager(io_series_net)
        bm_2d = BarManager(io_series_2d)
        bm_2d_groundwater = BarManager(io_series_2d_groundwater)
        bm_1d = BarManager(io_series_1d)

        bm_net.calc_balance(ts, ts_series, t1, t2, net=True)
        bm_2d.calc_balance(ts, ts_series, t1, t2)
        bm_2d_groundwater.calc_balance(
            ts,
            ts_series,
            t1,
            t2,
            invert=['infiltration/exfiltration (domain exchange)'])
        bm_1d.calc_balance(ts, ts_series, t1, t2, invert=['1D-2D exchange'])

        # init figure
        plt.close()
        plt.figure(1)  # TODO: what does this do?
        plt.suptitle("Water balance from t=%.2f to t=%.2f" % (t1, t2))

        # prevent clipping of tick-labels, among others
        plt.subplots_adjust(bottom=.3,
                            top=.9,
                            left=.125,
                            right=.9,
                            hspace=1,
                            wspace=.4)

        pattern = '//'

        # #####
        # Net #
        # #####

        plt.subplot(221)
        plt.axhline(color='black', lw=.5)
        bar_in = plt.bar(bm_net.x, bm_net.end_balance_in, label='In')
        bar_out = plt.bar(bm_net.x, bm_net.end_balance_out, label='Out')
        bar_in[-1].set_hatch(pattern)
        bar_out[-1].set_hatch(pattern)
        plt.xticks(bm_net.x, bm_net.xlabels, rotation=45, ha='right')
        plt.title('Net water balance')
        plt.ylabel(r'volume ($m^3$)')
        plt.legend()

        # ####
        # 2D #
        # ####

        # this axes object will be shared by the other subplots to give them
        # the same y alignment
        ax1 = plt.subplot(234)

        plt.axhline(color='black', lw=.5)
        bar_in = plt.bar(bm_2d.x, bm_2d.end_balance_in, label='In')
        bar_out = plt.bar(bm_2d.x, bm_2d.end_balance_out, label='Out')
        bar_in[-1].set_hatch(pattern)
        bar_out[-1].set_hatch(pattern)
        plt.xticks(bm_2d.x, bm_2d.xlabels, rotation=45, ha='right')
        plt.title('2D surface water domain')
        plt.ylabel(r'volume ($m^3$)')
        plt.legend()

        # ################
        # 2D groundwater #
        # ################

        plt.subplot(235, sharey=ax1)
        plt.axhline(color='black', lw=.5)
        bar_in = plt.bar(bm_2d_groundwater.x,
                         bm_2d_groundwater.end_balance_in,
                         label='In')
        bar_out = plt.bar(bm_2d_groundwater.x,
                          bm_2d_groundwater.end_balance_out,
                          label='Out')
        bar_in[-1].set_hatch(pattern)
        bar_out[-1].set_hatch(pattern)
        plt.xticks(bm_2d_groundwater.x,
                   bm_2d_groundwater.xlabels,
                   rotation=45,
                   ha='right')
        plt.title('2D groundwater domain')
        plt.ylabel(r'volume ($m^3$)')
        plt.legend()

        # ####
        # 1D #
        # ####

        plt.subplot(236, sharey=ax1)
        plt.axhline(color='black', lw=.5)
        bar_in = plt.bar(bm_1d.x, bm_1d.end_balance_in, label='In')
        bar_out = plt.bar(bm_1d.x, bm_1d.end_balance_out, label='Out')
        bar_in[-1].set_hatch(pattern)
        bar_out[-1].set_hatch(pattern)
        plt.xticks(bm_1d.x, bm_1d.xlabels, rotation=45, ha='right')
        plt.title('1D network domain')
        plt.ylabel(r'volume ($m^3$)')
        plt.legend()

        plt.show()

    def hover_enter_map_visualization(self, name):
        """On hover rubberband visualisation using the table item name.

        Uses the cached self.qgs_lines/self.qgs_points.
        """
        if self.select_polygon_button.isChecked():
            # highlighting when drawing the polygon doesn't look right.
            # this is the best solution I can think of atm...
            return
        types_2d_line = [
            '2d flow',
        ]
        types_2d_node = [
            'volumeverandering 2d',
        ]
        # TODO 1: generate this dict

        # TODO 2: 1d-2d flow isn't completely correct for 2d
        # and 1d flow because those only only take either 1d_2d_in or
        # 1d_2d_out and we're using the aggregated 1d_2d_intersected

        # TODO 3: using the name as key is INCREDIBLY error prone: one
        # spelling mistake or a change in sum_configs and it doesn't work
        # anymore, and because we also catch the KeyErrors you won't even
        # notice. NEEDS TO BE FIXED

        NAME_TO_LINE_TYPES_ALLES = {
            '2d flow': ['2d'],
            '2d boundaries': ['2d_bound'],
            '1d flow': ['1d'],
            '1d boundaries': ['1d_bound'],
            '1d-2d uitwisseling': ['1d_2d'],
            # TODO: '1d_2d_intersected' and 'pump_or_whatever' are magic
            # strings that we ad-hoc created in the
            # prepare_and_visualize_selection function.
            # A better solution would be nice...
            '1d-2d flow': ['1d_2d_intersected'],
            'pompen': ['pump_or_whatever'],
            '2d groundwater flow': ['2d_groundwater'],
        }
        NAME_TO_LINE_TYPES_HOOFDSTROMEN = {
            '2d flow': ['2d', '2d_bound', '1d_2d_intersected'],
            '1d flow':
            ['1d', 'pump_or_whatever', '1d_bound', '1d_2d_intersected'],
            '1d-2d uitwisseling': ['1d_2d'],
            '2d groundwater flow': ['2d_groundwater'],
        }
        NAME_TO_NODE_TYPES = {
            'volumeverandering': ['1d', '2d', '2d_groundwater'],
            'volumeverandering 2d': ['2d'],
            'volumeverandering 1d': ['1d'],
            'volumeverandering 2d grondwater': ['2d_groundwater'],
            'neerslag': ['2d'],
            'inflow 1d from rain': ['1d'],
            'lateraal 1d': ['1d'],
            'lateraal 2d': ['2d'],
            'leakage': ['2d'],
            'infiltratie': ['2d'],
            'belasting (regen en lateralen)': ['1d', '2d'],
        }

        # more hackery to fix keys defined in both 'hoofdstromen'
        # and 'alles'.
        sum_type = self.sum_type_combo_box.currentText()
        assert sum_type in ['hoofdstromen', 'alles']
        if sum_type == 'hoofdstromen':
            name_to_line_type = NAME_TO_LINE_TYPES_HOOFDSTROMEN
        elif sum_type == 'alles':
            name_to_line_type = NAME_TO_LINE_TYPES_ALLES
        else:
            raise ValueError("Unknown type %s" % sum_type)

        try:
            types_line = name_to_line_type[name]
        except KeyError:
            line_geoms = []
        else:
            line_geoms = []
            for t in types_line:
                try:
                    geoms = self.qgs_lines[t]
                except KeyError:
                    continue
                line_geoms.extend(geoms)
        try:
            types_node = NAME_TO_NODE_TYPES[name]
        except KeyError:
            point_geoms = []
        else:
            point_geoms = []
            for t in types_node:
                try:
                    geoms = self.qgs_points[t]
                except KeyError:
                    continue
                point_geoms.extend(geoms)
        self.polygon_tool.selection_vis.update(line_geoms, point_geoms)

    def hover_exit_map_visualization(self, *args):
        self.polygon_tool.selection_vis.reset()

    def on_polygon_ready(self, points):
        self.iface.mapCanvas().unsetMapTool(self.polygon_tool)

    def reset_waterbalans(self):
        self.polygon_tool.reset()

    def toggle_polygon_button(self):

        if self.select_polygon_button.isChecked():
            self.reset_waterbalans()

            self.iface.mapCanvas().setMapTool(self.polygon_tool)

            self.select_polygon_button.setText(
                _translate("DockWidget", "Gebied tekenen afronden", None))
        else:
            self.iface.mapCanvas().unsetMapTool(self.polygon_tool)
            self.update_wb()
            self.select_polygon_button.setText(
                _translate("DockWidget", "Teken nieuw gebied", None))

            if not self.aggregation_warning_issued_on_start:
                self.issue_warning()
                self.aggregation_warning_issued_on_start = True

    def redraw_wb(self):
        pass

    def update_wb(self):

        try:
            ts, graph_series = self.calc_wb(
                self.modelpart_combo_box.currentText(),
                self.source_nc_combo_box.currentText(),
                self.agg_combo_box.currentText(),
                serie_settings[self.sum_type_combo_box.currentText()])
        except self.calc.AggregationFileNotFoundError:
            QMessageBox.warning(
                None, "No aggregation file found",
                "The 'aggregation' option requires an aggregation NetCDF "
                "file with the following variables:"
                "\n\ncumulative:\n- rain\n- infiltration\n- laterals"
                "\n- leakage\n- discharge\n- pump discharge"
                "\n\npositive cumulative:\n- discharge"
                "\n\nnegative cumulative:\n- discharge")
            return

        self.model.removeRows(0, len(self.model.rows))

        self.model.ts = ts
        self.model.insertRows(graph_series['items'])

        if self.agg_combo_box.currentText() == 'm3/s':
            self.plot_widget.setLabel("left", "Debiet", "m3/s")
        elif self.agg_combo_box.currentText() == 'm3 cumulative':
            self.plot_widget.setLabel("left", "Cumulatieve debiet", "m3")
        elif self.agg_combo_box.currentText() == 'm3/s natural':
            self.plot_widget.setLabel("left", "Debiet", "m3/s")
        elif self.agg_combo_box.currentText() == 'm3 cumulative natural':
            self.plot_widget.setLabel("left", "Cumulatieve debiet", "m3")
        else:
            self.plot_widget.setLabel("left", "-", "-")

        # set labels for in and out fluxes
        text_upper = pg.TextItem(text="in", anchor=(0, 1), angle=-90)
        text_upper.setPos(0, 0)
        text_lower = pg.TextItem(text="uit", anchor=(1, 1), angle=-90)
        text_lower.setPos(0, 0)
        self.plot_widget.addItem(text_upper)
        self.plot_widget.addItem(text_lower)

    @property
    def _current_calc(self):
        return self.__current_calc

    @_current_calc.setter
    def _current_calc(self, ts_total_time_tuple):
        # NOTE: flips the sign on dvol to make things more intuitive for
        # barcharts
        ts, ts_series = ts_total_time_tuple
        ts_series = ts_series.copy()
        # indices for dvol of 2d, 1d, and groundwater
        if self.reverse_dvol_sign:
            ts_series[:, [18, 19, 25]] = -1 * ts_series[:, [18, 19, 25]]
        self.__current_calc = (ts, ts_series)

    @property
    def reverse_dvol_sign(self):
        aggregation_type = self.agg_combo_box.currentText()
        return aggregation_type in ['m3/s', 'm3 cumulative']

    def calc_wb(self, model_part, source_nc, aggregation_type, settings):
        poly_points = self.polygon_tool.points
        wb_polygon = QgsGeometry.fromPolygon([poly_points])

        lines, points, pumps = \
            self.ts_datasource.rows[0].get_result_layers()
        tr = QgsCoordinateTransform(
            self.iface.mapCanvas().mapRenderer().destinationCrs(), lines.crs())
        wb_polygon.transform(tr)

        link_ids, pump_ids = self.calc.get_incoming_and_outcoming_link_ids(
            wb_polygon, model_part)
        node_ids = self.calc.get_nodes(wb_polygon, model_part)

        ts, total_time = self.calc.get_aggregated_flows(
            link_ids,
            pump_ids,
            node_ids,
            model_part,
            source_nc,
            reverse_dvol_sign=self.reverse_dvol_sign)

        # cache data for barchart
        self._current_calc = (ts, total_time)

        graph_series = self.make_graph_series(ts, total_time, model_part,
                                              aggregation_type, settings)

        self.prepare_and_visualize_selection(link_ids, pump_ids, node_ids,
                                             lines, pumps, points)

        return ts, graph_series

    def prepare_and_visualize_selection(self,
                                        link_ids,
                                        pump_ids,
                                        node_ids,
                                        lines,
                                        pumps,
                                        points,
                                        draw_it=False):
        """Prepare dictionaries with geometries categorized by type and
        save it on self.qgs_lines and self.qgs_points.
        """
        req_filter_links = _get_request_filter(link_ids)
        req_filter_pumps = _get_request_filter(pump_ids)
        req_filter_nodes = _get_request_filter(node_ids)

        line_id_to_type = {}
        for _type, id_list in link_ids.items():
            for i in id_list:
                # we're not interested in in or out types, but for 1d_2d_in
                # and 1d_2d_out we need to employ this hack because these
                # types end in '_in'/'_out'
                if _type == '1d_2d_in' or _type == '1d_2d_out':
                    t = '1d_2d_intersected'
                else:
                    t = _type.rsplit('_out')[0].rsplit('_in')[0]

                if i not in line_id_to_type:
                    # business as usual
                    line_id_to_type[i] = t
                else:
                    # NOTE: awful hack for links that have multiple types
                    val = line_id_to_type[i]
                    if isinstance(val, list):
                        val.append(t)
                    else:
                        line_id_to_type[i] = [val, t]

        # pump_id_to_type = {}
        # for _, id_list in pump_ids.items():
        #     for i in id_list:
        #         pump_id_to_type[i] = 'all'
        node_id_to_type = {}
        for _type, id_list in node_ids.items():
            for i in id_list:
                node_id_to_type[i] = _type

        qgs_lines = {}
        qgs_points = {}
        tr_reverse = QgsCoordinateTransform(
            lines.crs(),
            self.iface.mapCanvas().mapRenderer().destinationCrs(),
        )

        # NOTE: getting all features again isn't efficient because they're
        # already calculated in WaterBalanceCalculation, but w/e
        for feat in _get_feature_iterator(lines, req_filter_links):
            geom = feat.geometry()
            geom.transform(tr_reverse)
            _type = line_id_to_type[feat['id']]

            if isinstance(_type, list):
                # NOTE: this means there are multiple types for one link
                for t in _type:
                    qgs_lines.setdefault(t, []).append(geom.asPolyline())
            else:
                # one type only, business as usual
                qgs_lines.setdefault(_type, []).append(geom.asPolyline())
        for feat in _get_feature_iterator(pumps, req_filter_pumps):
            geom = feat.geometry()
            geom.transform(tr_reverse)
            qgs_lines.setdefault('pump_or_whatever',
                                 []).append(geom.asPolyline())
        for feat in _get_feature_iterator(points, req_filter_nodes):
            geom = feat.geometry()
            geom.transform(tr_reverse)
            _type = node_id_to_type[feat['id']]
            qgs_points.setdefault(_type, []).append(geom.asPoint())

        self.qgs_lines = qgs_lines
        self.qgs_points = qgs_points

        # draw the lines/points immediately
        # TODO: probably need to throw this code away since we won't use it
        if draw_it:
            qgs_lines_all = [j for i in qgs_lines.values() for j in i]
            qgs_points_all = [j for i in qgs_points.values() for j in i]

            self.polygon_tool.update_line_point_selection(
                qgs_lines_all, qgs_points_all)

    def make_graph_series(self, ts, total_time, model_part, aggregation_type,
                          settings):
        settings = copy.deepcopy(settings)

        if model_part == '1d 2d':
            input_series = dict([(x, y) for (x, y, z) in self.INPUT_SERIES
                                 if z in ['2d', '1d', 'error_1d_2d']])
        elif model_part == '2d':
            input_series = dict([(x, y) for (x, y, z) in self.INPUT_SERIES
                                 if z in ['2d', '1d_2d', 'error_2d']])
        elif model_part == '1d':
            input_series = dict([(x, y) for (x, y, z) in self.INPUT_SERIES
                                 if z in ['1d', '1d_2d', 'error_1d']])
            idx_2d_to_1d_pos = input_series['2d_to_1d_pos']
            idx_2d_to_1d_neg = input_series['2d_to_1d_neg']
            idx_2d_to_1d = (idx_2d_to_1d_pos, idx_2d_to_1d_neg)
            total_time[:, idx_2d_to_1d] = total_time[:, idx_2d_to_1d] * -1

        # TODO: figure out why the hell np.clip is needed.
        for serie_setting in settings.get('items', []):
            serie_setting['active'] = True
            serie_setting['method'] = serie_setting['default_method']
            serie_setting['color'] = [
                int(c) for c in serie_setting['def_color'].split(',')
            ] + [150]
            serie_setting['ts_series'] = {}
            nrs_input_series = []
            for serie in serie_setting['series']:
                if serie not in input_series:
                    # throw good error message
                    log.warning(
                        'serie config error: %s is an unknown serie or is doubled in the config.',
                        serie)
                else:
                    nrs_input_series.append(input_series[serie])
                    del input_series[serie]

            if serie_setting['default_method'] == 'net':
                sum = total_time[:, nrs_input_series].sum(axis=1)
                serie_setting['ts_series']['in'] = sum.clip(min=0)
                serie_setting['ts_series']['out'] = sum.clip(max=0)
            elif serie_setting['default_method'] == 'gross':
                sum_pos = np.zeros(shape=(np.size(ts, 0), ))
                sum_neg = np.zeros(shape=(np.size(ts, 0), ))
                for nr in nrs_input_series:
                    sum_pos += total_time[:, nr].clip(min=0)
                    sum_neg += total_time[:, nr].clip(max=0)
                serie_setting['ts_series']['in'] = sum_pos
                serie_setting['ts_series']['out'] = sum_neg
            else:
                # throw config error
                log.warning('aggregation %s method unknown.',
                            serie_setting['default_method'])

            if aggregation_type == 'm3 cumulative' or \
                    aggregation_type == 'm3 cumulative natural':
                log.debug('aggregate')
                diff = np.append([0], np.diff(ts))

                serie_setting['ts_series'][
                    'in'] = serie_setting['ts_series']['in'] * diff
                serie_setting['ts_series']['in'] = np.cumsum(
                    serie_setting['ts_series']['in'], axis=0)

                serie_setting['ts_series'][
                    'out'] = serie_setting['ts_series']['out'] * diff
                serie_setting['ts_series']['out'] = np.cumsum(
                    serie_setting['ts_series']['out'], axis=0)

        if len(input_series) > 0:

            serie_setting = {
                'name':
                'Overige',
                'default_method':
                settings['remnant_method'],
                'order':
                100,
                'color':
                [int(c)
                 for c in settings['remnant_def_color'].split(',')] + [150],
                'def_color':
                settings['remnant_def_color'],  #TODO: fix + [150],
                'series': [key for key in input_series],
                'ts_series': {}
            }
            for serie in input_series:
                nrs_input_series.append(input_series[serie])

            if serie_setting['default_method'] == 'net':
                sum = total_time[:, nrs_input_series].sum(axis=1)
                serie_setting['ts_series']['in'] = sum.clip(min=0)
                serie_setting['ts_series']['out'] = sum.clip(max=0)
            elif serie_setting['default_method'] == 'gross':
                sum_pos = np.zeros(shape=(np.size(ts, 0), ))
                sum_neg = np.zeros(shape=(np.size(ts, 0), ))
                for nr in nrs_input_series:
                    sum_pos += total_time[:, nr].clip(min=0)
                    sum_neg += total_time[:, nr].clip(max=0)
                serie_setting['ts_series']['in'] = sum_pos
                serie_setting['ts_series']['out'] = sum_neg
            else:
                # throw config error
                log.warning('aggregation %s method unknown.',
                            serie_setting['default_method'])

            settings['items'].append(serie_setting)

        if model_part == '1d':
            total_time[:, (10, 11)] = total_time[:, (10, 11)] * -1

        settings['items'] = sorted(settings['items'],
                                   key=lambda item: item['order'])

        return settings

    def unset_tool(self):
        pass

    def accept(self):
        pass

    def reject(self):
        self.close()

    def closeEvent(self, event):
        self.select_polygon_button.toggled.disconnect(
            self.toggle_polygon_button)
        self.reset_waterbalans_button.clicked.disconnect(
            self.reset_waterbalans)
        self.chart_button.clicked.disconnect(self.show_chart)
        # self.polygon_tool.deactivated.disconnect(self.update_wb)
        self.iface.mapCanvas().unsetMapTool(self.polygon_tool)
        self.polygon_tool.close()

        self.modelpart_combo_box.currentIndexChanged.disconnect(self.update_wb)
        self.source_nc_combo_box.currentIndexChanged.disconnect(self.update_wb)
        self.sum_type_combo_box.currentIndexChanged.disconnect(self.update_wb)
        self.wb_item_table.hoverEnterRow.disconnect(
            self.hover_enter_map_visualization)
        self.wb_item_table.hoverExitAllRows.disconnect(
            self.hover_exit_map_visualization)

        self.closingWidget.emit()
        event.accept()

    def issue_warning(self):
        mode = self.source_nc_combo_box.currentText()
        if mode == 'normal':
            QMessageBox.information(
                None, "Information",
                "You're currently using the 'normal' NetCDF result file which "
                "may result in a less accurate overall water balance "
                "compared to the 'aggregation' NetCDF file, depending on the "
                "output time step that was chosen. Proceed at your own "
                "discretion. Please select the 'aggregation' option "
                "for the most accurate results.")

    def setup_ui(self, dock_widget):
        """
        initiate main Qt building blocks of interface
        :param dock_widget: QDockWidget instance
        """

        dock_widget.setObjectName("dock_widget")
        dock_widget.setAttribute(Qt.WA_DeleteOnClose)

        self.dock_widget_content = QWidget(self)
        self.dock_widget_content.setObjectName("dockWidgetContent")

        self.main_vlayout = QVBoxLayout(self)
        self.dock_widget_content.setLayout(self.main_vlayout)

        # add button to add objects to graphs
        self.button_bar_hlayout = QHBoxLayout(self)
        self.select_polygon_button = QPushButton(self)
        self.select_polygon_button.setCheckable(True)
        self.select_polygon_button.setObjectName("SelectedSideview")
        self.button_bar_hlayout.addWidget(self.select_polygon_button)
        self.reset_waterbalans_button = QPushButton(self)
        self.reset_waterbalans_button.setObjectName("ResetSideview")
        self.button_bar_hlayout.addWidget(self.reset_waterbalans_button)
        self.chart_button = QPushButton(self)
        self.button_bar_hlayout.addWidget(self.chart_button)

        self.modelpart_combo_box = QComboBox(self)
        self.button_bar_hlayout.addWidget(self.modelpart_combo_box)
        self.source_nc_combo_box = QComboBox(self)
        self.button_bar_hlayout.addWidget(self.source_nc_combo_box)
        self.sum_type_combo_box = QComboBox(self)
        self.button_bar_hlayout.addWidget(self.sum_type_combo_box)

        self.agg_combo_box = QComboBox(self)
        self.button_bar_hlayout.addWidget(self.agg_combo_box)

        spacer_item = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.button_bar_hlayout.addItem(spacer_item)
        self.main_vlayout.addLayout(self.button_bar_hlayout)

        # add tabWidget for graphWidgets
        self.contentLayout = QHBoxLayout(self)

        # Graph
        self.plot_widget = WaterBalancePlotWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.plot_widget.sizePolicy().hasHeightForWidth())
        self.plot_widget.setSizePolicy(sizePolicy)
        self.plot_widget.setMinimumSize(QSize(250, 250))

        self.contentLayout.addWidget(self.plot_widget)

        # table
        self.wb_item_table = WaterbalanceItemTable(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.wb_item_table.sizePolicy().hasHeightForWidth())
        self.wb_item_table.setSizePolicy(sizePolicy)
        self.wb_item_table.setMinimumSize(QSize(300, 0))

        self.contentLayout.addWidget(self.wb_item_table)

        self.main_vlayout.addLayout(self.contentLayout)

        # add dockwidget
        dock_widget.setWidget(self.dock_widget_content)
        self.retranslate_ui(dock_widget)
        QMetaObject.connectSlotsByName(dock_widget)

    def retranslate_ui(self, dock_widget):
        pass
        dock_widget.setWindowTitle(
            _translate("DockWidget", "3Di waterbalans", None))
        self.select_polygon_button.setText(
            _translate("DockWidget", "Teken nieuw gebied", None))
        self.chart_button.setText(
            _translate("DockWidget", "Toon totale balans", None))
        self.reset_waterbalans_button.setText(
            _translate("DockWidget", "Verberg op kaart", None))
Beispiel #53
0
class PDFWidget(QWidget):
    scaleFactors = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0]
    scalePercents = ["25%", "50%", "75%", "100%", "125%", "150%", "200%"]

    def __init__(self):
        QWidget.__init__(self)
        self.hboxLayout = QVBoxLayout()
        self.setLayout(self.hboxLayout)
        self.setMenu()
        self.setPDFLabelScrollArea()

        self.connect(self.pageLineEdit, SIGNAL("valueChanged(int)"),
                     self.pdfLabel.setPage)
        self.connect(self.pdfLabel, SIGNAL("pageChanged"),
                     self.pageLineEdit.setPageNumberValue)
        self.connect(self.pdfLabel, SIGNAL("pageChanged"), self.scrollToTop)

        self.connect(self.scaleComboBox, SIGNAL("currentIndexChanged(int)"),
                     self.scaleDocument)

        self.connect(self.searchLineEdit, SIGNAL("returnPressed()"),
                     self.searchDocument)
        self.connect(self.findButton, SIGNAL("clicked()"), self.searchDocument)
        self.connect(self.clearButton, SIGNAL("clicked()"),
                     self.pdfLabel.setPage)
        self.connect(self.searchLineEdit, SIGNAL("textChanged(QString)"),
                     self.checkSearchText)
        self.connect(self, SIGNAL("setDocument"), self.setDocument)

    def setMenu(self):
        self.menuLayout = QHBoxLayout()
        self.hboxLayout.addLayout(self.menuLayout)
        self.pageLineEdit = PageLineEdit()
        self.pageLineEdit.setEnabled(False)
        self.menuLayout.addLayout(self.pageLineEdit)

        spacer = QSpacerItem(20, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.menuLayout.addItem(spacer)

        self.searchLayout = QHBoxLayout()
        self.menuLayout.addLayout(self.searchLayout)
        self.searchLabel = QLabel(self.tr("Search:"))
        self.searchLabel.setTextFormat(Qt.AutoText)
        self.searchLayout.addWidget(self.searchLabel)
        self.searchLineEdit = QLineEdit()
        self.searchLineEdit.setEnabled(False)
        self.searchLabel.setBuddy(self.searchLineEdit)
        self.searchLayout.addWidget(self.searchLineEdit)
        self.searchComboBox = QComboBox()
        self.searchComboBox.setEnabled(False)
        self.searchComboBox.insertItems(0, ["Forwards", "Backwards"])
        self.searchLayout.addWidget(self.searchComboBox)
        self.findButton = QPushButton("Find")
        self.findButton.setEnabled(False)
        self.searchLayout.addWidget(self.findButton)
        self.clearButton = QPushButton("Clear")
        self.clearButton.setEnabled(False)
        self.searchLayout.addWidget(self.clearButton)

        spacer = QSpacerItem(20, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.menuLayout.addItem(spacer)

        self.scaleLabel = QLabel("Scale:")
        self.menuLayout.addWidget(self.scaleLabel)
        self.scaleComboBox = QComboBox()
        self.scaleComboBox.setEnabled(False)
        self.scaleComboBox.insertItems(0, self.scalePercents)
        self.scaleComboBox.setCurrentIndex(3)
        self.scaleLabel.setBuddy(self.scaleComboBox)
        self.menuLayout.addWidget(self.scaleComboBox)

    def setPDFLabelScrollArea(self):
        self.pdfLabel = PDFLabel(self)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setAlignment(Qt.AlignCenter)
        self.scrollArea.setWidget(self.pdfLabel)
        self.hboxLayout.addWidget(self.scrollArea)

    def scrollToTop(self, value):
        self.scrollArea.verticalScrollBar().setValue(0)

    def setDocument(self, data):
        if self.pdfLabel.setDocument(data):
            self.searchLineEdit.setEnabled(True)
            self.searchComboBox.setEnabled(True)
            self.findButton.setEnabled(True)
            self.clearButton.setEnabled(True)
            self.scaleComboBox.setEnabled(True)
            self.pageLineEdit.setEnabled(True)
            self.pageLineEdit.setPageNumberValue(1)
            self.pageLineEdit.setMaximumPageNumber(
                self.pdfLabel.document().numPages())

    def setError(self, errorMessage):
        self.pdfLabel.setError(errorMessage)

    def setMessage(self, message):
        self.pdfLabel.setText(message)

    def checkSearchText(self, text):
        if text == "":
            self.pdfLabel.setPage()

    def scaleDocument(self, index):
        self.pdfLabel.setScale(self.scaleFactors[index])

    def searchDocument(self):
        if self.searchComboBox.currentIndex() == 0:
            location = self.pdfLabel.searchForwards(self.searchLineEdit.text())
        else:
            location = self.pdfLabel.searchBackwards(
                self.searchLineEdit.text())

        target = self.pdfLabel.matrix().mapRect(location).center().toPoint()
        self.scrollArea.ensureVisible(target.x(), target.y())
class MCAHPanel(QWidget):
    def __init__(self, parent, altitudeUnit=AltitudeUnits.FT):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("MCAHPanel" +
                           str(len(parent.findChildren(MCAHPanel))))

        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)

        self.hLayout = QHBoxLayout(self)
        self.hLayout.setSpacing(0)
        self.hLayout.setMargin(0)
        self.hLayout.setObjectName("hLayout")

        self.basicFrame = Frame(self, "HL")
        self.basicFrame.Spacing = 0
        self.hLayout.addWidget(self.basicFrame)

        self.lblMCAH = QLabel(self.basicFrame)
        self.lblMCAH.setMinimumSize(QSize(250, 0))
        font = QFont()
        font.setWeight(50)
        font.setBold(False)
        self.lblMCAH.setFont(font)
        self.lblMCAH.setObjectName(("lblMCAH"))
        self.basicFrame.Add = self.lblMCAH
        self.cmbMCAH = QComboBox(self.basicFrame)
        font = QFont()
        font.setWeight(50)
        font.setBold(False)
        self.cmbMCAH.setFont(font)
        self.cmbMCAH.setObjectName(self.objectName() + "_cmbMCAH")
        self.basicFrame.Add = self.cmbMCAH
        self.txtMCAH = QLineEdit(self.basicFrame)
        font = QFont()
        font.setWeight(50)
        font.setBold(False)
        self.txtMCAH.setFont(font)
        self.txtMCAH.setObjectName(self.objectName() + "_txtMCAH")
        self.txtMCAH.setMinimumWidth(70)
        self.txtMCAH.setMaximumWidth(70)
        self.basicFrame.Add = self.txtMCAH
        self.setLayout(self.hLayout)

        spacerItem = QSpacerItem(0, 10, QSizePolicy.Minimum,
                                 QSizePolicy.Minimum)
        self.hLayout.addItem(spacerItem)
        self.cmbMCAH.addItems([MCAHType.MCA, MCAHType.MCH])
        #         self.txtMCAH.textChanged.connect(self.txtAltitude_TextChanged)
        self.altitudeUnit = altitudeUnit

    def setValue(self, altitude_0):
        if self.altitudeUnit == AltitudeUnits.FT:
            value1 = altitude_0.Feet
        elif self.altitudeUnit == AltitudeUnits.M:
            value1 = altitude_0.Metres
        self.txtMCAH.setText(str(value1))

    def set_Value(self, altitude_0):
        if self.altitudeUnit == AltitudeUnits.FT:
            value1 = altitude_0.Feet
        elif self.altitudeUnit == AltitudeUnits.M:
            value1 = altitude_0.Metres
        self.txtMCAH.setText(str(value1))

    def get_Value(self):
        try:
            return Altitude(float(self.txtMCAH.text()), self.altitudeUnit)
        except:
            raise UserWarning, self.lblMCAH.text() + " is invalid!"

    Value = property(get_Value, set_Value, None, None)

    def IsEmpty(self):
        if self.txtMCAH.text() == "":
            return True
        else:
            return False

    def method_2(self, altitude_0):
        if (self.cmbMCAH.currentIndex() == 0):
            return self.Value
        return self.Value + (altitude_0)

    def method_3(self, altitude_0):
        if (self.cmbMCAH.currentIndex() != 0):
            return self.Value
        return self.Value - (altitude_0)
class MapScalePanel(QWidget):
    def __init__(self, parent, mapScaleDropDownType):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("DistanceBoxPanel" +
                           str(len(parent.findChildren(MapScalePanel))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.frameBoxPanelIn = QFrame(self.frameBoxPanel)
        self.frameBoxPanelIn.setFrameShape(QFrame.StyledPanel)
        self.frameBoxPanelIn.setFrameShadow(QFrame.Raised)
        self.frameBoxPanelIn.setObjectName(("frameBoxPanelIn"))
        self.hLayoutframeBoxPanelIn = QHBoxLayout(self.frameBoxPanelIn)
        self.hLayoutframeBoxPanelIn.setSpacing(0)
        self.hLayoutframeBoxPanelIn.setMargin(0)
        self.hLayoutframeBoxPanelIn.setObjectName(("hLayoutframeBoxPanelIn"))

        self.comboBox = ComboBoxPanel(self.frameBoxPanelIn)
        self.comboBox.Caption = "1"
        self.comboBox.LabelWidth = 20
        self.hLayoutframeBoxPanelIn.addWidget(self.comboBox)
        # self.txtDistance = QLineEdit(self.frameBoxPanelIn)
        # self.txtDistance.setEnabled(True)
        # font = QFont()
        # font.setBold(False)
        # font.setWeight(50)
        # self.txtDistance.setFont(font)
        # self.txtDistance.setObjectName(("txtDistance"))
        # self.txtDistance.setText("0.0")
        # self.txtDistance.setMinimumWidth(70)
        # self.txtDistance.setMaximumWidth(70)
        # self.hLayoutframeBoxPanelIn.addWidget(self.txtDistance)

        self.imageButton = QToolButton(self.frameBoxPanelIn)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")),
                       QIcon.Normal, QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("btnDegreeBoxPanel"))
        self.hLayoutframeBoxPanelIn.addWidget(self.imageButton)

        self.hLayoutframeBoxPanel.addWidget(self.frameBoxPanelIn)
        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.hLayoutBoxPanel.addItem(spacerItem)

        self.imageButton.clicked.connect(self.imageButtonClicked)
        define._canvas.renderComplete.connect(self.canvas_renderComplete)
        self.connect(self.comboBox, SIGNAL("Event_0"), self.comboBox_Event_0)
        self.flag = 0
        self.dropDownType = mapScaleDropDownType
        self.method_5()
        self.imageButton.setVisible(False)

    def comboBox_Event_0(self):
        define._canvas.zoomScale(float(self.comboBox.SelectedItem))

    def canvas_renderComplete(self):
        self.comboBox.comboBox.setEditText(str(int(define._canvas.scale())))

    def method_4(self, mapScaleDropDownType_0):
        return (self.dropDownType
                & mapScaleDropDownType_0) == mapScaleDropDownType_0

    def method_5(self):
        self.comboBox.Clear()
        if (self.method_4(MapScaleDropDownType.Aerodrome)):
            for i in range(2, 7):
                num = i * 5000
                self.comboBox.Add(str(num))
        if (self.method_4(MapScaleDropDownType.Approach)):
            for j in range(4, 20):
                num1 = j * 50000
                self.comboBox.Add(str(num1))
        if (self.method_4(MapScaleDropDownType.Enroute)):
            for k in range(2, 21):
                num2 = k * 500000
                self.comboBox.Add(str(num2))

    # def method_6(self, string_0):
    #     value = None
    #     if self.distanceUnit == DistanceUnits.NM:
    #         value = self.txtDistance.text() + "nm"
    #     elif self.distanceUnit == DistanceUnits.M:
    #         value = self.txtDistance.text() + "m"
    #     elif self.distanceUnit == DistanceUnits.KM:
    #         value = self.txtDistance.text() + "km"
    #     elif self.distanceUnit == DistanceUnits.FT:
    #         value = self.txtDistance.text() + "ft"
    #     elif self.distanceUnit == DistanceUnits.MM:
    #         value = self.txtDistance.text() + "mm"
    #     else:
    #         value = ""
    #
    #
    #     return "%s%s\t%s"%(string_0, self.Caption, value);
    def txtDistanceChanged(self):
        try:
            test = float(self.txtDistance.text())
            self.emit(SIGNAL("Event_0"), self)
        except:
            str0 = "You must input the float type in \"%s\"." % (self.Caption)
            QMessageBox.warning(self, "Warning", str0)
            self.txtDistance.setText("0.0")

    def imageButtonClicked(self):
        measureDistanceTool = MeasureTool(define._canvas, self.txtDistance,
                                          self.distanceUnit)
        define._canvas.setMapTool(measureDistanceTool)
        self.emit(SIGNAL("Event_1"), self)

    def get_CaptionUnits(self):
        return self.distanceUnit

    def set_CaptionUnits(self, distanceUnit):
        self.distanceUnit = distanceUnit

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        # if self.distanceUnit == DistanceUnits.NM:
        #     value = captionStr + "(nm)"
        # elif self.distanceUnit == DistanceUnits.M:
        #     value = captionStr + "(m)"
        # elif self.distanceUnit == DistanceUnits.KM:
        #     value = captionStr + "(km)"
        # elif self.distanceUnit == DistanceUnits.FT:
        #     value = captionStr + "(ft)"
        # elif self.distanceUnit == DistanceUnits.MM:
        #     value = captionStr + "(mm)"
        # else:
        #     value = ""
        self.captionLabel.setText(captionStr + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_dropDownType(self):
        return self.dropDownType

    def set_dropDownType(self, val):
        self.dropDownType = val

    DropDownType = property(get_dropDownType, set_dropDownType, None, None)

    def get_Value(self):
        try:
            return self.comboBox.SelectedItem
        except:
            return ""

    # def set_Value(self, value):

    Value = property(get_Value, None, None, None)

    # def get_IsEmpty(self):
    #     return self.txtDistance.text() == "" or self.txtDistance.text() == None
    # IsEmpty = property(get_IsEmpty, None, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def get_ReadOnly(self):
        return self.comboBox.isReadOnly()

    def set_ReadOnly(self, bool):
        self.comboBox.setReadOnly(bool)

    ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def get_Enabled(self):
        return self.comboBox.Enabled

    def set_Enabled(self, bool):
        self.comboBox.Enabled = bool
        self.imageButton.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)