示例#1
0
文件: search.py 项目: diatel/microhex
class SearchDialog(utils.Dialog):
    def __init__(self, main_win, hex_widget):
        utils.Dialog.__init__(self, main_win, name='search_dialog')
        self.hexWidget = hex_widget

        self.setWindowTitle(utils.tr('Search'))

        self.m_layout = QVBoxLayout()
        self.setLayout(self.m_layout)
        self.descLabel = QLabel(self)
        self.descLabel.setText(utils.tr('Enter hex values to search for:'))
        self.m_layout.addWidget(self.descLabel)
        self.hexInput = hexlineedit.HexLineEdit(self)
        self.m_layout.addWidget(self.hexInput)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.addButton(QDialogButtonBox.Close)
        self.searchButton = QPushButton(utils.tr('Search'), self)
        self.searchButton.setIcon(utils.getIcon('edit-find'))
        self.buttonBox.addButton(self.searchButton, QDialogButtonBox.AcceptRole)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.m_layout.addWidget(self.buttonBox)

    @property
    def matcher(self):
        return matchers.BinaryMatcher(self.hexWidget.document, self.hexInput.data)
示例#2
0
    def __init__(self, parent, url, archivo_destino):
        super(Descargar, self).__init__(parent)

        self.url = url
        self.httpGetId = 0
        self.httpRequestAborted = False
        self.statusLabel = QLabel('Descargando el manual completo ...')
        self.closeButton = QPushButton("Cerrar")
        self.closeButton.setAutoDefault(False)
        self.barra = QProgressBar()

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)

        self.http = QHttp(self)
        self.http.requestFinished.connect(self.cuando_finalizar_request)
        self.http.dataReadProgress.connect(self.cuando_actualiza_descarga)
        self.http.responseHeaderReceived.connect(self.cuando_responder_header)
        self.closeButton.clicked.connect(self.cuando_cancela)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(self.barra)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle('Descargando manual')
        self.downloadFile(url, archivo_destino)
示例#3
0
    def _create_buttons ( self, parent ):
        buttons = QDialogButtonBox()

        # 'OK' button.
        # FIXME v3: Review how this is supposed to work for non-modal dialogs
        # (ie. how does anything act on a button click?)
        if self.ok_label:
            btn = buttons.addButton( self.ok_label,
                                     QDialogButtonBox.AcceptRole )
        else:
            btn = buttons.addButton( QDialogButtonBox.Ok )

        btn.setDefault( True )

        # 'Cancel' button.
        # FIXME v3: Review how this is supposed to work for non-modal dialogs
        # (ie. how does anything act on a button click?)
        if self.cancel_label:
            buttons.addButton( self.cancel_label, QDialogButtonBox.RejectRole )
        else:
            buttons.addButton( QDialogButtonBox.Cancel )

        # 'Help' button.
        # FIXME v3: In the original code the only possible hook into the help
        # was to reimplement self._on_help().  However this was a private
        # method.  Obviously nobody uses the Help button.  For the moment we
        # display it but can't actually use it.
        if len( self.help_id ) > 0:
            if self.help_label:
                buttons.addButton( self.help_label, QDialogButtonBox.HelpRole )
            else:
                buttons.addButton( QDialogButtonBox.Help )

        return buttons
示例#4
0
 def fill(self):
     # Vispa 
     # icon
     # Version
     # Release date os.path.getmtime(filename)
     # website url
     # license
     self.setLayout(QVBoxLayout())
     if "vispa" in self._application.windowTitle().lower():
         self._logo = QSvgWidget(":/resources/vispa_logo.svg")
         sizeHint = self._logo.sizeHint()
         logo_width_height_ratio =  1.0 * sizeHint.width() / sizeHint.height()
         logo_width = 200
         self._logo.setFixedSize(logo_width, logo_width/logo_width_height_ratio)
         self.layout().addWidget(self._logo)
     else:
         label=QLabel(self._application.windowTitle())
         self.layout().addWidget(label)
     self.layout().addWidget(QLabel("Version "+ self._application.version()))
     self.layout().addWidget(QLabel("More information can be found on:"))
     websiteLink = QLabel("<a href='"+ websiteUrl +"'>"+ websiteUrl +"</a>")
     websiteLink.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.TextSelectableByMouse)
     websiteLink.setOpenExternalLinks(True)
     self.layout().addWidget(websiteLink)
     buttonBox=QDialogButtonBox()
     buttonBox.addButton(QDialogButtonBox.Close)
     self.connect(buttonBox,SIGNAL("rejected()"),self,SLOT("reject()"))
     self.layout().addWidget(buttonBox)
示例#5
0
 def addNodeList(self, key, predefs, selectednodes):
     if not self.overwriteKeys(key) and type(key).__name__ == 'str':
         layout = QVBoxLayout()
         nodeList = NodeListItem()
         nodeList.setDragDropMode(QAbstractItemView.InternalMove)
         if len(predefs) > 0:
             if not self.checkUnifiedTypes(predefs):
                 return -1
             for predef in predefs:
                 nodeList.addSingleItem(str(predef), predef.value().uid())
         if selectednodes and len(selectednodes) > 0:
             for node in selectednodes:
                 name = QString.fromUtf8(node.absolute())
                 nodeList.addSingleItem(name, node.uid())
         hbox = QHBoxLayout()
         buttonbox = QDialogButtonBox()
         add = NodeSelectionButton(self, key, nodeList)
         buttonbox.addButton(add, QDialogButtonBox.ActionRole)
         rm = rmLocalPathButton(self, nodeList)
         buttonbox.addButton(rm, QDialogButtonBox.ActionRole)
         self.connect(add, SIGNAL("clicked()"), self.argumentChanged)
         self.connect(rm, SIGNAL("clicked()"), self.argumentChanged)
         hbox.addWidget(buttonbox, 3, Qt.AlignLeft)
         layout.addLayout(hbox, 0)
         layout.addWidget(nodeList, 2)
         if not self.displaykey:
             self.layout.addRow(layout)
         else:
             self.layout.addRow(key, layout)
         self.widgets[key] = nodeList
         return 1
     else:
         return -1
示例#6
0
    def __init__(self, url_to_download, download_location, parent=None):
        super(Downloader, self).__init__(parent)

        self.httpGetId = 0
        self.httpRequestAborted = False
        self.statusLabel = QLabel('Downloading %s' % url_to_download)
        self.closeButton = QPushButton("Close")
        self.closeButton.setAutoDefault(False)
        self.progressBar = QProgressBar()

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)

        self.http = QHttp(self)
        self.http.requestFinished.connect(self.httpRequestFinished)
        self.http.dataReadProgress.connect(self.updateDataReadProgress)
        self.http.responseHeaderReceived.connect(self.readResponseHeader)
        self.closeButton.clicked.connect(self.cancelDownload)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(self.progressBar)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle('Downloader')
        self.downloadFile(url_to_download, download_location)
示例#7
0
class DialogStudentId(QDialog):
    """Dialog to change the student id.

    Example (replace `parent` by the parent widget):

    dialog = DialogStudentId(parent)
    id = dialog.exec_()

    """
    def __init__(self, parent, students):
        super(DialogStudentId, self).__init__(parent)
        self.setWindowTitle(_('Change the student id'))
        layout = QFormLayout()
        self.setLayout(layout)
        self.combo = widgets.StudentComboBox(parent=self)
        self.combo.add_students(students)
        self.combo.editTextChanged.connect(self._check_value)
        self.combo.currentIndexChanged.connect(self._check_value)
        new_student_button = QPushButton( \
                                 QIcon(utils.resource_path('new_id.svg')),
                                 _('New student'), parent=self)
        new_student_button.clicked.connect(self._new_student)
        self.buttons = QDialogButtonBox((QDialogButtonBox.Ok
                                         | QDialogButtonBox.Cancel))
        self.buttons.addButton(new_student_button, QDialogButtonBox.ActionRole)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        layout.addRow(_('Student id:'), self.combo)
        layout.addRow(self.buttons)

    def exec_(self):
        """Shows the dialog and waits until it is closed.

        Returns a student object with the option selected by the user.
        The return value is None if the user cancels the dialog.

        """
        result = super(DialogStudentId, self).exec_()
        if result == QDialog.Accepted:
            return self.combo.current_student()
        else:
            return None

    def _new_student(self):
        dialog = NewStudentDialog(parent=self)
        student = dialog.exec_()
        if student is not None:
            self.combo.add_student(student, set_current=True)
            self.buttons.button(QDialogButtonBox.Ok).setFocus()
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)

    def _check_value(self, param):
        if self.combo.current_student() is not None:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)
        else:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
示例#8
0
 def initUI(self):
     u"""Build the dialog box."""
     self.setWindowTitle(_(u'Anki – Download audio'))
     self.setWindowIcon(QIcon(":/icons/anki.png"))
     layout = QGridLayout()
     self.setLayout(layout)
     explanation = QLabel(self)
     if len(self.entries_list) > 1:
         explanation.setText(
             _(u'Please select an action for each downloaded file:'))
     else:
         explanation.setText(_(u'Please select what to do with the file:'))
     layout.addWidget(explanation, 0, 0, 1, self.num_columns)
     if not self.hide_text:
         text_head_label = QLabel(_(u'<b>Source text</b>'), self)
         layout.addWidget(text_head_label, 1, 0, 1, 2)
         text_head_label.setToolTip(self.text_help)
     else:
         text_head_label = QLabel(_(u'<b>Source</b>'), self)
         layout.addWidget(text_head_label, 1, 0)
         text_head_label.setToolTip(self.text_hide_help)
     play_head_label = QLabel(_(u'play'), self)
     play_head_label.setToolTip(self.play_help)
     layout.addWidget(play_head_label, 1, self.play_column)
     play_old_head_label = QLabel(_(u'play old'), self)
     if not self.hide_text:
         play_old_head_label.setToolTip(self.play_old_help)
     else:
         play_old_head_label.setToolTip(self.play_old_hide_help)
     layout.addWidget(play_old_head_label, 1, self.play_old_column)
     add_head_label = QLabel(_(u'add'), self)
     add_head_label.setToolTip(self.add_help_text_long)
     layout.addWidget(add_head_label, 1, self.add_column)
     keep_head_label = QLabel(_(u'keep'), self)
     keep_head_label.setToolTip(self.keep_help_text_long)
     layout.addWidget(keep_head_label, 1, self.keep_column)
     delete_head_label = QLabel(_(u'delete'), self)
     delete_head_label.setToolTip(self.delete_help_text_long)
     layout.addWidget(delete_head_label, 1, self.delete_column)
     if self.show_skull_and_bones:
         blacklist_head_label = QLabel(_(u'blacklist'), self)
         blacklist_head_label.setToolTip(self.blacklist_help_text_long)
         layout.addWidget(blacklist_head_label, 1, self.blacklist_column)
     rule_label = QLabel('<hr>')
     layout.addWidget(rule_label, 2, 0, 1, self.num_columns)
     self.create_rows(layout)
     dialog_buttons = QDialogButtonBox(self)
     dialog_buttons.addButton(QDialogButtonBox.Cancel)
     dialog_buttons.addButton(QDialogButtonBox.Ok)
     self.connect(
         dialog_buttons, SIGNAL("accepted()"), self, SLOT("accept()"))
     self.connect(
         dialog_buttons, SIGNAL("rejected()"), self, SLOT("reject()"))
     layout.addWidget(
         dialog_buttons, len(self.buttons_groups) + 3, 0, 1,
         self.num_columns)
示例#9
0
class DialogStudentId(QDialog):
    """Dialog to change the student id.

    Example (replace `parent` by the parent widget):

    dialog = DialogStudentId(parent)
    id = dialog.exec_()

    """
    def __init__(self, parent, students):
        super(DialogStudentId, self).__init__(parent)
        self.setWindowTitle(_('Change the student id'))
        layout = QFormLayout()
        self.setLayout(layout)
        self.combo = widgets.StudentComboBox(parent=self)
        self.combo.add_students(students)
        self.combo.editTextChanged.connect(self._check_value)
        self.combo.currentIndexChanged.connect(self._check_value)
        new_student_button = QPushButton( \
                                 QIcon(utils.resource_path('new_id.svg')),
                                 _('New student'), parent=self)
        new_student_button.clicked.connect(self._new_student)
        self.buttons = QDialogButtonBox((QDialogButtonBox.Ok
                                         | QDialogButtonBox.Cancel))
        self.buttons.addButton(new_student_button, QDialogButtonBox.ActionRole)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        layout.addRow(_('Student id:'), self.combo)
        layout.addRow(self.buttons)

    def exec_(self):
        """Shows the dialog and waits until it is closed.

        Returns a student object with the option selected by the user.
        The return value is None if the user cancels the dialog.

        """
        result = super(DialogStudentId, self).exec_()
        if result == QDialog.Accepted:
            return self.combo.current_student()
        else:
            return None

    def _new_student(self):
        dialog = NewStudentDialog(parent=self)
        student = dialog.exec_()
        if student is not None:
            self.combo.add_student(student, set_current=True)
            self.buttons.button(QDialogButtonBox.Ok).setFocus()
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)

    def _check_value(self, param):
        if self.combo.current_student() is not None:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)
        else:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
示例#10
0
class DeletionOptions(QDialog):
    def __init__(self, parent, model):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.model = model
        self._setupUi()
        self.model.view = self
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupUi(self):
        self.setWindowTitle(tr("Deletion Options"))
        self.resize(400, 270)
        self.verticalLayout = QVBoxLayout(self)
        self.msgLabel = QLabel()
        self.verticalLayout.addWidget(self.msgLabel)
        self.linkCheckbox = QCheckBox(tr("Link deleted files"))
        self.verticalLayout.addWidget(self.linkCheckbox)
        text = tr("After having deleted a duplicate, place a link targeting the reference file "
            "to replace the deleted file.")
        self.linkMessageLabel = QLabel(text)
        self.linkMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.linkMessageLabel)
        self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False)
        self.verticalLayout.addWidget(self.linkTypeRadio)
        if not self.model.supports_links():
            self.linkCheckbox.setEnabled(False)
            self.linkTypeRadio.setEnabled(False)
            self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)"))
        self.directCheckbox = QCheckBox(tr("Directly delete files"))
        self.verticalLayout.addWidget(self.directCheckbox)
        text = tr("Instead of sending files to trash, delete them directly. This option is usually "
            "used as a workaround when the normal deletion method doesn't work.")
        self.directMessageLabel = QLabel(text)
        self.directMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.directMessageLabel)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
        self.verticalLayout.addWidget(self.buttonBox)
    
    #--- model --> view
    def update_msg(self, msg):
        self.msgLabel.setText(msg)
    
    def show(self):
        self.linkCheckbox.setChecked(self.model.link_deleted)
        self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0
        self.directCheckbox.setChecked(self.model.direct)
        result = self.exec()
        self.model.link_deleted = self.linkCheckbox.isChecked()
        self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1
        self.model.direct = self.directCheckbox.isChecked()
        return result == QDialog.Accepted
示例#11
0
 def initUI(self):
     u"""Build the dialog box."""
     self.setWindowTitle(_(u'Anki – Download audio'))
     self.setWindowIcon(QIcon(":/icons/anki.png"))
     layout = QGridLayout()
     self.setLayout(layout)
     explanation = QLabel(self)
     if len(self.list) > 1:
         explanation.setText(
             _(u'Please select an action for each downloaded file:'))
     else:
         explanation.setText(_(u'Please select what to do with the file:'))
     layout.addWidget(explanation, 0, 0, 1, self.num_columns)
     if not self.hide_text:
         text_head_label = QLabel(_(u'<b>Source text</b>'), self)
         layout.addWidget(text_head_label, 1, 0, 1, 2)
         text_head_label.setToolTip(self.text_help)
     else:
         text_head_label = QLabel(_(u'<b>Source</b>'), self)
         layout.addWidget(text_head_label, 1, 0)
         text_head_label.setToolTip(self.text_hide_help)
     play_head_label = QLabel(_(u'play'), self)
     play_head_label.setToolTip(self.play_help)
     layout.addWidget(play_head_label, 1, self.play_column)
     play_old_head_label = QLabel(_(u'play old'), self)
     if not self.hide_text:
         play_old_head_label.setToolTip(self.play_old_help)
     else:
         play_old_head_label.setToolTip(self.play_old_hide_help)
     layout.addWidget(play_old_head_label, 1, self.play_old_column)
     add_head_label = QLabel(_(u'add'), self)
     add_head_label.setToolTip(self.add_help_text_long)
     layout.addWidget(add_head_label, 1, self.add_column)
     keep_head_label = QLabel(_(u'keep'), self)
     keep_head_label.setToolTip(self.keep_help_text_long)
     layout.addWidget(keep_head_label, 1, self.keep_column)
     delete_head_label = QLabel(_(u'delete'), self)
     delete_head_label.setToolTip(self.delete_help_text_long)
     layout.addWidget(delete_head_label, 1, self.delete_column)
     if self.show_skull_and_bones:
         blacklist_head_label = QLabel(_(u'blacklist'), self)
         blacklist_head_label.setToolTip(self.blacklist_help_text_long)
         layout.addWidget(blacklist_head_label, 1, self.blacklist_column)
     rule_label = QLabel('<hr>')
     layout.addWidget(rule_label, 2, 0, 1, self.num_columns)
     self.create_rows(layout)
     dialog_buttons = QDialogButtonBox(self)
     dialog_buttons.addButton(QDialogButtonBox.Cancel)
     dialog_buttons.addButton(QDialogButtonBox.Ok)
     self.connect(dialog_buttons, SIGNAL("accepted()"),
                  self, SLOT("accept()"))
     self.connect(dialog_buttons, SIGNAL("rejected()"),
                  self, SLOT("reject()"))
     layout.addWidget(dialog_buttons,
                      len(self.buttons_groups) + 3, 0, 1, self.num_columns)
    def _initButtonBox(self):
        cancelButton = QPushButton("Deny", self)
        cancelButton.clicked.connect(self.reject)

        okButton = QPushButton("Accept", self)
        okButton.clicked.connect(self.accept)

        buttonBox = QDialogButtonBox(Qt.Horizontal, self)
        buttonBox.addButton(cancelButton, QDialogButtonBox.RejectRole)
        buttonBox.addButton(okButton, QDialogButtonBox.AcceptRole)
        return buttonBox
示例#13
0
 def __init__(self, parent = None):
 
     LoginDialog.__init__(self, parent)
     
     buttonBox = QDialogButtonBox()
     buttonBox.addButton(QDialogButtonBox.Ok)
     buttonBox.addButton(QDialogButtonBox.Cancel)
     
     buttonBox.accepted.connect(self.checkInput)
     buttonBox.rejected.connect(self.reject)
     
     self.layout().addRow(buttonBox)
示例#14
0
    def manage_buttons(self):
        buttons = QDialogButtonBox(Qt.Horizontal, self)

        button_cancel = QPushButton("&Anuluj")
        button_replace = QPushButton("&Zast\u0105p")
        button_compare = QPushButton("&Por\u00F3wnaj")
        buttons.addButton(button_cancel, QDialogButtonBox.RejectRole)
        buttons.addButton(button_replace, QDialogButtonBox.AcceptRole)
        buttons.addButton(button_compare, QDialogButtonBox.AcceptRole)

        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        button_compare.clicked.connect(self.compare)

        self.layout.addWidget(buttons, 1, 3)
示例#15
0
    def addPathList(self, key, typeid, predefs, selectednodes):
        if not self.overwriteKeys(key) and type(key).__name__=='str':
            layout = QVBoxLayout()
            listpathcontainer = QListWidget() ##XXX
            listpathcontainer.setDragDropMode(QAbstractItemView.InternalMove)
            if len(predefs) > 0:
                if not self.checkUnifiedTypes(predefs):
                    return -1
                for predef in predefs:
                    listpathcontainer.insertItem(listpathcontainer.count() + 1, str(predef))
            if selectednodes and len(selectednodes) > 0:
                for node in selectednodes:
		   if type(node) == Node and typeid == typeId.Node:
                        listpathcontainer.insertItem(listpathcontainer.count() + 1, QString.fromUtf8(node.absolute())) 
		   elif type(node) != Node:
			listpathcontainer.insertItem(listpathcontainer.count() + 1, node)
            hbox = QHBoxLayout()
            buttonbox = QDialogButtonBox()
            if typeid == typeId.Path:
                combo = QComboBox()
	        self.connect(combo, SIGNAL("editTextChanged(QString)"), self.argumentChanged)
		self.connect(combo, SIGNAL("currentIndexChanged(QString)"), self.argumentChanged)
                combo.addItem(self.inputFile)
                combo.addItem(self.inputDirectory)
                add = addLocalPathButton(self, key, listpathcontainer, combo)
            else:
                add = addLocalPathButton(self, key, listpathcontainer, nodetype=True)
            buttonbox.addButton(add, QDialogButtonBox.ActionRole)
            rm = rmLocalPathButton(self, listpathcontainer)
            buttonbox.addButton(rm, QDialogButtonBox.ActionRole)

            self.connect(add, SIGNAL("clicked()"), self.argumentChanged)
            self.connect(rm, SIGNAL("clicked()"), self.argumentChanged)

            hbox.addWidget(buttonbox, 3, Qt.AlignLeft)
            if typeid == typeId.Path:
                hbox.addWidget(combo, 1, Qt.AlignRight)
            layout.addLayout(hbox, 0)
            layout.addWidget(listpathcontainer, 2)

            if not self.displaykey:
                self.layout.addRow(layout)
            else:
                self.layout.addRow(key, layout)
            self.widgets[key] = listpathcontainer
            return 1
        else:
            return -1
    def __init__(self, data, title="", comment="",
                 icon=None, parent=None, apply=None):
        super(FormDialog, self).__init__(parent)

        self.apply_callback = apply
        
        # Form
        if isinstance(data[0][0], (list, tuple)):
            self.formwidget = FormTabWidget(data, comment=comment,
                                            parent=self)
        elif len(data[0])==3:
            self.formwidget = FormComboWidget(data, comment=comment,
                                              parent=self)
        else:
            self.formwidget = FormWidget(data, comment=comment, 
                                         parent=self)
        layout = QVBoxLayout()
        layout.addWidget(self.formwidget)
        
        # Button box
        bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        if self.apply_callback is not None:
            apply_btn = bbox.addButton(QDialogButtonBox.Apply)
            self.connect(apply_btn, SIGNAL("clicked()"), self.apply)
        self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()"))
        self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()"))
        layout.addWidget(bbox)

        self.setLayout(layout)
        
        self.setWindowTitle(title)
        if not isinstance(icon, QIcon):
            icon = QWidget().style().standardIcon(QStyle.SP_MessageBoxQuestion)
        self.setWindowIcon(icon)
示例#17
0
    def __init__(self, data, title="", comment="",
                 icon=None, parent=None, apply=None):
        super(FormDialog, self).__init__(parent)

        self.apply_callback = apply
        
        # Form
        if isinstance(data[0][0], (list, tuple)):
            self.formwidget = FormTabWidget(data, comment=comment,
                                            parent=self)
        elif len(data[0])==3:
            self.formwidget = FormComboWidget(data, comment=comment,
                                              parent=self)
        else:
            self.formwidget = FormWidget(data, comment=comment, 
                                         parent=self)
        layout = QVBoxLayout()
        layout.addWidget(self.formwidget)
        
        # Button box
        bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        if self.apply_callback is not None:
            apply_btn = bbox.addButton(QDialogButtonBox.Apply)
            self.connect(apply_btn, SIGNAL("clicked()"), self.apply)
        self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()"))
        self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()"))
        layout.addWidget(bbox)

        self.setLayout(layout)
        
        self.setWindowTitle(title)
        if not isinstance(icon, QIcon):
            icon = QWidget().style().standardIcon(QStyle.SP_MessageBoxQuestion)
        self.setWindowIcon(icon)
示例#18
0
class AboutDialog(QDialog):
    """
    Common About Dialog for the Freeseer Project. This should be used for the
    about dialog when including one in GUIs.


    Grid Layout:

    Logo  |  About Infos
    ------|-------------
          |  Close Button
    """
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.aboutWidget = AboutWidget()

        icon = QIcon()
        icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.layout.addWidget(self.aboutWidget)

        # Right Bottom corner of grid, Close Button
        self.buttonBox = QDialogButtonBox()
        self.closeButton = self.buttonBox.addButton("Close", QDialogButtonBox.AcceptRole)
        self.layout.addWidget(self.buttonBox, 1, 1)
        self.connect(self.closeButton, SIGNAL("clicked()"), self.close)

        self.setWindowTitle("About Freeseer")
示例#19
0
    def __init__(self):
        super(ForceUpgradeDialog, self).__init__()
        vbox = QVBoxLayout(self)

        self.setWindowTitle(u"El contenido debe actualizarse")

        self.main_text = QLabel(UPGRADE_TEXT)
        vbox.addWidget(self.main_text)

        bbox = QDialogButtonBox()
        bbox.addButton(QPushButton(u"Salir del programa"),
                       QDialogButtonBox.AcceptRole)
        bbox.accepted.connect(self.accept)
        bbox.addButton(QPushButton(u"Continuar"), QDialogButtonBox.RejectRole)
        bbox.rejected.connect(self.reject)
        vbox.addWidget(bbox)
        self.show()
示例#20
0
 def __init__(self, parent=None):
     super(MusicPreviewDialog, self).__init__(parent)
     layout = QVBoxLayout()
     self.setLayout(layout)
     self._widget = MusicPreviewWidget()
     layout.addWidget(self._widget)
     layout.addWidget(widgets.Separator())
     b = QDialogButtonBox()
     layout.addWidget(b)
     b.addButton(QDialogButtonBox.Close)
     b.rejected.connect(self.accept)
     self._printButton = b.addButton('', QDialogButtonBox.ActionRole)
     self._printButton.setIcon(icons.get("document-print"))
     self._printButton.clicked.connect(self._widget.print_)
     self._printButton.hide()
     qutil.saveDialogSize(self, "musicpreview/dialog/size", QSize(500, 350))
     app.translateUI(self)
示例#21
0
 def __init__(self, parent=None):
     super(MusicPreviewDialog, self).__init__(parent)
     layout = QVBoxLayout()
     self.setLayout(layout)
     self._widget = MusicPreviewWidget()
     layout.addWidget(self._widget)
     layout.addWidget(widgets.Separator())
     b = QDialogButtonBox()
     layout.addWidget(b)
     b.addButton(QDialogButtonBox.Close)
     b.rejected.connect(self.accept)
     self._printButton = b.addButton('', QDialogButtonBox.ActionRole)
     self._printButton.setIcon(icons.get("document-print"))
     self._printButton.clicked.connect(self._widget.print_)
     self._printButton.hide()
     qutil.saveDialogSize(self, "musicpreview/dialog/size", QSize(500, 350))
     app.translateUI(self)
示例#22
0
 def __init__(self, parent, description = "Please enter your login information:", loginText = "Login:"******"Password:"):
     QDialog.__init__(self, parent)
     
     self._username = None
     self._password = None
     
     formGridLayout = QGridLayout(self)
  
     descLabel = QLabel(description, self)
     descLabel.setWordWrap(True)
     descLabel.setContentsMargins(0,0,0,5)
  
     self.editUserName = QLineEdit(self)
     self.editPassword = QLineEdit(self)
     self.editPassword.setEchoMode( QLineEdit.Password )
  
     labelUsername = QLabel(self)
     labelPassword = QLabel(self)
     labelUsername.setText(loginText)
     labelUsername.setBuddy(self.editUserName)
     labelPassword.setText(passwordText)
     labelPassword.setBuddy(self.editPassword)
  
     buttons = QDialogButtonBox(self)
     buttons.addButton(QDialogButtonBox.Ok)
     buttons.addButton(QDialogButtonBox.Cancel)
  
     buttons.button(QDialogButtonBox.Cancel).clicked.connect(self.close)
     buttons.button(QDialogButtonBox.Ok).clicked.connect(self.slotAcceptLogin)
  
     formGridLayout.addWidget(descLabel, 0, 0, 1, 2)
     formGridLayout.addWidget(labelUsername, 1, 0, 1, 1, Qt.AlignRight)
     formGridLayout.addWidget(self.editUserName, 1, 1)
     formGridLayout.addWidget(labelPassword, 2, 0, 1, 1, Qt.AlignRight)
     formGridLayout.addWidget(self.editPassword, 2, 1)
     formGridLayout.addWidget(buttons, 3, 0, 1, 2, Qt.AlignBottom)
     formGridLayout.setRowStretch(0, 0)
     formGridLayout.setRowStretch(1, 0)
     formGridLayout.setRowStretch(2, 0)
     formGridLayout.setRowStretch(3, 1)
     
     self.setMaximumHeight(self.sizeHint().height())
     self.setMinimumHeight(self.sizeHint().height())
     #self.setMinimumWidth(400)
     self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
示例#23
0
    def __init__(self):
        super(ForceUpgradeDialog, self).__init__()
        vbox = QVBoxLayout(self)

        self.setWindowTitle(u"El contenido debe actualizarse")

        self.main_text = QLabel(UPGRADE_TEXT)
        vbox.addWidget(self.main_text)

        bbox = QDialogButtonBox()
        bbox.addButton(QPushButton(u"Salir del programa"),
                       QDialogButtonBox.AcceptRole)
        bbox.accepted.connect(self.accept)
        bbox.addButton(QPushButton(u"Continuar"),
                       QDialogButtonBox.RejectRole)
        bbox.rejected.connect(self.reject)
        vbox.addWidget(bbox)
        self.show()
    def __init__(self, parent):
        super(LunchinatorSettingsDialog, self).__init__(parent, Qt.Dialog)

        self.setWindowTitle("Lunchinator Settings")
        # self.setModal(True)
        self.setResult(QDialog.Rejected)

        contentLayout = QVBoxLayout(self)

        self.nb = ComboTabWidget(self)
        self.nb.setTabPosition(QTabWidget.North)

        self.widget_containers = {}
        self.widget_names = []
        try:
            if get_settings().get_plugins_enabled():
                for pluginInfo in get_plugin_manager().getAllPlugins():
                    if pluginInfo.plugin_object.is_activated:
                        self.addPlugin(pluginInfo.plugin_object, pluginInfo.name, pluginInfo.category)
        except:
            getCoreLogger().exception("while including plugins in settings window")

        contentLayout.addWidget(self.nb)
        # d.get_content_area().pack_start(nb, True, True, 0)
        if self.nb.count() > 0:
            self.nb.setCurrentIndex(0)
            # show first widget
            self.nb.widget(0).showContents()

        buttonBox = QDialogButtonBox(Qt.Horizontal, self)

        saveButton = QPushButton("Save", self)
        # saveButton.setAutoDefault(True)
        saveButton.clicked.connect(self.savePressed)
        buttonBox.addButton(saveButton, QDialogButtonBox.AcceptRole)

        cancelButton = QPushButton("Cancel", self)
        cancelButton.clicked.connect(self.cancelPressed)
        buttonBox.addButton(cancelButton, QDialogButtonBox.RejectRole)

        applyButton = QPushButton("Apply", self)
        applyButton.clicked.connect(self.applyPressed)
        buttonBox.addButton(applyButton, QDialogButtonBox.ApplyRole)

        discardButton = QPushButton("Discard", self)
        discardButton.clicked.connect(self.discardPressed)
        buttonBox.addButton(discardButton, QDialogButtonBox.ApplyRole)

        contentLayout.addWidget(buttonBox)

        get_notification_center().connectPluginActivated(self._pluginActivated)
        get_notification_center().connectPluginWillBeDeactivated(self._pluginWillBeDeactivated)
示例#25
0
 def __init__(self, widget, parent = None):
 
     QDialog.__init__(self, parent)
     
     # We keep a reference to the widget in the form.
     self.widget = widget
     try:
         self.type = type(widget.paramDefault).__name__
     except AttributeError:
         try:
             self.type = type(widget.paramMin).__name__
         except AttributeError:
             self.type = "Bang"
     
     self.address = QLineEdit(self)
     self.address.setText(widget.paramPath)
     self.address.setSelection(0, self.address.maxLength())
     
     self.default = [None for i in range(self.widget.length)]
     self.max = [None for i in range(self.widget.length)]
     self.min = [None for i in range(self.widget.length)]
     self.standardActions = [None for i in range(self.widget.length)]
     self.setupAtoms()
     self.setValues()
     
     buttonBox = QDialogButtonBox()
     okButton = buttonBox.addButton(buttonBox.Ok)
     cancelButton = buttonBox.addButton(buttonBox.Cancel)
     
     self.connect(okButton, SIGNAL("clicked()"),
                  self.updateWidget)
     self.connect(cancelButton, SIGNAL("clicked()"),
                  self, SLOT("reject()"))
     
     layout = QVBoxLayout()
     layout.addWidget(QLabel("OSC Path", self))
     layout.addWidget(self.address)
     self.setupAtomUi(layout)
     layout.addWidget(buttonBox)
     self.setLayout(layout)
     
     self.setWindowTitle(self.tr("Edit Malarm Properties"))
示例#26
0
 def add_button_box(self, stdbtns):
     """Create dialog button box and add it to the dialog layout"""
     bbox = QDialogButtonBox(stdbtns)
     run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole)
     self.connect(run_btn, SIGNAL('clicked()'), self.run_btn_clicked)
     self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()"))
     self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()"))
     btnlayout = QHBoxLayout()
     btnlayout.addStretch(1)
     btnlayout.addWidget(bbox)
     self.layout().addLayout(btnlayout)
示例#27
0
 def add_button_box(self, stdbtns):
     """Create dialog button box and add it to the dialog layout"""
     bbox = QDialogButtonBox(stdbtns)
     run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole)
     self.connect(run_btn, SIGNAL('clicked()'), self.run_btn_clicked)
     self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()"))
     self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()"))
     btnlayout = QHBoxLayout()
     btnlayout.addStretch(1)
     btnlayout.addWidget(bbox)
     self.layout().addLayout(btnlayout)
示例#28
0
 def widget(self,parent):
     td = ListPickerDialog(self, parent)
     td.setWindowTitle("Select Server")
     td.setAttribute(Qt.WA_DeleteOnClose)
     layout = QHBoxLayout();
     layout.setContentsMargins(16, 0, 16, 8)
     
     view = self.view()
     if not view:
         listView = QListView()
         listView.setEditTriggers( QAbstractItemView.NoEditTriggers)
         listView.setModel(self.model())
         listView.setModelColumn(self.modelColumn())
         if listView.sizeHintForRow(0)>0:
             listView.setMinimumHeight(listView.sizeHintForRow(0) * 5)
         view = listView
     else:
         view.setModel(self.model())
     
     layout.addWidget(view)
     self.setView(view)
     
     if self.model():
         index = self.model().index(self.currentIndex(), self.modelColumn())
         self.selectModelIndex(index)
     
     btnbox = QDialogButtonBox(Qt.Vertical)
     btnbox.addButton("Select", QDialogButtonBox.AcceptRole)
     addBtn = btnbox.addButton("Add", QDialogButtonBox.ActionRole)
     addBtn.clicked.connect(self.addServer)
     editBtn = btnbox.addButton("Edit", QDialogButtonBox.ActionRole)
     editBtn.clicked.connect(self.editServer)
     remBtn = btnbox.addButton("Remove", QDialogButtonBox.ActionRole)
     remBtn.clicked.connect(self.remServer)
     btnbox.accepted.connect( td.accept)
     btnbox.rejected.connect( td.reject)
     layout.addWidget(btnbox)
     
     td.setLayout(layout)
     return td
示例#29
0
    def __init__(self, main_window):
        super(WizardDialog, self).__init__()
        self.mw = main_window
        vbox = QVBoxLayout(self)

        # label and checkbox
        self.main_text = QLabel(u"init text")
        vbox.addWidget(self.main_text)
        self.notthisagain = QCheckBox(u"No mostrar automáticamente esta ayuda")
        nowizard = config.get('nowizard', False)
        self.notthisagain.setCheckState(nowizard)
        self.notthisagain.stateChanged.connect(self._notthisagain_toggled)
        vbox.addWidget(self.notthisagain)

        # buttons
        bbox = QDialogButtonBox()
        self.navbut_actn = QPushButton(u"init text")
        bbox.addButton(self.navbut_actn, QDialogButtonBox.ActionRole)
        self.navbut_prev = QPushButton(u"Anterior")
        bbox.addButton(self.navbut_prev, QDialogButtonBox.ActionRole)
        self.navbut_next = QPushButton(u"Siguiente")
        bbox.addButton(self.navbut_next, QDialogButtonBox.ActionRole)
        vbox.addWidget(bbox)

        self.show()
        self.step = 0
        self._move(0)
示例#30
0
    def __init__(self, main_window):
        super(WizardDialog, self).__init__()
        self.mw = main_window
        vbox = QVBoxLayout(self)

        # label and checkbox
        self.main_text = QLabel(u"init text")
        vbox.addWidget(self.main_text)
        self.notthisagain = QCheckBox(u"No mostrar automáticamente esta ayuda")
        nowizard = config.get('nowizard', False)
        self.notthisagain.setCheckState(nowizard)
        self.notthisagain.stateChanged.connect(self._notthisagain_toggled)
        vbox.addWidget(self.notthisagain)

        # buttons
        bbox = QDialogButtonBox()
        self.navbut_actn = QPushButton(u"init text")
        bbox.addButton(self.navbut_actn, QDialogButtonBox.ActionRole)
        self.navbut_prev = QPushButton(u"Anterior")
        bbox.addButton(self.navbut_prev, QDialogButtonBox.ActionRole)
        self.navbut_next = QPushButton(u"Siguiente")
        bbox.addButton(self.navbut_next, QDialogButtonBox.ActionRole)
        vbox.addWidget(bbox)

        self.show()
        self.step = 0
        self._move(0)
示例#31
0
    def __init__(self, client):
        super(TableList, self).__init__(None)
        self.autoStarted = False
        self.client = client
        self.setObjectName('TableList')
        self.resize(700, 400)
        self.view = MJTableView(self)
        self.differ = None
        self.debugModelTest = None
        self.requestedNewTable = False
        self.view.setItemDelegateForColumn(2,
                                           RichTextColumnDelegate(self.view))

        buttonBox = QDialogButtonBox(self)
        self.newButton = buttonBox.addButton(
            m18nc('allocate a new table', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.setToolTip(m18n("Allocate a new table"))
        self.newButton.clicked.connect(self.client.newTable)
        self.joinButton = buttonBox.addButton(m18n("&Join"),
                                              QDialogButtonBox.AcceptRole)
        self.joinButton.clicked.connect(client.joinTable)
        self.joinButton.setIcon(KIcon("list-add-user"))
        self.joinButton.setToolTip(m18n("Join a table"))
        self.leaveButton = buttonBox.addButton(m18n("&Leave"),
                                               QDialogButtonBox.AcceptRole)
        self.leaveButton.clicked.connect(self.leaveTable)
        self.leaveButton.setIcon(KIcon("list-remove-user"))
        self.leaveButton.setToolTip(m18n("Leave a table"))
        self.compareButton = buttonBox.addButton(
            m18nc('Kajongg-Ruleset', 'Compare'), QDialogButtonBox.AcceptRole)
        self.compareButton.clicked.connect(self.compareRuleset)
        self.compareButton.setIcon(KIcon("preferences-plugin-script"))
        self.compareButton.setToolTip(
            m18n('Compare the rules of this table with my own rulesets'))
        self.chatButton = buttonBox.addButton(m18n('&Chat'),
                                              QDialogButtonBox.AcceptRole)
        self.chatButton.setIcon(KIcon("call-start"))
        self.chatButton.clicked.connect(self.chat)
        self.startButton = buttonBox.addButton(m18n('&Start'),
                                               QDialogButtonBox.AcceptRole)
        self.startButton.clicked.connect(self.startGame)
        self.startButton.setIcon(KIcon("arrow-right"))
        self.startButton.setToolTip(
            m18n(
                "Start playing on a table. Empty seats will be taken by robot players."
            ))

        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(buttonBox)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)

        self.view.doubleClicked.connect(client.joinTable)
        StateSaver(self, self.view.horizontalHeader())
        self.updateButtonsForTable(None)
示例#32
0
    def _create_buttons ( self, dialog, layout ):
        """ Creates the buttons.
        """
        # Create the button:
        buttons = QDialogButtonBox()

        if self.can_cancel:
            buttons.addButton( self.cancel_button_label,
                               QDialogButtonBox.RejectRole )

        buttons.addButton( QDialogButtonBox.Ok )

        # TODO: hookup the buttons to our methods, this may involve subclassing
        # from QDialog

        if self.can_cancel:
            buttons.connect( buttons, SIGNAL( 'rejected()' ), dialog,
                             SLOT( 'reject() ' ) )
        buttons.connect( buttons, SIGNAL( 'accepted()' ), dialog,
                         SLOT( 'accept()' ) )

        layout.addWidget( buttons )
示例#33
0
 def addPathList(self, key, predefs):
     if not self.overwriteKeys(key) and type(key).__name__ == 'str':
         layout = QVBoxLayout()
         pathList = ListItem()  ##XXX
         pathList.setDragDropMode(QAbstractItemView.InternalMove)
         if len(predefs) > 0:
             if not self.checkUnifiedTypes(predefs):
                 return -1
             for predef in predefs:
                 pathList.addSingleItem(str(predef))
         hbox = QHBoxLayout()
         buttonbox = QDialogButtonBox()
         combo = QComboBox()
         combo.setMinimumContentsLength(20)
         self.connect(combo, SIGNAL("editTextChanged(QString)"),
                      self.argumentChanged)
         self.connect(combo, SIGNAL("currentIndexChanged(QString)"),
                      self.argumentChanged)
         combo.addItem(self.inputFile)
         combo.addItem(self.inputDirectory)
         add = PathSelectionButton(self, key, pathList, combo)
         buttonbox.addButton(add, QDialogButtonBox.ActionRole)
         rm = rmLocalPathButton(self, pathList)
         buttonbox.addButton(rm, QDialogButtonBox.ActionRole)
         self.connect(add, SIGNAL("clicked()"), self.argumentChanged)
         self.connect(rm, SIGNAL("clicked()"), self.argumentChanged)
         hbox.addWidget(buttonbox, 3, Qt.AlignLeft)
         hbox.addWidget(combo, 1, Qt.AlignRight)
         layout.addLayout(hbox, 0)
         layout.addWidget(pathList, 2)
         if not self.displaykey:
             self.layout.addRow(layout)
         else:
             self.layout.addRow(key, layout)
         self.widgets[key] = pathList
         return 1
     else:
         return -1
示例#34
0
class UnlockTalkWidget(QDialog):
    def __init__(self, parent=None):
        super(UnlockTalkWidget, self).__init__(parent)
        self.setWindowTitle('Unlock Talk Details')

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.information = QLabel('Enter the password to unlock the talks')
        self.layout.addWidget(self.information)

        self.passwordBox = QLineEdit()
        self.layout.addWidget(self.passwordBox)

        self.buttonBox = QDialogButtonBox(Qt.Horizontal)
        self.layout.addWidget(self.buttonBox)

        self.unlockButton = QPushButton('Unlock')
        self.cancelButton = QPushButton('Cancel')
        self.buttonBox.addButton(self.unlockButton,
                                 QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(self.cancelButton,
                                 QDialogButtonBox.RejectRole)
示例#35
0
    def __init__(self, parent=None, url_to_download=None, fout=None):
        " init class "
        super(Downloader, self).__init__(parent)
        self.timer = time()
        self.httpGetId = 0
        self.httpRequestAborted = False
        self.url = QUrl(url_to_download)
        self.fileInfo = QFileInfo(self.url.path())
        self.fout = fout
        self.fileName = path.join(fout, str(self.fileInfo.fileName()))
        self.statusLabel = QLabel(
            "<center><h3>Downloading from:</h3>%s<h3>Saving to:</h3>%s</center>" % (url_to_download, fout)
        )
        self.bytes = QLabel(" ??? ")
        self.closeButton = QPushButton(" Cancel ")
        self.closeButton.setAutoDefault(False)
        self.progressBar = QProgressBar()

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)

        self.http = QHttp(self)
        self.http.requestFinished.connect(self.httpRequestFinished)
        self.http.dataReadProgress.connect(self.updateDataReadProgress)
        self.http.responseHeaderReceived.connect(self.readResponseHeader)
        self.closeButton.clicked.connect(self.cancelDownload)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(self.progressBar)
        mainLayout.addWidget(self.bytes)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle(__doc__ + " - MultiThreaded Downloader ")
        self.resize(parent.size().width(), self.size().height())
        self.downloadFile(url_to_download, fout)
示例#36
0
class StaffDataDlg(QDialog):

    def __init__(self, parent=None):
        super(StaffDataDlg, self).__init__(parent)
        self.create_widgets()
        self.layout_widgets()
        
        self.setMinimumWidth(850)
        self.setWindowTitle(u'Список сотрудников компании')


    def create_widgets(self):
        self.model = QSqlTableModel(self)
        

        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QTableView.SingleSelection)
        self.view.setSelectionBehavior(QTableView.SelectRows)
        
        self.view.resizeColumnsToContents()

        self.buttonBox = QDialogButtonBox()
        self.addButton = self.buttonBox.addButton(u"&Добавить",
                QDialogButtonBox.ActionRole)
        self.deleteButton = self.buttonBox.addButton(u"&Удалить",
                QDialogButtonBox.ActionRole)
        self.sortButton = self.buttonBox.addButton(u"&Сортировать",
                QDialogButtonBox.ActionRole)
        

    def layout_widgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)
示例#37
0
class UnlockTalkWidget(QDialog):

    def __init__(self, parent=None):
        super(UnlockTalkWidget, self).__init__(parent)
        self.setWindowTitle('Unlock Talk Details')

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.information = QLabel('Enter the password to unlock the talks')
        self.layout.addWidget(self.information)

        self.passwordBox = QLineEdit()
        self.layout.addWidget(self.passwordBox)

        self.buttonBox = QDialogButtonBox(Qt.Horizontal)
        self.layout.addWidget(self.buttonBox)

        self.unlockButton = QPushButton('Unlock')
        self.cancelButton = QPushButton('Cancel')
        self.buttonBox.addButton(
            self.unlockButton, QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(
            self.cancelButton, QDialogButtonBox.RejectRole)
示例#38
0
    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 400, 100 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )

        # Check boxes
        self.includeClassesBox = QCheckBox( self )
        self.includeClassesBox.setText( "Show &classes in modules" )
        self.includeClassesBox.setChecked( self.options.includeClasses )
        self.includeClassesBox.stateChanged.connect( self.__updateOptions )
        self.includeFuncsBox = QCheckBox( self )
        self.includeFuncsBox.setText( "Show &functions in modules" )
        self.includeFuncsBox.setChecked( self.options.includeFuncs )
        self.includeFuncsBox.stateChanged.connect( self.__updateOptions )
        self.includeGlobsBox = QCheckBox( self )
        self.includeGlobsBox.setText( "Show &global variables in modules" )
        self.includeGlobsBox.setChecked( self.options.includeGlobs )
        self.includeGlobsBox.stateChanged.connect( self.__updateOptions )
        self.includeDocsBox = QCheckBox( self )
        self.includeDocsBox.setText( "Show modules &docstrings" )
        self.includeDocsBox.setChecked( self.options.includeDocs )
        self.includeDocsBox.stateChanged.connect( self.__updateOptions )
        self.includeConnTextBox = QCheckBox( self )
        self.includeConnTextBox.setText( "Show connection &labels" )
        self.includeConnTextBox.setChecked( self.options.includeConnText )
        self.includeConnTextBox.stateChanged.connect( self.__updateOptions )

        verticalLayout.addWidget( self.includeClassesBox )
        verticalLayout.addWidget( self.includeFuncsBox )
        verticalLayout.addWidget( self.includeGlobsBox )
        verticalLayout.addWidget( self.includeDocsBox )
        verticalLayout.addWidget( self.includeConnTextBox )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel )
        generateButton = buttonBox.addButton( "Generate",
                                              QDialogButtonBox.ActionRole )
        generateButton.setDefault( True )
        generateButton.clicked.connect( self.accept )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.close )
        return
示例#39
0
    def __init__(self, client):
        super(TableList, self).__init__(None)
        self.autoStarted = False
        self.client = client
        self.setObjectName('TableList')
        self.resize(700, 400)
        self.view = MJTableView(self)
        self.differ = None
        self.debugModelTest = None
        self.requestedNewTable = False
        self.view.setItemDelegateForColumn(2, RichTextColumnDelegate(self.view))

        buttonBox = QDialogButtonBox(self)
        self.newButton = buttonBox.addButton(m18nc('allocate a new table', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.setToolTip(m18n("Allocate a new table"))
        self.newButton.clicked.connect(self.client.newTable)
        self.joinButton = buttonBox.addButton(m18n("&Join"), QDialogButtonBox.AcceptRole)
        self.joinButton.clicked.connect(client.joinTable)
        self.joinButton.setIcon(KIcon("list-add-user"))
        self.joinButton.setToolTip(m18n("Join a table"))
        self.leaveButton = buttonBox.addButton(m18n("&Leave"), QDialogButtonBox.AcceptRole)
        self.leaveButton.clicked.connect(self.leaveTable)
        self.leaveButton.setIcon(KIcon("list-remove-user"))
        self.leaveButton.setToolTip(m18n("Leave a table"))
        self.compareButton = buttonBox.addButton(m18nc('Kajongg-Ruleset','Compare'), QDialogButtonBox.AcceptRole)
        self.compareButton.clicked.connect(self.compareRuleset)
        self.compareButton.setIcon(KIcon("preferences-plugin-script"))
        self.compareButton.setToolTip(m18n('Compare the rules of this table with my own rulesets'))
        self.chatButton = buttonBox.addButton(m18n('&Chat'), QDialogButtonBox.AcceptRole)
        self.chatButton.setIcon(KIcon("call-start"))
        self.chatButton.clicked.connect(self.chat)
        self.startButton = buttonBox.addButton(m18n('&Start'), QDialogButtonBox.AcceptRole)
        self.startButton.clicked.connect(self.startGame)
        self.startButton.setIcon(KIcon("arrow-right"))
        self.startButton.setToolTip(m18n("Start playing on a table. Empty seats will be taken by robot players."))

        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(buttonBox)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)

        self.view.doubleClicked.connect(client.joinTable)
        StateSaver(self, self.view.horizontalHeader())
        self.updateButtonsForTable(None)
示例#40
0
 def _initUI(self, text):
     layout = QVBoxLayout(self)
     layout.setContentsMargins(0, 10, 0, 0)
     layout.setSpacing(5)
     
     labelLayout = QHBoxLayout()
     if not text:
         text = u"Some plugins cannot be activated due to missing requirements:"
     label = QLabel(text, self)
     label.setWordWrap(True)
     labelLayout.addWidget(label)
     labelLayout.setContentsMargins(10, 0, 0, 0)
     layout.addLayout(labelLayout)
     
     self._reqTable = QTreeWidget(self)
     self._reqTable.setSortingEnabled(False)
     self._reqTable.setHeaderHidden(False)
     self._reqTable.setAlternatingRowColors(True)
     self._reqTable.setIndentation(0)
     self._reqTable.setUniformRowHeights(True)
     self._reqTable.setObjectName(u"__ERROR_LOG_")
     self._reqTable.setColumnCount(3)
     self._reqTable.setHeaderLabels([u"Package", u"Problem", u"Required by"])
     
     self._reqTable.setFrameShape(QFrame.StyledPanel)
     if getPlatform() == PLATFORM_MAC:
         self._reqTable.setAttribute(Qt.WA_MacShowFocusRect, False)
         self._reqTable.setStyleSheet("QFrame#__ERROR_LOG_{border-width: 1px; border-top-style: solid; border-right-style: none; border-bottom-style: solid; border-left-style: none; border-color:palette(mid)}");
         
     layout.addWidget(self._reqTable)
     
     buttonBox = QDialogButtonBox(Qt.Horizontal, self)
     ignore = QPushButton(u"Ignore", self)
     deactivate = QPushButton(u"Deactivate", self)
     install = QPushButton(u"Install Selected", self)
     install.setEnabled(self._canInstall)
     buttonBox.addButton(deactivate, QDialogButtonBox.DestructiveRole)
     buttonBox.addButton(ignore, QDialogButtonBox.RejectRole)
     buttonBox.addButton(install, QDialogButtonBox.AcceptRole)
     deactivate.clicked.connect(self._deactivate)
     ignore.clicked.connect(self._ignore)
     buttonBox.accepted.connect(self.accept)
     bottomLayout = QHBoxLayout()
     bottomLayout.addWidget(buttonBox, 1, Qt.AlignRight)
     layout.addLayout(bottomLayout)
示例#41
0
class ConfirmationDialog(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        save = QPushButton(self.trUtf8('&Save'))
        save.clicked.connect(self.close)
        close = QPushButton(self.trUtf8('Close &without saving'))
        close.clicked.connect(self.close)
        cancel = QPushButton(self.trUtf8('&Cancel'))
        cancel.clicked.connect(self.close)
        self.buttons = QDialogButtonBox()
        self.buttons.addButton(save, QDialogButtonBox.AcceptRole)
        self.buttons.addButton(close, QDialogButtonBox.HelpRole)
        self.buttons.addButton(cancel, QDialogButtonBox.RejectRole)
        label = QLabel(self.trUtf8(
            "You've got some unsaved changes. What would you like to do?"))
        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(self.buttons)
        self.setLayout(layout)
示例#42
0
class StaffDataDlg(QDialog):

    def __init__(self, parent=None):
        super(StaffDataDlg, self).__init__(parent)
        self.create_widgets()
        self.layout_widgets()
        self.create_connections()
        self.setMinimumWidth(850)
        self.setWindowTitle(u'Список сотрудников компании')

    def create_widgets(self):
        
        self.model = QtSql.QSqlRelationalTableModel(self)
        self.model.setTable("employee")
        self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
        self.model.setRelation(CITY, QtSql.QSqlRelation('cities', 'city_id', 'name'))
        self.model.setRelation(DEPARTMENT, QtSql.QSqlRelation('deps', 'dep_id', 'name'))

        self.model.setSort(ID, Qt.AscendingOrder)
        self.model.setHeaderData(ID, Qt.Horizontal, QVariant("ID"))
        
        self.model.setHeaderData(CITY, Qt.Horizontal,
                QVariant("City"))
        self.model.setHeaderData(DEPARTMENT, Qt.Horizontal,
                QVariant("Department"))
        self.model.setHeaderData(FIRSTNAME, Qt.Horizontal,
                QVariant("First Name"))
        self.model.setHeaderData(LASTNAME, Qt.Horizontal,
                QVariant("Last Name"))
        self.model.setHeaderData(SEX, Qt.Horizontal,
                QVariant("sex"))
        self.model.setHeaderData(ADDRESS, Qt.Horizontal,
                QVariant("Address"))
        self.model.setHeaderData(PID, Qt.Horizontal,
                QVariant("PID"))
        
        self.model.setHeaderData(TITLE, Qt.Horizontal,
                QVariant("Title"))
        
        self.model.setHeaderData(SOLARY, Qt.Horizontal,
                QVariant("SOLARY"))
        self.model.setHeaderData(SHIFT, Qt.Horizontal,
                QVariant("SHIFT"))
        self.model.setHeaderData(HOURS, Qt.Horizontal,
                QVariant("HOURS"))
        
        self.model.select()
    

        self.view = QTableView()
        self.view.setModel(self.model)
        
        self.view.setItemDelegate(QtSql.QSqlRelationalDelegate(self))
        
        self.view.setColumnHidden(ID, True)
        self.view.resizeColumnsToContents()

        self.buttonBox = QDialogButtonBox()
        self.addCity = self.buttonBox.addButton(u"&Добавить City",
                QDialogButtonBox.ActionRole)
        self.addDep = self.buttonBox.addButton(u"&Добавить Department",
                QDialogButtonBox.ActionRole)
        self.addButton = self.buttonBox.addButton(u"&Добавить",
                QDialogButtonBox.ActionRole)
        self.deleteButton = self.buttonBox.addButton(u"&Удалить",
                QDialogButtonBox.ActionRole)
        self.sortButton = self.buttonBox.addButton(u"&Сортировать",
                QDialogButtonBox.ActionRole)
        

        menu = QMenu(self)
        self.sortByTitleAction = menu.addAction(u"Сортировка по &Title")
        self.sortBySolaryAction = menu.addAction(
                u"Сортировка по &SOLARY")
        self.sortByIDAction = menu.addAction(u"Сортировка по &ID")
        self.sortButton.setMenu(menu)
        self.closeButton = self.buttonBox.addButton(QDialogButtonBox.Close)


    def layout_widgets(self):
        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def create_connections(self):
        self.addButton.clicked.connect(self.addRecord)
        self.deleteButton.clicked.connect(self.deleteRecord)
        self.addCity.clicked.connect(self.editCities)
        
        self.sortByTitleAction.triggered.connect(
                lambda: self.sort(TITLE))
        self.sortBySolaryAction.triggered.connect(
                lambda: self.sort(SOLARY))
        self.sortByIDAction.triggered.connect(lambda: self.sort(ID))
        self.closeButton.clicked.connect(self.accept)

    def addRecord(self):
        row = self.model.rowCount()
        self.model.insertRow(row)
        index = self.model.index(row, TITLE)
        self.view.setCurrentIndex(index)
        self.view.edit(index)


    def deleteRecord(self):
        index = self.view.currentIndex()
        if not index.isValid():
            return
        record = self.model.record(index.row())
        title = record.value(TITLE).toString()
        desc = record.value(SOLARY).toString()
        if (QMessageBox.question(self, "Reference Data",
                QString("Delete %1 from title %2?")
                .arg(desc).arg(title),
                QMessageBox.Yes|QMessageBox.No) ==
                QMessageBox.No):
            return
        self.model.removeRow(index.row())
        self.model.submitAll()


    def sort(self, column):
        self.model.setSort(column, Qt.AscendingOrder)
        self.model.select()

    def editCities(self):
        form = ReferenceDataDlg("cities", "Cities", self)
        form.exec_()
示例#43
0
class _QueuedMessageWidget(QWidget):
    
    cleared = pyqtSignal()
    finished = pyqtSignal()
    shown = pyqtSignal()
    closed = pyqtSignal()
    linkActivated = pyqtSignal(unicode)
    linkHovered= pyqtSignal(unicode)
    buttonClicked = pyqtSignal(QAbstractButton)
    
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self._messages = []
        self._defaultTimeout = 0
        self._defaultPixmap = QPixmap(":/enkiicons/infos.png" )
        self._defaultBackground = QBrush( QColor( 250, 230, 147 ) )
        self._defaultForeground = QBrush( QColor( 0, 0, 0 ) )
        
        # pixmap
        self.lPixmap = QLabel( self )
        self.lPixmap.setAlignment( Qt.AlignCenter )
        self.lPixmap.setSizePolicy( QSizePolicy( QSizePolicy.Maximum, QSizePolicy.Preferred ) )
        
        # message
        self.lMessage = QLabel( self )
        self.lMessage.setAlignment( Qt.AlignVCenter | Qt.AlignLeft )
        self.lMessage.setSizePolicy( QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) )
        self.lMessage.setWordWrap( True )
        self.lMessage.setOpenExternalLinks( True )
        self.lMessage.setTextInteractionFlags( Qt.TextBrowserInteraction )
        
        # button
        self.dbbButtons = QDialogButtonBox( self )
        
        # if false - buttons don't have neither text nor icons
        self.dbbButtons.setStyleSheet("dialogbuttonbox-buttons-have-icons: true;")

        self.dbbButtons.setSizePolicy( QSizePolicy( QSizePolicy.Maximum, QSizePolicy.Preferred ) )
        
        self.setSizePolicy( QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Maximum ) )
        
        # layout
        self.hbl = QHBoxLayout( self )
        self.hbl.setMargin( 0 )
        self.hbl.addWidget( self.lPixmap, 0, Qt.AlignCenter )
        self.hbl.addWidget( self.lMessage )
        self.hbl.addWidget( self.dbbButtons, 0, Qt.AlignCenter )
        
        # connections
        self.lMessage.linkActivated.connect(self.linkActivated)
        self.lMessage.linkHovered.connect(self.linkHovered)
        self.dbbButtons.clicked.connect(self.buttonClicked)

    def sizeHint(self):
        return QWidget.minimumSizeHint(self)

    def openExternalLinks(self):
        return self.lMessage.openExternalLinks()

    def defaultTimeout(self):
        return self._defaultTimeout

    def defaultPixmap(self):
        return self._defaultPixmap

    def defaultBackground(self):
        return self._defaultBackground

    def defaultForeground(self):
        return self._defaultForeground

    def currentMessageInformations(self):
        return self.currentMessagePixmap(), self.currentMessageBackground(), self.currentMessageForeground()

    def pendingMessageCount(self):
        return len(self._messages)

    def currentMessage(self):
        return self._messages[0]

    def append(self, message, milliSeconds ):
        msg = _QueuedMessage()
        msg.message = message
        if milliSeconds == -1:
            msg.milliSeconds = self._defaultTimeout
        else:
           msg.milliSeconds = milliSeconds
        msg.pixmap = self._defaultPixmap
        msg.background = self._defaultBackground
        msg.foreground = self._defaultForeground
        
        self._messages.append(msg)
            
        if  len(self._messages) == 1 :
            QTimer.singleShot( 0, self.showMessage)

    def setOpenExternalLinks(self, open ):
        self.lMessage.setOpenExternalLinks( open )

    def setDefaultTimeout(self, timeout ):
        self._defaultTimeout = timeout

    def setDefaultPixmap(self, pixmap ):
        self._defaultPixmap = pixmap

    def setDefaultBackground(self, brush ):
        self._defaultBackground = brush

    def setDefaultForeground(self, brush ):
        self._defaultForeground = brush

    def remove(self, message ):
        raise NotImplemented()  # incorrect port from cpp fresh
        if not self._messages or self._messages.first() == message:
            return

        self._messages.removeOne( message )

    def clear(self):
        self._messages.clear()
        self.lPixmap.clear()
        self.lMessage.clear()
        self.dbbButtons.clear()
        self.cleared.emit()

    def currentMessagePixmap(self):
        msg = self.currentMessage()
        if msg.pixmap.isNull():
            return self._defaultPixmap
        else:
            return msg.pixmap

    def currentMessageBackground(self):
        msg = self.currentMessage()
        if msg.background == QBrush( Qt.NoBrush ):
            return self._defaultBackground
        else:
            return msg.background

    def currentMessageForeground(self):
        msg = self.currentMessage()
        if msg.foreground == QBrush( Qt.NoBrush ):
            return self._defaultForeground
        else:
            return msg.foreground

    def paintEvent(self, event ):
        if  self.pendingMessageCount() == 0 :
            QWidget.paintEvent(self, event )
            return
        
        painter = QPainter( self )
        painter.setPen( Qt.NoPen )
        painter.setBrush( self.currentMessageBackground() )
        painter.drawRect( self.contentsRect() )

    def buttonClicked(self, button ):
        msg = self.currentMessage()
        standardButton = self.dbbButtons.standardButton( button )
        
        if msg.slot is not None:
            msg.slot(standardButton, msg)
        
        self.closeMessage()

    def showMessage(self):
        # get message
        msg = self.currentMessage()
        
        # update palette
        pal = self.lMessage.palette()
        pal.setBrush( self.lMessage.foregroundRole(), self.currentMessageForeground() )
        self.lMessage.setPalette( pal )
        
        # format widget
        self.lPixmap.setPixmap( self.currentMessagePixmap() )
        self.lMessage.setText( msg.message )
        self.lMessage.setToolTip( msg.message )
        self.lMessage.setWhatsThis( msg.message )
        
        # set buttons
        if not msg.buttons:
            msg.buttons[ QDialogButtonBox.Close ] = None

        self.dbbButtons.clear()
        
        for button in msg.buttons.keys():
            pb = self.dbbButtons.addButton( button )
            
            if button in msg.buttons:
                pb.setText( msg.buttons[ button ] )
        
        # auto close if needed
        if msg.milliSeconds == -1:
            timeout = self._defaultTimeout
        else:
            timeout =  msg.milliSeconds
        
        if  timeout > 0:
            QTimer.singleShot( timeout, self.closeMessage )
        
        # signal.emit
        self.shown.emit()

    def closeMessage(self):
        # message.emit
        self.closed.emit()
        
        # remove remove current message from hash
        self._messages = self._messages[1:]
        
        # process next if possible, clear gui
        if self._messages:
            QTimer.singleShot( 0, self.showMessage)
        else:
            QTimer.singleShot( 0, self.clearMessage)
        
        # finished.emit message if needed
        if not self._messages:
            self.finished.emit()

    def clearMessage(self):
        self.lPixmap.clear()
        self.lMessage.clear()
        self.dbbButtons.clear()
示例#44
0
class DeletionOptions(QDialog):
    def __init__(self, parent, model):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.model = model
        self._setupUi()
        self.model.view = self

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

    def _setupUi(self):
        self.setWindowTitle(tr("Deletion Options"))
        self.resize(400, 270)
        self.verticalLayout = QVBoxLayout(self)
        self.msgLabel = QLabel()
        self.verticalLayout.addWidget(self.msgLabel)
        self.linkCheckbox = QCheckBox(tr("Link deleted files"))
        self.verticalLayout.addWidget(self.linkCheckbox)
        text = tr(
            "After having deleted a duplicate, place a link targeting the reference file "
            "to replace the deleted file.")
        self.linkMessageLabel = QLabel(text)
        self.linkMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.linkMessageLabel)
        self.linkTypeRadio = RadioBox(items=[tr("Symlink"),
                                             tr("Hardlink")],
                                      spread=False)
        self.verticalLayout.addWidget(self.linkTypeRadio)
        if not self.model.supports_links():
            self.linkCheckbox.setEnabled(False)
            self.linkTypeRadio.setEnabled(False)
            self.linkCheckbox.setText(self.linkCheckbox.text() +
                                      tr(" (unsupported)"))
        self.directCheckbox = QCheckBox(tr("Directly delete files"))
        self.verticalLayout.addWidget(self.directCheckbox)
        text = tr(
            "Instead of sending files to trash, delete them directly. This option is usually "
            "used as a workaround when the normal deletion method doesn't work."
        )
        self.directMessageLabel = QLabel(text)
        self.directMessageLabel.setWordWrap(True)
        self.verticalLayout.addWidget(self.directMessageLabel)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole)
        self.verticalLayout.addWidget(self.buttonBox)

    #--- model --> view
    def update_msg(self, msg):
        self.msgLabel.setText(msg)

    def show(self):
        self.linkCheckbox.setChecked(self.model.link_deleted)
        self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0
        self.directCheckbox.setChecked(self.model.direct)
        result = self.exec()
        self.model.link_deleted = self.linkCheckbox.isChecked()
        self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1
        self.model.direct = self.directCheckbox.isChecked()
        return result == QDialog.Accepted
示例#45
0
class MainWidget(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.configOptions, self.checkBoxList, self.configBool = {}, {}, None
        # Check for root privileges
        if geteuid() != 0:
            msg = ("{} is not root. You need to run with root priviliges\n"
                   "Please use kdesudo, gksu or sudo/sux.").format(getuser())
            QMessageBox.critical(self, __doc__ + "- Error", msg)
            sys.exit(1)
        else:
            msg = "This tool is running with root priviliges."
            QMessageBox.warning(self, __doc__ + "- Warning", msg)
        # title, icon and sizes
        self.setWindowTitle(__doc__)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(2048, 2048)
        self.resize(600, 600)
        self.setWindowIcon(QIcon.fromTheme("preferences-system"))
        self.menuBar().addMenu("&File").addAction("Exit", exit)
        QShortcut("Ctrl+q", self, activated=lambda: self.close())
        # main group
        main_group = QGroupBox("Module configuration")
        self.setCentralWidget(main_group)
        self.layout = QVBoxLayout(main_group)
        # scrollarea widgets
        self.scrollArea, self.window = QScrollArea(), QWidget()
        self.layout.addWidget(self.scrollArea)
        self.vbox = QVBoxLayout(self.window)
        # Graphic effect
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.scrollArea.setGraphicsEffect(glow)
        glow.setEnabled(True)
        # config loading stuff
        self.findConfig(CONFIG_DIR)
        for eachOption in tuple(self.configOptions.keys()):

            self.readConfig(eachOption, self.configOptions)
            self.subLayout = QHBoxLayout()

            self.checkBoxName = "checkBox_" + eachOption
            checkBoxList = QCheckBox(self.checkBoxName, self)
            self.checkBoxList[self.checkBoxName] = checkBoxList
            checkBoxList.setObjectName(self.checkBoxName)
            checkBoxList.setText("Enable module {}".format(eachOption))

            if self.tooltip is not '':
                checkBoxList.setToolTip(self.tooltip)
            else:
                tooltip = "Configuration settings for {}".format(eachOption)
                checkBoxList.setToolTip(tooltip)

            if self.configBool:
                checkBoxList.setChecked(True)

            self.subLayout.addWidget(checkBoxList)
            self.vbox.addLayout(self.subLayout)
        self.scrollArea.setWidget(self.window)

        # Bottom Buttons Bar
        self.pushButtonSleep = QPushButton("Sleep")
        self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep")
        self.pushButtonSleep.clicked.connect(self.sleep)
        self.pushButtonHibernate = QPushButton("Hibernate")
        self.pushButtonHibernate.setToolTip(
            "Trigger Suspend to Disk Hibernate")
        self.pushButtonHibernate.clicked.connect(self.hibernate)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Close
                                          | QDialogButtonBox.Help)
        self.buttonBox.addButton(self.pushButtonHibernate,
                                 QDialogButtonBox.ActionRole)
        self.buttonBox.addButton(self.pushButtonSleep,
                                 QDialogButtonBox.ActionRole)
        self.layout.addWidget(self.buttonBox)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.writeConfig)
        self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))

    def closeEvent(self, event):
        ' Ask to Quit '
        the_conditional_is_true = QMessageBox.question(
            self, __doc__.title(), 'Quit ?.', QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        event.accept() if the_conditional_is_true else event.ignore()

    def sleep(self):
        """Method to make the computer Sleep."""
        try:
            sysfsFP = open("/sys/power/state", 'w')
        except:
            log.err("Couldn't open kernel interface")
            return False
        else:
            try:
                sysfsFP.write("mem")
            except:
                log.err("Couldn't write to kernel interface")
                return False

    def hibernate(self):
        """Method to make the computer Hibernate."""
        try:
            sysfsFP = open("/sys/power/state", 'w')
        except:
            log.err("Couldn't open kernel interface")
            return False
        else:
            try:
                sysfsFP.write("disk")
            except:
                log.err("Couldn't write to kernel interface")
                return False

    def writeConfig(self):
        """Method to get a configuration for the App."""
        finalResult = True
        for eachWriteOption in tuple(self.configOptions.keys()):
            checkBoxName = "checkBox_" + eachWriteOption
            if self.checkBoxList[checkBoxName].isChecked() is True:
                val = 1
            else:
                val = 0
            ret = self.populateValues(self.configOptions[eachWriteOption], val)

            if ret is False:
                log.debug("Couldn't apply setting for %s" % checkBoxName)
                finalResult = False

        if finalResult is False:
            QMessageBox.critical(self, "Error",
                                 "Couldn't apply all requested settings")
        else:
            QMessageBox.information(self, "Success",
                                    "Applied all requested settings")

    def populateValues(self, _path, value):
        """Method to populate values from a file path."""
        try:
            readHandle = open(_path, 'r')
            writeHandle = open(_path + ".tmp", 'w')
            for line in readHandle.readlines():
                if line.startswith(CONTROL_IDENTIFIER):
                    newline = line.split("=")[0] + "=" + str(value)
                    writeHandle.write(newline)
                    # You need this newline, otherwise the next line gets
                    # overlapped here
                    writeHandle.write("\n")
                else:
                    writeHandle.write(line)
            readHandle.close()
            writeHandle.close()
            move(_path + ".tmp", _path)
            return True
        except:
            log.debug("Failed in populateValues() when operating on %s" %
                      _path)
            return False

    def findConfig(self, configDir):
        """Take a configDir and find the configuration for the App."""
        if configDir is None:
            return False

        # TODO: Do we need to take care of the vendor specific overrides ???
        for configFile in listdir(configDir):
            if access(path.join(configDir, configFile), F_OK) is True:
                fn = path.join(configDir, configFile)
                self.configOptions[configFile.split(".")[0]] = fn
            else:
                pass

    def readConfig(self, key, configOptionsDict):
        """Take a key and dict and read the configurations for the App."""
        self.tooltip = ''

        if key is None or configOptionsDict is None:
            return False

        try:
            fileHandle = open(configOptionsDict[key], 'r')
        except:
            return False

        for line in fileHandle.readlines():
            if line.startswith(COMMENT_IDENTIFIER):
                self.tooltip = self.tooltip + line.lstrip(COMMENT_IDENTIFIER)
            elif line.startswith(CONTROL_IDENTIFIER):
                boolValue = line.split("=")[1]
                # Bloody boolValue could inherit the '\n' new line
                boolValue = boolValue.rstrip("\n")

                if boolValue == str(1) or "\"auto\"" in boolValue:
                    self.configBool = True
                else:
                    self.configBool = False

        # This will ensure that even if we don't read any string, tooltip
        # doesn't fail
        self.tooltip = self.tooltip + ''
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
示例#47
0
class EntityEditorDialog(QDialog, MapperMixin):
    """
    Dialog for editing entity attributes.
    """
    addedModel = pyqtSignal(object)

    def __init__(self,
                 entity,
                 model=None,
                 parent=None,
                 manage_documents=True,
                 collect_model=False,
                 parent_entity=None,
                 exclude_columns=[],
                 plugin=None):
        """
        Class constructor.
        :param entity: Entity object corresponding to a table object.
        :type entity: Entity
        :param model: Data object for loading data into the form widgets.
        If the model is set, then the editor dialog is assumed to be in edit
        mode.
        :type model: object
        :param parent: Parent widget that the form belongs to.
        :type parent: QWidget
        :param manage_documents: True if the dialog should provide controls
        for managing supporting documents. Only applicable if the entity
        allows for supporting documents to be attached.
        :type manage_documents: bool
        :param collect_model: If set to True only returns
        the filled form model without saving it to the database.
        :type collect_model: Boolean
        :param parent_entity: The parent entity of the editor
        :type parent_entity: Object
        :param exclude_columns: List of columns to be excluded if in a list.
        :type exclude_columns: List
        :return: If collect_model, returns SQLAlchemy Model
        """
        QDialog.__init__(self, parent)

        self.entity_table_model = {}

        self.collection_suffix = self.tr('Collection')

        #Set minimum width
        self.setMinimumWidth(450)

        self.plugin = plugin

        #Flag for mandatory columns
        self.has_mandatory = False
        self.reload_form = False
        self._entity = entity
        self.edit_model = model
        self.column_widgets = OrderedDict()
        self._parent = parent
        self.exclude_columns = exclude_columns
        self.entity_tab_widget = None
        self._disable_collections = False
        self.filter_val = None
        self.parent_entity = parent_entity
        self.child_models = OrderedDict()
        self.entity_scroll_area = None
        self.entity_editor_widgets = OrderedDict()
        # Set notification layout bar
        self.vlNotification = QVBoxLayout()
        self.vlNotification.setObjectName('vlNotification')
        self._notifBar = NotificationBar(self.vlNotification)
        self.do_not_check_dirty = False
        # Set manage documents only if the entity supports documents
        if self._entity.supports_documents:
            self._manage_documents = manage_documents
        else:
            self._manage_documents = False

        # Setup entity model
        self._ent_document_model = None
        if self._entity.supports_documents:
            self.ent_model, self._ent_document_model = entity_model(
                self._entity, with_supporting_document=True)
        else:
            self.ent_model = entity_model(self._entity)
        if not model is None:
            self.ent_model = model

        MapperMixin.__init__(self, self.ent_model, entity)

        self.collect_model = collect_model

        self.register_column_widgets()
        try:
            if isinstance(parent._parent, EntityEditorDialog):
                # hide collections form child editor
                self._disable_collections = True

        except AttributeError:
            self._parent._parent = None
        # Set title
        editor_trans = self.tr('Editor')
        if self._entity.label is not None:
            if self._entity.label != '':
                title_str = self._entity.label
            else:
                title_str = format_name(self._entity.short_name)
        else:
            title_str = format_name(self._entity.short_name)

        self.title = u'{0} {1}'.format(title_str, editor_trans)

        self.setWindowTitle(self.title)

        self._init_gui()
        self.adjustSize()

        self._get_entity_editor_widgets()

        if isinstance(parent._parent, EntityEditorDialog):
            self.parent_entity = parent.parent_entity
            self.set_parent_values()
            # make the size smaller to differentiate from parent and as it
            # only has few tabs.
            self.adjustSize()

        self.attribute_mappers = self._attr_mapper_collection

        # Exception title for editor extension exceptions
        self._ext_exc_msg = self.tr(
            'An error has occured while executing Python code in the editor '
            'extension:')

        # Register custom editor extension if specified
        self._editor_ext = entity_dlg_extension(self)
        if not self._editor_ext is None:
            self._editor_ext.post_init()

            # Initialize CascadingFieldContext objects
            self._editor_ext.connect_cf_contexts()

    def _init_gui(self):
        # Setup base elements
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName('glMain')
        self.gridLayout.addLayout(self.vlNotification, 0, 0, 1, 1)
        QApplication.processEvents()

        #set widgets values
        column_widget_area = self._setup_columns_content_area()

        self.gridLayout.addWidget(column_widget_area, 1, 0, 1, 1)

        QApplication.processEvents()
        # Add notification for mandatory columns if applicable
        next_row = 2
        if self.has_mandatory:
            self.required_fields_lbl = QLabel(self)
            msg = self.tr('Please fill out all required (*) fields.')
            msg = self._highlight_asterisk(msg)
            self.required_fields_lbl.setText(msg)
            self.gridLayout.addWidget(self.required_fields_lbl, next_row, 0, 1,
                                      2)
            # Bump up row reference
            next_row += 1

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setObjectName('buttonBox')
        self.gridLayout.addWidget(self.buttonBox, next_row, 0, 1, 1)

        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Save)

        if self.edit_model is None:
            if not self.collect_model:
                self.save_new_button = QPushButton(
                    QApplication.translate('EntityEditorDialog',
                                           'Save and New'))
                self.buttonBox.addButton(self.save_new_button,
                                         QDialogButtonBox.ActionRole)

        # edit model, collect model
        # adding new record for child

        # Saving in parent editor
        if not isinstance(self._parent._parent, EntityEditorDialog):
            # adding a new record
            if self.edit_model is None:
                # saving when digitizing.
                if self.collect_model:
                    self.buttonBox.accepted.connect(self.on_model_added)
                # saving parent editor
                else:
                    self.buttonBox.accepted.connect(self.save_parent_editor)
                    self.save_new_button.clicked.connect(self.save_and_new)
            # updating existing record
            else:
                if not self.collect_model:
                    # updating existing record of the parent editor
                    self.buttonBox.accepted.connect(self.save_parent_editor)
                else:
                    self.buttonBox.accepted.connect(self.on_model_added)
        # Saving in child editor
        else:
            # save and new record
            if self.edit_model is None:
                self.buttonBox.accepted.connect(self.on_child_saved)
                self.save_new_button.clicked.connect(
                    lambda: self.on_child_saved(True))

            else:
                # When updating an existing child editor save to the db
                self.buttonBox.accepted.connect(self.on_child_saved)
                #self.buttonBox.accepted.connect(self.submit)

        self.buttonBox.rejected.connect(self.cancel)

    @property
    def notification_bar(self):
        """
        :return: Returns the dialog's notification bar.
        :rtype: NotificationBar
        """
        return self._notifBar

    def save_parent_editor(self):
        """
        Saves the parent editor and its children.
        """
        self.submit()
        self.save_children()

    def set_parent_values(self):
        """
        Sets the parent display column for the child.
        """
        if self.parent_entity is None:
            return
        for col in self._entity.columns.values():
            if col.TYPE_INFO == 'FOREIGN_KEY':
                parent_entity = col.parent
                if parent_entity == self.parent_entity:
                    self.parent_widgets_value_setter(self._parent._parent, col)

    def parent_widgets_value_setter(self, parent, col):
        """
        Finds and sets the value from parent widget and set it to the column
        widget of a child using the child column.
        :param parent: The parent widget
        :type parent: QWidget
        :param col: The child column object
        :type col: Object
        """
        for parent_col, parent_widget in parent.column_widgets.iteritems():
            if parent_col.name == col.name:
                self.single_parent_value_setter(col, parent_widget)
                break
            if parent_col.name in col.entity_relation.display_cols:
                self.single_parent_value_setter(col, parent_widget)
                break

    def single_parent_value_setter(self, col, parent_widget):
        """
        Gets value from parent widget and set it to the column widget of a
        child using the child column.
        :param parent: The parent widget
        :type parent: QWidget
        :param col: The child column object
        :type col: Object
        """
        local_widget = self.column_widgets[col]
        local_widget.show_clear_button()
        self.filter_val = parent_widget.text()
        local_widget.setText(self.filter_val)

    def save_and_new(self):
        """
        A slot raised when Save and New button is click. It saves the form
        without showing a success message. Then it sets reload_form property
        to True so that entity_browser can re-load the form.
        """
        from stdm.ui.entity_browser import (EntityBrowserWithEditor)
        self.submit(False, True)
        self.save_children()

        if self.is_valid:
            self.addedModel.emit(self.model())
            self.setModel(self.ent_model())
            self.clear()
            self.child_models.clear()
            for index in range(0, self.entity_tab_widget.count() - 1):
                if isinstance(self.entity_tab_widget.widget(index),
                              EntityBrowserWithEditor):
                    child_browser = self.entity_tab_widget.widget(index)
                    child_browser.remove_rows()

    def on_model_added(self):
        """
        A slot raised when a form is submitted with collect model set to True.
        There will be no success message and the form does not close.
        """
        self.submit(True)
        self.addedModel.emit(self.model())

    def closeEvent(self, event):
        '''
        Raised when a request to close the window is received.
        Check the dirty state of input controls and prompt user to
        save if dirty.
        '''

        if self.do_not_check_dirty:
            event.accept()
            return
        isDirty, userResponse = self.checkDirty()

        if isDirty:
            if userResponse == QMessageBox.Yes:
                # We need to ignore the event so that validation and
                # saving operations can be executed
                event.ignore()
                self.submit()
            elif userResponse == QMessageBox.No:
                event.accept()
            elif userResponse == QMessageBox.Cancel:
                event.ignore()
        else:
            event.accept()

    def on_child_saved(self, save_and_new=False):
        """
        A slot raised when the save or save and new button is clicked. It sets
        the child_models dictionary of the parent when saved.
        :param save_and_new: A boolean indicating the save and new button is
        clicked to trigger the slot.
        :type save_and_new: Boolean
        """
        if self.parent_entity is None:
            return

        self.submit(True)

        insert_pos = self._parent.tbEntity.model().rowCount() + 1
        # Save to parent editor so that it is persistent.
        self._parent._parent.child_models[insert_pos, self._entity] = \
            self.model()
        self.addedModel.emit(self.model())
        if not save_and_new:
            self.accept()

        else:
            if self.is_valid:
                #self.addedModel.emit(self.model())
                self.setModel(self.ent_model())

                self.clear()
                self.set_parent_values()

    def save_children(self):
        """
        Saves children models into the database by assigning the the id of the
        parent for foreign key column.
        """
        if len(self.child_models) < 1:
            return
        children_obj = []
        for row_entity, model in self.child_models.iteritems():
            row_pos = row_entity[0]
            entity = row_entity[1]
            ent_model = entity_model(entity)
            entity_obj = ent_model()
            for col in entity.columns.values():
                if col.TYPE_INFO == 'FOREIGN_KEY':
                    if col.parent.name == self._entity.name:
                        setattr(model, col.name, self.model().id)
                        children_obj.append(model)
            entity_obj.saveMany(children_obj)

    def register_column_widgets(self):
        """
        Registers the column widgets.
        """
        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        self.scroll_widget_contents = QWidget()
        self.scroll_widget_contents.setObjectName('scrollAreaWidgetContents')
        for c in self._entity.columns.values():
            if c.name in self.exclude_columns:
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue
            # Get widget factory
            column_widget = ColumnWidgetRegistry.create(
                c, self.scroll_widget_contents, host=self)
            self.column_widgets[c] = column_widget

    def _setup_columns_content_area(self):
        # Only use this if entity supports documents
        # self.entity_tab_widget = None
        self.doc_widget = None

        self.entity_scroll_area = QScrollArea(self)
        self.entity_scroll_area.setFrameShape(QFrame.NoFrame)
        self.entity_scroll_area.setWidgetResizable(True)
        self.entity_scroll_area.setObjectName('scrollArea')

        # Grid layout for controls
        self.gl = QGridLayout(self.scroll_widget_contents)
        self.gl.setObjectName('gl_widget_contents')

        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        # Iterate entity column and assert if they exist
        row_id = 0
        for c, column_widget in self.column_widgets.iteritems():
            if c.name in self.exclude_columns:
                continue
            if not c.name in columns and not isinstance(c, VirtualColumn):
                continue

            if column_widget is not None:
                header = c.ui_display()
                self.c_label = QLabel(self.scroll_widget_contents)

                # Format label text if it is a mandatory field
                if c.mandatory:
                    header = u'{0} *'.format(c.ui_display())
                    #Highlight asterisk
                    header = self._highlight_asterisk(header)

                self.c_label.setText(header)
                self.gl.addWidget(self.c_label, row_id, 0, 1, 1)

                self.column_widget = column_widget
                self.gl.addWidget(self.column_widget, row_id, 1, 1, 1)

                #Add user tip if specified for the column configuration
                if c.user_tip:
                    self.tip_lbl = UserTipLabel(user_tip=c.user_tip)
                    self.gl.addWidget(self.tip_lbl, row_id, 2, 1, 1)

                if c.mandatory and not self.has_mandatory:
                    self.has_mandatory = True

                col_name = c.name
                #Replace name accordingly based on column type
                if isinstance(c, MultipleSelectColumn):
                    col_name = c.model_attribute_name

                # Add widget to MapperMixin collection
                self.addMapping(col_name,
                                self.column_widget,
                                c.mandatory,
                                pseudoname=c.ui_display())

                # Bump up row_id
                row_id += 1

        self.entity_scroll_area.setWidget(self.scroll_widget_contents)

        if self.entity_tab_widget is None:
            self.entity_tab_widget = QTabWidget(self)
        # Check if there are children and add foreign key browsers

        # Add primary tab if necessary
        self._add_primary_attr_widget()

        if not self._disable_collections:
            ch_entities = self.children_entities()

            for col, ch in ch_entities.iteritems():
                if hasattr(col.entity_relation, 'show_in_parent'):
                    if col.entity_relation.show_in_parent != '0':
                        self._add_fk_browser(ch, col)
                else:
                    self._add_fk_browser(ch, col)

        #Add tab widget if entity supports documents
        if self._entity.supports_documents:
            self.doc_widget = SupportingDocumentsWidget(
                self._entity.supporting_doc, self._ent_document_model, self)

            # Map the source document manager object
            self.addMapping('documents',
                            self.doc_widget.source_document_manager)

            #
            # # Add attribute tab
            # self._add_primary_attr_widget()

            # Add supporting documents tab
            self.entity_tab_widget.addTab(self.doc_widget,
                                          self.tr('Supporting Documents'))

        # Return the correct widget
        if not self.entity_tab_widget is None:
            return self.entity_tab_widget

        return self.entity_scroll_area

    def _add_primary_attr_widget(self):
        # Check if the primary entity
        # exists and add if it does not
        pr_txt = self.tr('Primary')
        if not self.entity_tab_widget is None:
            tab_txt = self.entity_tab_widget.tabText(0)
            if not tab_txt == pr_txt:
                self.entity_tab_widget.addTab(self.entity_scroll_area, pr_txt)

    def _add_fk_browser(self, child_entity, column):
        # Create and add foreign key
        # browser to the collection
        from stdm.ui.entity_browser import (EntityBrowserWithEditor)

        attr = u'{0}_collection'.format(child_entity.name)

        # Return if the attribute does not exist
        if not hasattr(self._model, attr):
            return
        entity_browser = EntityBrowserWithEditor(child_entity,
                                                 self,
                                                 MANAGE,
                                                 False,
                                                 plugin=self.plugin)
        entity_browser.buttonBox.setVisible(False)
        entity_browser.record_filter = []

        if len(child_entity.label) > 2:
            column_label = child_entity.label
        else:
            # Split and join  to filter out entity name prefix
            # e.g. 'lo_parcel' to 'parcel'
            column_label = format_name(" ".join(
                child_entity.name.split("_", 1)[1:]))
        self.entity_tab_widget.addTab(entity_browser,
                                      u'{0}'.format(column_label))
        self.set_filter(child_entity, entity_browser)

    def set_filter(self, entity, browser):
        col = self.filter_col(entity)
        child_model = entity_model(entity)
        child_model_obj = child_model()
        col_obj = getattr(child_model, col.name)
        if self.model() is not None:
            if self.model().id is None:
                browser.filtered_records = []
            else:
                browser.filtered_records = child_model_obj.queryObject(
                ).filter(col_obj == self.model().id).all()

        if self.edit_model is not None:
            browser.filtered_records = child_model_obj.queryObject().filter(
                col_obj == self.edit_model.id).all()

        if self.edit_model is None and self.model() is None:
            browser.filtered_records = []

    def filter_col(self, child_entity):
        for col in child_entity.columns.values():
            if col.TYPE_INFO == 'FOREIGN_KEY':
                parent_entity = col.parent
                if parent_entity == self._entity:
                    return col

    def children_entities(self):
        """
        :return: Returns a list of children entities
        that refer to the main entity as the parent.
        :rtype: OrderedDict
        """
        child_columns = OrderedDict()
        for ch in self._entity.children():
            if ch.TYPE_INFO == Entity.TYPE_INFO:
                for col in ch.columns.values():
                    if hasattr(col, 'entity_relation'):

                        if col.parent.name == self._entity.name:
                            child_columns[col] = ch
        return child_columns

    def document_widget(self):
        """
        :return: Returns the widget for managing
        the supporting documents for an entity if enabled.
        :rtype: SupportingDocumentsWidget
        """
        return self.doc_widget

    def source_document_manager(self):
        """
        :return: Returns an instance of the
        SourceDocumentManager only if supporting
        documents are enabled for the given entity. Otherwise,
        None if supporting documents are not enabled.
        :rtype: SourceDocumentManager
        """
        if self.doc_widget is None:
            return None

        return self.doc_widget.source_document_manager

    def _highlight_asterisk(self, text):
        # Highlight asterisk in red
        c = '*'

        # Do not format if there is no asterisk
        if text.find(c) == -1:
            return text

        asterisk_highlight = '<span style=\" color:#ff0000;\">*</span>'
        text = text.replace(c, asterisk_highlight)

        return u'<html><head/><body><p>{0}</p></body></html>'.format(text)

    def _custom_validate(self):
        """
        Override of the MapperMixin which enables custom editor extensions to
        inject additional validation before saving form data.
        :return: Return True if the validation was successful,
        otherwise False.
        :rtype: bool
        """
        if not self._editor_ext is None:
            return self._editor_ext.validate()

        # Return True if there is no custom editor extension specified
        return True

    def _post_save(self, model):
        """
        Include additional post-save logic by custom extensions.
        :param model: SQLAlchemy model
        :type model: object
        """
        if not self._editor_ext is None:
            self._editor_ext.post_save(model)

    def _get_entity_editor_widgets(self):
        """
        Gets entity editor widgets and appends them to a dictionary
        """
        if self.entity_tab_widget:
            tab_count = self.entity_tab_widget.count()
            for i in range(tab_count):
                tab_object = self.entity_tab_widget.widget(i)
                tab_text = self.entity_tab_widget.tabText(i)
                self.entity_editor_widgets[tab_text] = tab_object
        else:
            self.entity_editor_widgets['no_tab'] = self.entity_scroll_area
示例#48
0
    def __init__(self, nbprocessors):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.taskset = None

        # Utilizations:
        vbox_utilizations = QVBoxLayout()
        group = QGroupBox("Task Utilizations:")

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Generator:", self))
        self.comboGenerator = QComboBox()
        self.comboGenerator.addItem("RandFixedSum")
        self.comboGenerator.addItem("UUniFast-Discard")
        self.comboGenerator.addItem("Kato's method")
        self.comboGenerator.currentIndexChanged.connect(self.generator_changed)
        hbox.addWidget(self.comboGenerator)
        vbox_utilizations.addLayout(hbox)

        # Load slider + spinner:
        hbox_load = QHBoxLayout()
        sld = _DoubleSlider(QtCore.Qt.Horizontal, self)
        sld.setMinimum(0)
        sld.setMaximum(32)
        self.spin_load = QDoubleSpinBox(self)
        self.spin_load.setMinimum(0)
        self.spin_load.setMaximum(32)
        self.spin_load.setSingleStep(0.1)
        hbox_load.addWidget(QLabel("Total utilization: ", self))
        hbox_load.addWidget(sld)
        hbox_load.addWidget(self.spin_load)
        sld.doubleValueChanged.connect(self.spin_load.setValue)
        self.spin_load.valueChanged.connect(sld.setValue)
        self.spin_load.setValue(nbprocessors / 2.)
        vbox_utilizations.addLayout(hbox_load)

        # Number of periodic tasks:
        self.hbox_tasks = QHBoxLayout()
        self.spin_tasks = QSpinBox(self)
        self.spin_tasks.setMinimum(0)
        self.spin_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self))
        self.hbox_tasks.addStretch(1)
        self.hbox_tasks.addWidget(self.spin_tasks)
        vbox_utilizations.addLayout(self.hbox_tasks)

        # Number of sporadic tasks:
        self.hbox_sporadic_tasks = QHBoxLayout()
        self.spin_sporadic_tasks = QSpinBox(self)
        self.spin_sporadic_tasks.setMinimum(0)
        self.spin_sporadic_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_sporadic_tasks.addWidget(
            QLabel("Number of sporadic tasks: ", self))
        self.hbox_sporadic_tasks.addStretch(1)
        self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks)
        vbox_utilizations.addLayout(self.hbox_sporadic_tasks)

        # Min / Max utilizations
        self.hbox_utilizations = QHBoxLayout()
        self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ",
                                                self))
        self.interval_utilization = IntervalSpinner(self,
                                                    min_=0,
                                                    max_=1,
                                                    step=.01,
                                                    round_option=False)
        self.hbox_utilizations.addWidget(self.interval_utilization)
        vbox_utilizations.addLayout(self.hbox_utilizations)

        group.setLayout(vbox_utilizations)
        self.layout.addWidget(group)

        # Periods:
        vbox_periods = QVBoxLayout()
        group = QGroupBox("Task Periods:")

        # Log uniform
        self.lunif = QRadioButton("log-uniform distribution between:")
        vbox_periods.addWidget(self.lunif)
        self.lunif.setChecked(True)

        self.lunif_interval = IntervalSpinner(self)
        self.lunif_interval.setEnabled(self.lunif.isChecked())
        self.lunif.toggled.connect(self.lunif_interval.setEnabled)
        vbox_periods.addWidget(self.lunif_interval)

        # Uniform
        self.unif = QRadioButton("uniform distribution between:")
        vbox_periods.addWidget(self.unif)

        self.unif_interval = IntervalSpinner(self)
        self.unif_interval.setEnabled(self.unif.isChecked())
        self.unif.toggled.connect(self.unif_interval.setEnabled)
        vbox_periods.addWidget(self.unif_interval)

        # Discrete
        discrete = QRadioButton("chosen among these (space separated) values:")
        vbox_periods.addWidget(discrete)

        self.periods = QLineEdit(self)
        self.periods.setValidator(
            QRegExpValidator(QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$")))

        vbox_periods.addWidget(self.periods)
        self.periods.setEnabled(discrete.isChecked())
        discrete.toggled.connect(self.periods.setEnabled)
        vbox_periods.addStretch(1)

        group.setLayout(vbox_periods)
        self.layout.addWidget(group)

        buttonBox = QDialogButtonBox()
        cancel = buttonBox.addButton(QDialogButtonBox.Cancel)
        generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole)
        cancel.clicked.connect(self.reject)
        generate.clicked.connect(self.generate)
        self.layout.addWidget(buttonBox)

        self.show_randfixedsum_options()
示例#49
0
    def __init__(self,
                 parent=None,
                 signalManager=None,
                 title="CSV File Import"):
        OWWidget.__init__(self,
                          parent,
                          signalManager,
                          title,
                          wantMainArea=False,
                          noReport=True)

        self.symbol_DC = ""
        self.symbol_DK = ""

        #: List of recent opened files.
        self.recent_files = []
        #: Current selected file name
        self.selected_file = None
        #: Variable reuse flag
        self.create_new_on = 2
        #: Display advanced var reuse options
        self.show_advanced = False

        self.loadSettings()

        self.recent_files = filter(os.path.exists, self.recent_files)

        self._loader = None
        self._invalidated = False
        self._datareport = None

        layout = QHBoxLayout()
        OWGUI.widgetBox(self.controlArea, "File", orientation=layout)

        icons = standard_icons(self)

        self.recent_combo = QComboBox(self,
                                      objectName="recent_combo",
                                      toolTip="Recent files.",
                                      activated=self.activate_recent)
        cb_append_file_list(self.recent_combo, self.recent_files)

        self.recent_combo.insertSeparator(self.recent_combo.count())
        self.recent_combo.addItem(u"Browse documentation data sets…")

        self.browse_button = QPushButton(u"…",
                                         icon=icons.dir_open_icon,
                                         toolTip="Browse filesystem",
                                         clicked=self.browse)

        self.reload_button = QPushButton("Reload",
                                         icon=icons.reload_icon,
                                         toolTip="Reload the selected file",
                                         clicked=self.reload,
                                         default=True)

        layout.addWidget(self.recent_combo, 2)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.reload_button)

        ###########
        # Info text
        ###########
        box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
        self.infoa = OWGUI.widgetLabel(box, "No data loaded.")
        self.infob = OWGUI.widgetLabel(box, " ")
        self.warnings = OWGUI.widgetLabel(box, " ")

        # Set word wrap so long warnings won't expand the widget
        self.warnings.setWordWrap(True)
        self.warnings.setSizePolicy(QSizePolicy.Ignored,
                                    QSizePolicy.MinimumExpanding)

        advanced = QGroupBox("Advanced Settings",
                             checkable=True,
                             checked=self.show_advanced)
        advanced.setLayout(QVBoxLayout())

        def set_group_visible(groupbox, state):
            layout = groupbox.layout()
            for i in range(layout.count()):
                item = layout.itemAt(i)
                widget = item.widget()
                if widget is not None:
                    widget.setVisible(state)
            groupbox.setFlat(not state)

        def toogle_advanced(state):
            self.show_advanced = state
            set_group_visible(advanced, state)
            self.layout().activate()
            QApplication.instance().processEvents()
            QTimer.singleShot(0, self.adjustSize)

        advanced.toggled.connect(toogle_advanced)

        self.taboptions = QWidget()
        self.taboptions.setLayout(QVBoxLayout())
        box = QGroupBox("Missing Value Symbols", flat=True)
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        form.addRow(
            "Don't care:",
            OWGUI.lineEdit(None,
                           self,
                           "symbol_DC",
                           tooltip="Default values: '~' or '*'"))
        form.addRow(
            "Don't know:",
            OWGUI.lineEdit(None,
                           self,
                           "symbol_DK",
                           tooltip="Default values: empty fields (space), "
                           "'?' or 'NA'"))
        box.setLayout(form)
        advanced.layout().addWidget(box)

        rb = OWGUI.radioButtonsInBox(
            advanced,
            self,
            "create_new_on",
            box="New Attributes",
            callback=self._invalidate,
            label=u"Create a new attribute when existing attribute(s) …",
            btnLabels=[
                u"Have mismatching order of values",
                u"Have no common values with the new (recommended)",
                u"Miss some values of the new attribute",
                u"… Always create a new attribute"
            ])
        rb.setFlat(True)
        self.controlArea.layout().addWidget(advanced)

        button_box = QDialogButtonBox(orientation=Qt.Horizontal)
        self.import_options_button = QPushButton(u"Import Options…",
                                                 enabled=False)
        self.import_options_button.pressed.connect(
            self._activate_import_dialog)
        button_box.addButton(self.import_options_button,
                             QDialogButtonBox.ActionRole)
        button_box.addButton(
            QPushButton("&Report", pressed=self.reportAndFinish),
            QDialogButtonBox.ActionRole)
        self.controlArea.layout().addWidget(button_box)

        OWGUI.rubber(self.controlArea)

        set_group_visible(advanced, self.show_advanced)

        if self.recent_files and self.recent_files[0] == self.selected_file:
            QTimer.singleShot(0, lambda: self.activate_recent(0))
        else:
            self.selected_file = None
            self.recent_combo.setCurrentIndex(-1)
示例#50
0
    def initUI(self):
        u"""Build the dialog box."""
        language_help = _(u'''<h4>Language code.</h4>
<p>This will be transmitted as part of the requst sent to the
sites. As some sites only support one language, this is also used to
decide where to send the requests. Use a standard language code
here. Using invalid values or codes of unsupported languages will
result in no downloads. Do <em>not</em> use domain codes (E.g. use
<code>zh</code> rather than <code>cn</code> for Chinese.)</p>''')
        self.setWindowTitle(_(u'Anki – Download audio'))
        self.setWindowIcon(QIcon(":/icons/anki.png"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        edit_word_head = QLabel()
        kanji_et = _('''\
<h4>Requests to send to the download sites</h4>
<p>In the split edit fields, set the kanji on the left, the
kana on the right.</p>
''')
        base_et = _('''\
<h4>Requests to send to the download sites</h4>
<p>In split edit fields, set the expression (base) on the left, the
reading (ruby) on the right.</p>
''')
        single_et = _('''\
<h4>Requests to send to the download sites</h4>
''')
        # Now decide which help text to show.
        # First, decide if we have any split fields.
        if any(f_data.split for f_data in self.field_data_list):
            if self.language_code and self.language_code.startswith('ja'):
                # Japanese
                edit_word_head.setText(kanji_et)
            else:
                # Chinese should not happen at the moment
                edit_word_head.setText(base_et)
        else:
            edit_word_head.setText(single_et)
        layout.addWidget(edit_word_head)
        self.create_data_rows(layout)
        line = QFrame(self)
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        layout.addWidget(line)
        lcode_head = QLabel(_('''<h4>Language code</h4>'''))
        layout.addWidget(lcode_head)
        lang_hlayout = QHBoxLayout()
        lc_label = QLabel(_(u'Language code:'), self)
        lang_hlayout.addWidget(lc_label)
        lc_label.setToolTip(language_help)
        self.language_code_lineedit = QLineEdit(self)
        try:
            self.language_code_lineedit.setText(self.language_code)
        except:
            self.language_code_lineedit.setText(default_audio_language_code)
        lang_hlayout.addWidget(self.language_code_lineedit)
        self.language_code_lineedit.setToolTip(language_help)
        layout.addLayout(lang_hlayout)
        dialog_buttons = QDialogButtonBox(self)
        dialog_buttons.addButton(QDialogButtonBox.Cancel)
        dialog_buttons.addButton(QDialogButtonBox.Ok)
        self.connect(dialog_buttons, SIGNAL("accepted()"), self,
                     SLOT("accept()"))
        self.connect(dialog_buttons, SIGNAL("rejected()"), self,
                     SLOT("reject()"))
        layout.addWidget(dialog_buttons)
示例#51
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(600, 300)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Combo box for the text to search
        findLabel = QLabel(self)
        findLabel.setText("Find text:")
        self.findCombo = QComboBox(self)
        self.__tuneCombo(self.findCombo)
        self.findCombo.lineEdit().setToolTip(
            "Regular expression to search for")
        self.findCombo.editTextChanged.connect(self.__someTextChanged)

        gridLayout.addWidget(findLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.findCombo, 0, 1, 1, 1)
        verticalLayout.addLayout(gridLayout)

        # Check boxes
        horizontalCBLayout = QHBoxLayout()
        self.caseCheckBox = QCheckBox(self)
        self.caseCheckBox.setText("Match &case")
        horizontalCBLayout.addWidget(self.caseCheckBox)
        self.wordCheckBox = QCheckBox(self)
        self.wordCheckBox.setText("Match whole &word")
        horizontalCBLayout.addWidget(self.wordCheckBox)
        self.regexpCheckBox = QCheckBox(self)
        self.regexpCheckBox.setText("Regular &expression")
        horizontalCBLayout.addWidget(self.regexpCheckBox)

        verticalLayout.addLayout(horizontalCBLayout)

        # Files groupbox
        filesGroupbox = QGroupBox(self)
        filesGroupbox.setTitle("Find in")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            filesGroupbox.sizePolicy().hasHeightForWidth())
        filesGroupbox.setSizePolicy(sizePolicy)

        gridLayoutFG = QGridLayout(filesGroupbox)
        self.projectRButton = QRadioButton(filesGroupbox)
        self.projectRButton.setText("&Project")
        gridLayoutFG.addWidget(self.projectRButton, 0, 0)
        self.projectRButton.clicked.connect(self.__projectClicked)

        self.openFilesRButton = QRadioButton(filesGroupbox)
        self.openFilesRButton.setText("&Opened files only")
        gridLayoutFG.addWidget(self.openFilesRButton, 1, 0)
        self.openFilesRButton.clicked.connect(self.__openFilesOnlyClicked)

        self.dirRButton = QRadioButton(filesGroupbox)
        self.dirRButton.setText("&Directory tree")
        gridLayoutFG.addWidget(self.dirRButton, 2, 0)
        self.dirRButton.clicked.connect(self.__dirClicked)

        self.dirEditCombo = QComboBox(filesGroupbox)
        self.__tuneCombo(self.dirEditCombo)
        self.dirEditCombo.lineEdit().setToolTip("Directory to search in")
        gridLayoutFG.addWidget(self.dirEditCombo, 2, 1)
        self.dirEditCombo.editTextChanged.connect(self.__someTextChanged)

        self.dirSelectButton = QPushButton(filesGroupbox)
        self.dirSelectButton.setText("...")
        gridLayoutFG.addWidget(self.dirSelectButton, 2, 2)
        self.dirSelectButton.clicked.connect(self.__selectDirClicked)

        filterLabel = QLabel(filesGroupbox)
        filterLabel.setText("Files filter:")
        gridLayoutFG.addWidget(filterLabel, 3, 0)
        self.filterCombo = QComboBox(filesGroupbox)
        self.__tuneCombo(self.filterCombo)
        self.filterCombo.lineEdit().setToolTip("File names regular expression")
        gridLayoutFG.addWidget(self.filterCombo, 3, 1)
        self.filterCombo.editTextChanged.connect(self.__someTextChanged)

        verticalLayout.addWidget(filesGroupbox)

        # File label
        self.fileLabel = FitPathLabel(self)
        self.fileLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        verticalLayout.addWidget(self.fileLabel)

        # Progress bar
        self.progressBar = QProgressBar(self)
        self.progressBar.setValue(0)
        self.progressBar.setOrientation(Qt.Horizontal)
        verticalLayout.addWidget(self.progressBar)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.findButton = buttonBox.addButton("Find",
                                              QDialogButtonBox.AcceptRole)
        self.findButton.setDefault(True)
        self.findButton.clicked.connect(self.__process)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return
class WellMarkerDialog(QDialog):
    def __init__(self, well):
        super(WellMarkerDialog, self).__init__()
        self.well = well
        self.setupUi()
        self.initUI()
        self.button_box.accepted.connect(self.save_markers)
        self.button_box.rejected.connect(self.close)
        self.add_Button.clicked.connect(self.add_row)
        self.del_Button.clicked.connect(self.del_row)
        self.export_Button.clicked.connect(self.export_markers)
        self.import_Button.clicked.connect(self.import_markers)

    def setupUi(self):
        self.resize(568, 411)
        self.setWindowIcon(QIcon(':/icon/layer_icon'))
        self.setWindowTitle("Edit Markers")
        self.gridLayout = QGridLayout(self)
        # table widget
        self.tableWidget = QTableWidget(self)
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setHorizontalHeaderItem(0, QTableWidgetItem("Name"))
        self.tableWidget.setHorizontalHeaderItem(1,
                                                 QTableWidgetItem("TVD (m)"))
        self.tableWidget.setHorizontalHeaderItem(2,
                                                 QTableWidgetItem("TVDSS (m)"))
        self.tableWidget.setHorizontalHeaderItem(3, QTableWidgetItem("Color"))
        self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
        # button box
        self.button_box = QDialogButtonBox(self)
        self.export_Button = self.button_box.addButton(
            "Export", QDialogButtonBox.ResetRole)
        self.import_Button = self.button_box.addButton(
            "Import", QDialogButtonBox.ResetRole)
        self.add_Button = self.button_box.addButton("Add",
                                                    QDialogButtonBox.ResetRole)
        self.del_Button = self.button_box.addButton("Del",
                                                    QDialogButtonBox.ResetRole)
        self.button_box.setStandardButtons(QDialogButtonBox.Save
                                           | QDialogButtonBox.Cancel)
        self.gridLayout.addWidget(self.button_box, 1, 0, 1, 1)

    def initUI(self):
        self.populate_marker_table()

    def populate_marker_table(self):
        try:
            markers_dict = self.well.params["horizon"]
            for mark in markers_dict.keys():
                self.tableWidget.insertRow(0)
                self.tableWidget.setItem(0, 0, QTableWidgetItem(mark))
                self.tableWidget.setItem(
                    0, 1, QTableWidgetItem(str(markers_dict[mark])))
                self.tableWidget.setItem(
                    0, 2, QTableWidgetItem(str(markers_dict[mark])))
            self.tableWidget.sortItems(0, Qt.AscendingOrder)
        except KeyError:
            pass

    def add_row(self):
        self.tableWidget.insertRow(self.tableWidget.rowCount())

    def del_row(self):
        self.tableWidget.removeRow(self.tableWidget.currentRow())

    def save_markers(self):
        l_names = [str(self.tableWidget.item(irow, 0).text()) \
            for irow in range(self.tableWidget.rowCount())]
        l_md = [float(self.tableWidget.item(irow, 1).text()) \
            for irow in range(self.tableWidget.rowCount())]
        new_dict = OrderedDict([(a, b) for a, b in zip(l_names, l_md)])
        if self.well.params['horizon'] != new_dict:
            respond = QMessageBox.question(
                self, "Save Markers", "Sure to save changes?",
                QMessageBox.Save | QMessageBox.Cancel)
            if respond == QMessageBox.Save:
                self.well.params['horizon'] = new_dict
                self.well.save_params()
        self.close()

    def export_markers(self):
        file_path = str(QFileDialog.getSaveFileName(self, "Save Markers"))
        l_names = [str(self.tableWidget.item(irow, 0).text()) \
            for irow in range(self.tableWidget.rowCount())]
        l_md = [float(self.tableWidget.item(irow, 1).text()) \
            for irow in range(self.tableWidget.rowCount())]
        df = pd.DataFrame({"name": l_names, "MD(m)": l_md})
        df.to_csv(file_path, sep='\t', columns=["name", "MD(m)"], index=False)
        QMessageBox.information(self, "Export Markers", "Succeed!")

    def import_markers(self):
        read_csv_dialog = ReadCsvDialog()
        read_csv_dialog.setWindowIcon(QIcon(':/icon/layer_icon'))
        read_csv_dialog.setWindowTitle("Open Markers File")
        read_csv_dialog.label.setText("Read Makers from File")
        read_csv_dialog.exec_()
示例#53
0
    def __createLayout(self, action):
        """ Creates the dialog layout """

        self.resize(650, 300)
        self.setSizeGripEnabled(True)

        # Top level layout
        layout = QVBoxLayout(self)

        # Cmd line arguments
        argsLabel = QLabel("Command line arguments")
        self.__argsEdit = QLineEdit()
        self.__argsEdit.textChanged.connect(self.__argsChanged)
        argsLayout = QHBoxLayout()
        argsLayout.addWidget(argsLabel)
        argsLayout.addWidget(self.__argsEdit)
        layout.addLayout(argsLayout)

        # Working directory
        workDirGroupbox = QGroupBox(self)
        workDirGroupbox.setTitle("Working directory")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        workDirGroupbox.sizePolicy().hasHeightForWidth() )
        workDirGroupbox.setSizePolicy(sizePolicy)

        gridLayoutWD = QGridLayout(workDirGroupbox)
        self.__scriptWDRButton = QRadioButton(workDirGroupbox)
        self.__scriptWDRButton.setText("&Use script location")
        gridLayoutWD.addWidget(self.__scriptWDRButton, 0, 0)
        self.__scriptWDRButton.clicked.connect(self.__scriptWDirClicked)

        self.__dirRButton = QRadioButton(workDirGroupbox)
        self.__dirRButton.setText("Select &directory")
        gridLayoutWD.addWidget(self.__dirRButton, 1, 0)
        self.__dirRButton.clicked.connect(self.__dirClicked)

        self.__dirEdit = QLineEdit(workDirGroupbox)
        gridLayoutWD.addWidget(self.__dirEdit, 1, 1)
        self.__dirEdit.textChanged.connect(self.__workingDirChanged)

        self.__dirSelectButton = QPushButton(workDirGroupbox)
        self.__dirSelectButton.setText("...")
        gridLayoutWD.addWidget(self.__dirSelectButton, 1, 2)
        self.__dirSelectButton.clicked.connect(self.__selectDirClicked)

        layout.addWidget(workDirGroupbox)

        # Environment
        envGroupbox = QGroupBox(self)
        envGroupbox.setTitle("Environment")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        envGroupbox.sizePolicy().hasHeightForWidth() )
        envGroupbox.setSizePolicy(sizePolicy)

        layoutEnv = QVBoxLayout(envGroupbox)
        self.__inheritParentRButton = QRadioButton(envGroupbox)
        self.__inheritParentRButton.setText("Inherit &parent")
        self.__inheritParentRButton.clicked.connect(self.__inhClicked)
        layoutEnv.addWidget(self.__inheritParentRButton)

        self.__inheritParentPlusRButton = QRadioButton(envGroupbox)
        self.__inheritParentPlusRButton.setText(
            "Inherit parent and add/&modify")
        self.__inheritParentPlusRButton.clicked.connect(self.__inhPlusClicked)
        layoutEnv.addWidget(self.__inheritParentPlusRButton)
        hInhPlusLayout = QHBoxLayout()
        self.__inhPlusEnvTable = QTreeWidget()
        self.__inhPlusEnvTable.itemActivated.connect(
            self.__inhPlusItemActivated)
        self.__tuneTable(self.__inhPlusEnvTable)
        hInhPlusLayout.addWidget(self.__inhPlusEnvTable)
        vInhPlusLayout = QVBoxLayout()
        self.__addInhButton = QPushButton()
        self.__addInhButton.clicked.connect(self.__addInhClicked)
        self.__addInhButton.setText('Add')
        vInhPlusLayout.addWidget(self.__addInhButton)
        self.__delInhButton = QPushButton()
        self.__delInhButton.clicked.connect(self.__delInhClicked)
        self.__delInhButton.setText('Delete')
        vInhPlusLayout.addWidget(self.__delInhButton)
        self.__editInhButton = QPushButton()
        self.__editInhButton.clicked.connect(self.__editInhClicked)
        self.__editInhButton.setText("Edit")
        vInhPlusLayout.addWidget(self.__editInhButton)
        hInhPlusLayout.addLayout(vInhPlusLayout)
        layoutEnv.addLayout(hInhPlusLayout)

        self.__specificRButton = QRadioButton(envGroupbox)
        self.__specificRButton.setText("&Specific")
        self.__specificRButton.clicked.connect(self.__specClicked)
        layoutEnv.addWidget(self.__specificRButton)
        hSpecLayout = QHBoxLayout()
        self.__specEnvTable = QTreeWidget()
        self.__specEnvTable.itemActivated.connect(self.__specItemActivated)
        self.__tuneTable(self.__specEnvTable)
        hSpecLayout.addWidget(self.__specEnvTable)
        vSpecLayout = QVBoxLayout()
        self.__addSpecButton = QPushButton()
        self.__addSpecButton.clicked.connect(self.__addSpecClicked)
        self.__addSpecButton.setText('Add')
        vSpecLayout.addWidget(self.__addSpecButton)
        self.__delSpecButton = QPushButton()
        self.__delSpecButton.clicked.connect(self.__delSpecClicked)
        self.__delSpecButton.setText('Delete')
        vSpecLayout.addWidget(self.__delSpecButton)
        self.__editSpecButton = QPushButton()
        self.__editSpecButton.clicked.connect(self.__editSpecClicked)
        self.__editSpecButton.setText("Edit")
        vSpecLayout.addWidget(self.__editSpecButton)
        hSpecLayout.addLayout(vSpecLayout)
        layoutEnv.addLayout(hSpecLayout)
        layout.addWidget(envGroupbox)

        # Terminal and profile limits
        if self.__action in ["profile", "debug"]:
            layout.addWidget(self.__getIDEWideGroupbox())
        else:
            termGroupbox = self.__getTermGroupbox()
            termGroupbox.setTitle("Terminal to run in (IDE wide setting)")
            layout.addWidget(termGroupbox)

        # Close checkbox
        self.__closeCheckBox = QCheckBox("&Close terminal upon "
                                         "successful completion")
        self.__closeCheckBox.stateChanged.connect(self.__onCloseChanged)
        layout.addWidget(self.__closeCheckBox)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__runButton = buttonBox.addButton(action,
                                               QDialogButtonBox.AcceptRole)
        self.__runButton.setDefault(True)
        self.__runButton.clicked.connect(self.onAccept)
        layout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return
示例#54
0
    def __init__(self, parent=None, signalManager=None,
                 title="CSV File Import"):
        OWWidget.__init__(self, parent, signalManager, title,
                          wantMainArea=False, noReport=True)

        self.symbol_DC = ""
        self.symbol_DK = ""

        #: List of recent opened files.
        self.recent_files = []
        #: Current selected file name
        self.selected_file = None
        #: Variable reuse flag
        self.create_new_on = 2
        #: Display advanced var reuse options
        self.show_advanced = False

        self.loadSettings()

        self.recent_files = filter(os.path.exists, self.recent_files)

        self._loader = None
        self._invalidated = False
        self._datareport = None

        layout = QHBoxLayout()
        OWGUI.widgetBox(self.controlArea, "File", orientation=layout)

        icons = standard_icons(self)

        self.recent_combo = QComboBox(
            self, objectName="recent_combo",
            toolTip="Recent files.",
            activated=self.activate_recent
        )
        cb_append_file_list(self.recent_combo, self.recent_files)

        self.recent_combo.insertSeparator(self.recent_combo.count())
        self.recent_combo.addItem(u"Browse documentation data sets…")

        self.browse_button = QPushButton(
            u"…",
            icon=icons.dir_open_icon, toolTip="Browse filesystem",
            clicked=self.browse
        )

        self.reload_button = QPushButton(
            "Reload", icon=icons.reload_icon,
            toolTip="Reload the selected file", clicked=self.reload,
            default=True
        )

        layout.addWidget(self.recent_combo, 2)
        layout.addWidget(self.browse_button)
        layout.addWidget(self.reload_button)

        ###########
        # Info text
        ###########
        box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
        self.infoa = OWGUI.widgetLabel(box, "No data loaded.")
        self.infob = OWGUI.widgetLabel(box, " ")
        self.warnings = OWGUI.widgetLabel(box, " ")

        # Set word wrap so long warnings won't expand the widget
        self.warnings.setWordWrap(True)
        self.warnings.setSizePolicy(QSizePolicy.Ignored,
                                    QSizePolicy.MinimumExpanding)

        advanced = QGroupBox(
            "Advanced Settings", checkable=True, checked=self.show_advanced
        )
        advanced.setLayout(QVBoxLayout())

        def set_group_visible(groupbox, state):
            layout = groupbox.layout()
            for i in range(layout.count()):
                item = layout.itemAt(i)
                widget = item.widget()
                if widget is not None:
                    widget.setVisible(state)
            groupbox.setFlat(not state)

        def toogle_advanced(state):
            self.show_advanced = state
            set_group_visible(advanced, state)
            self.layout().activate()
            QApplication.instance().processEvents()
            QTimer.singleShot(0, self.adjustSize)

        advanced.toggled.connect(toogle_advanced)

        self.taboptions = QWidget()
        self.taboptions.setLayout(QVBoxLayout())
        box = QGroupBox("Missing Value Symbols", flat=True)
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        form.addRow(
            "Don't care:",
            OWGUI.lineEdit(None, self, "symbol_DC",
                           tooltip="Default values: '~' or '*'"))
        form.addRow(
            "Don't know:",
            OWGUI.lineEdit(None, self, "symbol_DK",
                           tooltip="Default values: empty fields (space), "
                                   "'?' or 'NA'"))
        box.setLayout(form)
        advanced.layout().addWidget(box)

        rb = OWGUI.radioButtonsInBox(
            advanced, self, "create_new_on",
            box="New Attributes",
            callback=self._invalidate,
            label=u"Create a new attribute when existing attribute(s) …",
            btnLabels=[u"Have mismatching order of values",
                       u"Have no common values with the new (recommended)",
                       u"Miss some values of the new attribute",
                       u"… Always create a new attribute"]
        )
        rb.setFlat(True)
        self.controlArea.layout().addWidget(advanced)

        button_box = QDialogButtonBox(orientation=Qt.Horizontal)
        self.import_options_button = QPushButton(
            u"Import Options…", enabled=False
        )
        self.import_options_button.pressed.connect(self._activate_import_dialog)
        button_box.addButton(
            self.import_options_button, QDialogButtonBox.ActionRole
        )
        button_box.addButton(
            QPushButton("&Report", pressed=self.reportAndFinish),
            QDialogButtonBox.ActionRole
        )
        self.controlArea.layout().addWidget(button_box)

        OWGUI.rubber(self.controlArea)

        set_group_visible(advanced, self.show_advanced)

        if self.recent_files and self.recent_files[0] == self.selected_file:
            QTimer.singleShot(
                0, lambda: self.activate_recent(0)
            )
        else:
            self.selected_file = None
            self.recent_combo.setCurrentIndex(-1)
示例#55
0
class Games(QDialog):
    """a dialog for selecting a game"""
    def __init__(self, parent=None):
        super(Games, self).__init__(parent)
        self.selectedGame = None
        self.onlyPending = True
        self.setWindowTitle(m18nc('kajongg', 'Games') + ' - Kajongg')
        self.setObjectName('Games')
        self.resize(700, 400)
        self.model = GamesModel(self)
        if Debug.modelTest:
            self.modelTest = ModelTest(self.model, self)

        self.view = MJTableView(self)
        self.view.setModel(self.model)
        self.selection = QItemSelectionModel(self.model, self.view)
        self.view.setSelectionModel(self.selection)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.view.setSelectionMode(QAbstractItemView.SingleSelection)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.newButton = self.buttonBox.addButton(
            m18nc('start a new game', "&New"), QDialogButtonBox.ActionRole)
        self.newButton.setIcon(KIcon("document-new"))
        self.newButton.clicked.connect(self.accept)
        self.loadButton = self.buttonBox.addButton(m18n("&Load"),
                                                   QDialogButtonBox.AcceptRole)
        self.loadButton.clicked.connect(self.loadGame)
        self.loadButton.setIcon(KIcon("document-open"))
        self.deleteButton = self.buttonBox.addButton(
            m18n("&Delete"), QDialogButtonBox.ActionRole)
        self.deleteButton.setIcon(KIcon("edit-delete"))
        self.deleteButton.clicked.connect(self.delete)

        chkPending = QCheckBox(m18n("Show only pending games"), self)
        chkPending.setChecked(True)
        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(chkPending)
        cmdLayout.addWidget(self.buttonBox)

        layout = QVBoxLayout()
        layout.addWidget(self.view)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)
        StateSaver(self)

        self.selection.selectionChanged.connect(self.selectionChanged)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.view.doubleClicked.connect(self.loadGame)
        chkPending.stateChanged.connect(self.pendingOrNot)

    def showEvent(self, dummyEvent):
        """only now get the data set. Not doing this in__init__ would eventually
        make it easier to subclass from some generic TableEditor class"""
        self.setQuery()
        self.view.initView()
        self.selectionChanged()

    def keyPressEvent(self, event):
        """use insert/delete keys for insert/delete"""
        key = event.key()
        if key == Qt.Key_Insert:
            self.newEntry()
            return
        if key == Qt.Key_Delete:
            self.delete()
            event.ignore()
            return
        QDialog.keyPressEvent(self, event)

    def selectionChanged(self):
        """update button states according to selection"""
        selectedRows = len(self.selection.selectedRows())
        self.loadButton.setEnabled(selectedRows == 1)
        self.deleteButton.setEnabled(selectedRows >= 1)

    def setQuery(self):
        """define the query depending on self.OnlyPending"""
        query = "select g.id, g.starttime, " \
            "p0.name||'///'||p1.name||'///'||p2.name||'///'||p3.name " \
            "from game g, player p0," \
            "player p1, player p2, player p3 " \
            "where seed is null" \
            " and p0.id=g.p0 and p1.id=g.p1 " \
            " and p2.id=g.p2 and p3.id=g.p3 " \
            "%s" \
            "and exists(select 1 from score where game=g.id)" % \
            ("and g.endtime is null " if self.onlyPending else "")
        self.model.setQuery(query, DBHandle.default)
        self.model.setHeaderData(1, Qt.Horizontal, QVariant(m18n("Started")))
        self.model.setHeaderData(2, Qt.Horizontal, QVariant(m18n("Players")))
        self.view.hideColumn(0)

    def __idxForGame(self, game):
        """returns the model index for game"""
        for row in range(self.model.rowCount()):
            if self.model.record(row).field(0).value().toInt()[0] == game:
                return self.model.index(row, 0)
        return self.model.index(0, 0)

    def pendingOrNot(self, chosen):
        """do we want to see all games or only pending games?"""
        if self.onlyPending != chosen:
            self.onlyPending = chosen
            idx = self.view.currentIndex()
            selectedGame = self.model.record(idx.row()).value(0).toInt()[0]
            self.setQuery()
            idx = self.__idxForGame(selectedGame)
            self.view.selectRow(idx.row())
        self.view.setFocus()

    def loadGame(self):
        """load a game"""
        selnum = len(self.selection.selectedRows())
        if selnum != 1:
            # should never happen
            logException('loadGame: %d rows selected' % selnum)
        idx = self.view.currentIndex()
        self.selectedGame = self.model.record(idx.row()).value(0).toInt()[0]
        self.buttonBox.accepted.emit()

    def delete(self):
        """delete a game"""
        def answered(result, games):
            """question answered, result is True or False"""
            if result:
                cmdList = []
                for game in games:
                    cmdList.append("DELETE FROM score WHERE game = %d" % game)
                    cmdList.append("DELETE FROM game WHERE id = %d" % game)
                Query(cmdList)
                self.setQuery()  # just reload entire table

        deleteGames = list(x.data().toInt()[0]
                           for x in self.view.selectionModel().selectedRows(0))
        if len(deleteGames) == 0:
            # should never happen
            logException('delete: 0 rows selected')
        WarningYesNo(
            m18n("Do you really want to delete <numid>%1</numid> games?<br>" \
            "This will be final, you cannot cancel it with the cancel button",
            len(deleteGames))).addCallback(answered, deleteGames)
示例#56
0
    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(700, 300)
        self.setSizeGripEnabled(True)

        layout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Columns
        colsLabel = QLabel("Columns")
        self.__colsEdit = QLineEdit()
        self.__colsEdit.setText(str(self.__settings.settings["COL_LIMIT"]))
        self.__colsEdit.setToolTip(self.__settings.getDescription("COL_LIMIT"))
        self.__colsEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(colsLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.__colsEdit, 0, 1, 1, 1)
        font = self.__colsEdit.font()
        font.setFamily(GlobalData().skin.baseMonoFontFace)
        self.__colsEdit.setFont(font)

        # Assignment
        assignmentLabel = QLabel("Assignment")
        self.__assignmentEdit = QLineEdit()
        self.__assignmentEdit.setText(self.__settings.settings["ASSIGNMENT"])
        self.__assignmentEdit.setToolTip(
            self.__settings.getDescription("ASSIGNMENT"))
        self.__assignmentEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(assignmentLabel, 0, 3, 1, 1)
        gridLayout.addWidget(self.__assignmentEdit, 0, 4, 1, 1)
        self.__assignmentEdit.setFont(font)

        # Function parameters assignment
        funcAssignLabel = QLabel("Function params\nassignment")
        self.__funcAssignEdit = QLineEdit()
        self.__funcAssignEdit.setText(
            self.__settings.settings["FUNCTION_PARAM_ASSIGNMENT"])
        self.__funcAssignEdit.setToolTip(
            self.__settings.getDescription("FUNCTION_PARAM_ASSIGNMENT"))
        self.__funcAssignEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(funcAssignLabel, 1, 0, 1, 1)
        gridLayout.addWidget(self.__funcAssignEdit, 1, 1, 1, 1)
        self.__funcAssignEdit.setFont(font)

        # Dictionary separator
        dictSepLabel = QLabel("Dictionary separator")
        self.__dictSepEdit = QLineEdit()
        self.__dictSepEdit.setText(self.__settings.settings["DICT_COLON"])
        self.__dictSepEdit.setToolTip(
            self.__settings.getDescription("DICT_COLON"))
        self.__dictSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(dictSepLabel, 1, 3, 1, 1)
        gridLayout.addWidget(self.__dictSepEdit, 1, 4, 1, 1)
        self.__dictSepEdit.setFont(font)

        # Slice separator
        sliceSepLabel = QLabel("Slice separator")
        self.__sliceSepEdit = QLineEdit()
        self.__sliceSepEdit.setText(self.__settings.settings["SLICE_COLON"])
        self.__sliceSepEdit.setToolTip(
            self.__settings.getDescription("SLICE_COLON"))
        self.__sliceSepEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(sliceSepLabel, 2, 0, 1, 1)
        gridLayout.addWidget(self.__sliceSepEdit, 2, 1, 1, 1)
        self.__sliceSepEdit.setFont(font)

        # Interpreter
        inLabel = QLabel("Interpreter")
        self.__inEdit = QLineEdit()
        self.__inEdit.setText(self.__settings.settings["SHEBANG"])
        self.__inEdit.setToolTip(self.__settings.getDescription("SHEBANG"))
        self.__inEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(inLabel, 2, 3, 1, 1)
        gridLayout.addWidget(self.__inEdit, 2, 4, 1, 1)
        self.__inEdit.setFont(font)

        # Coding spec
        codingLabel = QLabel("Output encoding")
        self.__outCodingEdit = QLineEdit()
        self.__outCodingEdit.setText(self.__settings.settings["CODING"])
        self.__outCodingEdit.setToolTip(
            self.__settings.getDescription("CODING"))
        self.__outCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(codingLabel, 3, 0, 1, 1)
        gridLayout.addWidget(self.__outCodingEdit, 3, 1, 1, 1)
        self.__outCodingEdit.setFont(font)

        # Src coding comment
        srcCodingLabel = QLabel("File encoding\ncomment")
        self.__srcCodingEdit = QLineEdit()
        self.__srcCodingEdit.setText(self.__settings.settings["CODING_SPEC"])
        self.__srcCodingEdit.setToolTip(
            self.__settings.getDescription("CODING_SPEC"))
        self.__srcCodingEdit.textChanged.connect(self.__validate)
        gridLayout.addWidget(srcCodingLabel, 3, 3, 1, 1)
        gridLayout.addWidget(self.__srcCodingEdit, 3, 4, 1, 1)
        self.__srcCodingEdit.setFont(font)

        layout.addLayout(gridLayout)

        # Boilerplate
        boilLabel = QLabel("Boilerplate  ")
        boilLabel.setAlignment(Qt.AlignTop)
        self.__boilEdit = QTextEdit()
        self.__boilEdit.setPlainText(self.__settings.settings["BOILERPLATE"])
        self.__boilEdit.setToolTip(
            self.__settings.getDescription("BOILERPLATE"))
        self.__boilEdit.setTabChangesFocus(True)
        self.__boilEdit.setAcceptRichText(False)
        self.__boilEdit.setFont(font)
        self.__boilEdit.textChanged.connect(self.__validate)
        boilLayout = QHBoxLayout()
        boilLayout.addWidget(boilLabel)
        boilLayout.addWidget(self.__boilEdit)
        layout.addLayout(boilLayout)

        # Now check boxes and radio buttons
        cbGridLayout = QGridLayout()
        self.__keepBlanks = QCheckBox("Keep blank lines")
        self.__keepBlanks.setChecked(
            self.__settings.settings["KEEP_BLANK_LINES"])
        self.__keepBlanks.setToolTip(
            self.__settings.getDescription("KEEP_BLANK_LINES"))
        cbGridLayout.addWidget(self.__keepBlanks, 0, 0, 1, 1)

        self.__addBlanks = QCheckBox("Add blank lines around comments")
        self.__addBlanks.setChecked(
            self.__settings.settings["ADD_BLANK_LINES_AROUND_COMMENTS"])
        self.__addBlanks.setToolTip(
            self.__settings.getDescription("ADD_BLANK_LINES_AROUND_COMMENTS"))
        cbGridLayout.addWidget(self.__addBlanks, 0, 2, 1, 1)

        self.__justifyDoc = QCheckBox("Left justify doc strings")
        self.__justifyDoc.setChecked(
            self.__settings.settings["LEFTJUST_DOC_STRINGS"])
        self.__justifyDoc.setToolTip(
            self.__settings.getDescription("LEFTJUST_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__justifyDoc, 1, 0, 1, 1)

        self.__wrapDoc = QCheckBox("Wrap long doc strings")
        self.__wrapDoc.setChecked(self.__settings.settings["WRAP_DOC_STRINGS"])
        self.__wrapDoc.setToolTip(
            self.__settings.getDescription("WRAP_DOC_STRINGS"))
        cbGridLayout.addWidget(self.__wrapDoc, 1, 2, 1, 1)

        self.__recodeStrings = QCheckBox("Try to decode strings")
        self.__recodeStrings.setChecked(
            self.__settings.settings["RECODE_STRINGS"])
        self.__recodeStrings.setToolTip(
            self.__settings.getDescription("RECODE_STRINGS"))
        cbGridLayout.addWidget(self.__recodeStrings, 2, 0, 1, 1)

        self.__splitStrings = QCheckBox("Split long strings")
        self.__splitStrings.setChecked(
            self.__settings.settings["CAN_SPLIT_STRINGS"])
        self.__splitStrings.setToolTip(
            self.__settings.getDescription("CAN_SPLIT_STRINGS"))
        cbGridLayout.addWidget(self.__splitStrings, 2, 2, 1, 1)

        self.__keepUnassignedConst = QCheckBox("Keep unassigned constants")
        self.__keepUnassignedConst.setChecked(
            self.__settings.settings["KEEP_UNASSIGNED_CONSTANTS"])
        self.__keepUnassignedConst.setToolTip(
            self.__settings.getDescription("KEEP_UNASSIGNED_CONSTANTS"))
        cbGridLayout.addWidget(self.__keepUnassignedConst, 3, 0, 1, 1)

        self.__parenTuple = QCheckBox("Parenthesize tuple display")
        self.__parenTuple.setChecked(
            self.__settings.settings["PARENTHESIZE_TUPLE_DISPLAY"])
        self.__parenTuple.setToolTip(
            self.__settings.getDescription("PARENTHESIZE_TUPLE_DISPLAY"))
        cbGridLayout.addWidget(self.__parenTuple, 3, 2, 1, 1)

        self.__javaListDedent = QCheckBox("Java style list dedent")
        self.__javaListDedent.setChecked(
            self.__settings.settings["JAVA_STYLE_LIST_DEDENT"])
        self.__javaListDedent.setToolTip(
            self.__settings.getDescription("JAVA_STYLE_LIST_DEDENT"))
        cbGridLayout.addWidget(self.__javaListDedent, 4, 0, 1, 1)

        layout.addLayout(cbGridLayout)

        # Quotes radio buttons
        quotesGroupbox = QGroupBox("Quotes")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                        quotesGroupbox.sizePolicy().hasHeightForWidth() )
        quotesGroupbox.setSizePolicy(sizePolicy)

        layoutQG = QVBoxLayout(quotesGroupbox)
        self.__use1RButton = QRadioButton(
            "Use apostrophes instead of quotes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use1RButton)
        self.__use2RButton = QRadioButton(
            "Use quotes instead of apostrophes for string literals",
            quotesGroupbox)
        layoutQG.addWidget(self.__use2RButton)
        self.__useAsIsRButton = QRadioButton("Do not make changes",
                                             quotesGroupbox)
        layoutQG.addWidget(self.__useAsIsRButton)
        use1 = self.__settings.settings["SINGLE_QUOTED_STRINGS"]
        use2 = self.__settings.settings["DOUBLE_QUOTED_STRINGS"]
        if use1:
            self.__use1RButton.setChecked(True)
        elif use2:
            self.__use2RButton.setChecked(True)
        else:
            self.__useAsIsRButton.setChecked(True)
        layout.addWidget(quotesGroupbox)

        fontMetrics = QFontMetrics(font)
        editWidth = fontMetrics.width("iso8859-10  ") + 20
        self.__colsEdit.setFixedWidth(editWidth)
        self.__funcAssignEdit.setFixedWidth(editWidth)
        self.__sliceSepEdit.setFixedWidth(editWidth)
        self.__outCodingEdit.setFixedWidth(editWidth)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.__resetButton = buttonBox.addButton("Reset to Default",
                                                 QDialogButtonBox.ActionRole)
        self.__resetButton.setToolTip(
            "Mostly as recommended by PEP 8 / PEP 308")
        self.__resetButton.clicked.connect(self.__reset)
        self.__tidyButton = buttonBox.addButton("Tidy",
                                                QDialogButtonBox.ActionRole)
        self.__tidyButton.setToolTip("Save settings and run PythonTidy")
        self.__tidyButton.setDefault(True)
        self.__tidyButton.clicked.connect(self.__saveAndAccept)
        layout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.close)
        return
示例#57
0
class XPopupWidget(QWidget):
    """ """
    Direction = enum('North', 'South', 'East', 'West')
    Mode = enum('Popup', 'Dialog', 'ToolTip')
    Anchor = enum('TopLeft', 'TopCenter', 'TopRight', 'LeftTop', 'LeftCenter',
                  'LeftBottom', 'RightTop', 'RightCenter', 'RightBottom',
                  'BottomLeft', 'BottomCenter', 'BottomRight')

    aboutToShow = qt.Signal()
    accepted = qt.Signal()
    closed = qt.Signal()
    rejected = qt.Signal()
    resetRequested = qt.Signal()
    shown = qt.Signal()
    buttonClicked = qt.Signal(QAbstractButton)

    def __init__(self, parent=None, buttons=None):
        super(XPopupWidget, self).__init__(parent)

        # define custom properties
        self._anchor = XPopupWidget.Anchor.TopCenter
        self._autoCalculateAnchor = False
        self._autoCloseOnAccept = True
        self._autoCloseOnReject = True
        self._autoCloseOnFocusOut = False
        self._autoDefault = True
        self._first = True
        self._animated = False
        self._currentMode = None
        self._positionLinkedTo = []

        # define controls
        self._resizable = True
        self._popupPadding = 10
        self._titleBarVisible = True
        self._buttonBoxVisible = True
        self._dialogButton = QToolButton(self)
        self._closeButton = QToolButton(self)
        self._scrollArea = QScrollArea(self)
        self._sizeGrip = QSizeGrip(self)
        self._sizeGrip.setFixedWidth(12)
        self._sizeGrip.setFixedHeight(12)

        self._leftSizeGrip = QSizeGrip(self)
        self._leftSizeGrip.setFixedWidth(12)
        self._leftSizeGrip.setFixedHeight(12)

        if buttons is None:
            buttons = QDialogButtonBox.NoButton

        self._buttonBox = QDialogButtonBox(buttons, Qt.Horizontal, self)
        self._buttonBox.setContentsMargins(3, 0, 3, 9)

        self._scrollArea.setWidgetResizable(True)
        self._scrollArea.setFrameShape(QScrollArea.NoFrame)
        self._scrollArea.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)

        palette = self.palette()
        self._scrollArea.setPalette(palette)

        self._dialogButton.setToolTip('Popout to Dialog')
        self._closeButton.setToolTip('Close Popup')

        for btn in (self._dialogButton, self._closeButton):
            btn.setAutoRaise(True)
            btn.setIconSize(QSize(14, 14))
            btn.setMaximumSize(16, 16)

        # setup the icons
        icon = QIcon(projexui.resources.find('img/dialog.png'))
        self._dialogButton.setIcon(icon)

        icon = QIcon(projexui.resources.find('img/close.png'))
        self._closeButton.setIcon(icon)

        # define the ui
        hlayout = QHBoxLayout()
        hlayout.setSpacing(0)
        hlayout.addStretch(1)
        hlayout.addWidget(self._dialogButton)
        hlayout.addWidget(self._closeButton)
        hlayout.setContentsMargins(0, 0, 0, 0)

        hlayout2 = QHBoxLayout()
        hlayout2.addWidget(self._buttonBox)
        hlayout2.setContentsMargins(0, 0, 3, 0)

        vlayout = QVBoxLayout()
        vlayout.addLayout(hlayout)
        vlayout.addWidget(self._scrollArea)
        vlayout.addLayout(hlayout2)
        vlayout.setContentsMargins(3, 2, 3, 2)
        vlayout.setSpacing(0)

        self.setLayout(vlayout)
        self.setPositionLinkedTo(parent)

        # set default properties
        self.setAutoFillBackground(True)
        self.setBackgroundRole(QPalette.Button)
        self.setWindowTitle('Popup')
        self.setFocusPolicy(Qt.StrongFocus)
        self.setCurrentMode(XPopupWidget.Mode.Popup)

        # create connections
        self._dialogButton.clicked.connect(self.setDialogMode)
        self._closeButton.clicked.connect(self.reject)
        self._buttonBox.accepted.connect(self.accept)
        self._buttonBox.rejected.connect(self.reject)
        self._buttonBox.clicked.connect(self.handleButtonClick)

    def addButton(self, button, role=QDialogButtonBox.ActionRole):
        """
        Adds a custom button to the button box for this popup widget.
        
        :param      button | <QAbstractButton> || <str>
        
        :return     <button> || None (based on if a button or string was given)
        """
        return self._buttonBox.addButton(button, role)

    def adjustContentsMargins(self):
        """
        Adjusts the contents for this widget based on the anchor and \
        mode.
        """
        anchor = self.anchor()
        mode = self.currentMode()

        # margins for a dialog
        if (mode == XPopupWidget.Mode.Dialog):
            self.setContentsMargins(0, 0, 0, 0)

        # margins for a top anchor point
        elif (anchor &
              (XPopupWidget.Anchor.TopLeft | XPopupWidget.Anchor.TopCenter
               | XPopupWidget.Anchor.TopRight)):
            self.setContentsMargins(0, self.popupPadding() + 5, 0, 0)

        # margins for a bottom anchor point
        elif (
                anchor &
            (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter
             | XPopupWidget.Anchor.BottomRight)):
            self.setContentsMargins(0, 0, 0, self.popupPadding())

        # margins for a left anchor point
        elif (anchor &
              (XPopupWidget.Anchor.LeftTop | XPopupWidget.Anchor.LeftCenter
               | XPopupWidget.Anchor.LeftBottom)):
            self.setContentsMargins(self.popupPadding(), 0, 0, 0)

        # margins for a right anchor point
        else:
            self.setContentsMargins(0, 0, self.popupPadding(), 0)

        self.adjustMask()

    def adjustMask(self):
        """
        Updates the alpha mask for this popup widget.
        """
        if self.currentMode() == XPopupWidget.Mode.Dialog:
            self.clearMask()
            return

        path = self.borderPath()
        bitmap = QBitmap(self.width(), self.height())
        bitmap.fill(QColor('white'))

        painter = QPainter()
        painter.begin(bitmap)
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen(QColor('black'))
        pen.setWidthF(0.75)
        painter.setPen(pen)
        painter.setBrush(QColor('black'))
        painter.drawPath(path)
        painter.end()

        self.setMask(bitmap)

    def adjustSize(self):
        """
        Adjusts the size of this popup to best fit the new widget size.
        """
        widget = self.centralWidget()
        if widget is None:
            super(XPopupWidget, self).adjustSize()
            return

        widget.adjustSize()
        hint = widget.minimumSizeHint()
        size = widget.minimumSize()

        width = max(size.width(), hint.width())
        height = max(size.height(), hint.height())

        width += 20
        height += 20

        if self._buttonBoxVisible:
            height += self.buttonBox().height() + 10

        if self._titleBarVisible:
            height += max(self._dialogButton.height(),
                          self._closeButton.height()) + 10

        curr_w = self.width()
        curr_h = self.height()

        # determine if we need to move based on our anchor
        anchor = self.anchor()
        if anchor & (self.Anchor.LeftBottom | self.Anchor.RightBottom | \
                       self.Anchor.BottomLeft | self.Anchor.BottomCenter | \
                       self.Anchor.BottomRight):
            delta_y = height - curr_h

        elif anchor & (self.Anchor.LeftCenter | self.Anchor.RightCenter):
            delta_y = (height - curr_h) / 2

        else:
            delta_y = 0

        if anchor & (self.Anchor.RightTop | self.Anchor.RightCenter | \
                       self.Anchor.RightTop | self.Anchor.TopRight):
            delta_x = width - curr_w

        elif anchor & (self.Anchor.TopCenter | self.Anchor.BottomCenter):
            delta_x = (width - curr_w) / 2

        else:
            delta_x = 0

        self.setMinimumSize(width, height)
        self.resize(width, height)

        pos = self.pos()
        pos.setX(pos.x() - delta_x)
        pos.setY(pos.y() - delta_y)

        self.move(pos)

    @qt.Slot()
    def accept(self):
        """
        Emits the accepted signal and closes the popup.
        """
        if not self.signalsBlocked():
            self.accepted.emit()

        if self.autoCloseOnAccept():
            self.close()

    def anchor(self):
        """
        Returns the anchor point for this popup widget.
        
        :return     <XPopupWidget.Anchor>
        """
        return self._anchor

    def autoCalculateAnchor(self):
        """
        Returns whether or not this popup should calculate the anchor point
        on popup based on the parent widget and the popup point.
        
        :return     <bool>
        """
        return self._autoCalculateAnchor

    def autoCloseOnAccept(self):
        """
        Returns whether or not this popup widget manages its own close on accept
        behavior.
        
        :return     <bool>
        """
        return self._autoCloseOnAccept

    def autoCloseOnReject(self):
        """
        Returns whether or not this popup widget manages its own close on reject
        behavior.
        
        :return     <bool>
        """
        return self._autoCloseOnReject

    def autoCloseOnFocusOut(self):
        """
        Returns whether or not this popup widget should auto-close when the user
        clicks off the view.
        
        :return     <bool>
        """
        return self._autoCloseOnFocusOut

    def autoDefault(self):
        """
        Returns whether or not clicking enter should default to the accept key.
        
        :return     <bool>
        """
        return self._autoDefault

    def borderPath(self):
        """
        Returns the border path that will be drawn for this widget.
        
        :return     <QPainterPath>
        """

        path = QPainterPath()

        x = 1
        y = 1
        w = self.width() - 2
        h = self.height() - 2
        pad = self.popupPadding()
        anchor = self.anchor()

        # create a path for a top-center based popup
        if anchor == XPopupWidget.Anchor.TopCenter:
            path.moveTo(x, y + pad)
            path.lineTo(x + ((w / 2) - pad), y + pad)
            path.lineTo(x + (w / 2), y)
            path.lineTo(x + ((w / 2) + pad), y + pad)
            path.lineTo(x + w, y + pad)
            path.lineTo(x + w, y + h)
            path.lineTo(x, y + h)
            path.lineTo(x, y + pad)

        # create a path for a top-left based popup
        elif anchor == XPopupWidget.Anchor.TopLeft:
            path.moveTo(x, y + pad)
            path.lineTo(x + pad, y)
            path.lineTo(x + 2 * pad, y + pad)
            path.lineTo(x + w, y + pad)
            path.lineTo(x + w, y + h)
            path.lineTo(x, y + h)
            path.lineTo(x, y + pad)

        # create a path for a top-right based popup
        elif anchor == XPopupWidget.Anchor.TopRight:
            path.moveTo(x, y + pad)
            path.lineTo(x + w - 2 * pad, y + pad)
            path.lineTo(x + w - pad, y)
            path.lineTo(x + w, y + pad)
            path.lineTo(x + w, y + h)
            path.lineTo(x, y + h)
            path.lineTo(x, y + pad)

        # create a path for a bottom-left based popup
        elif anchor == XPopupWidget.Anchor.BottomLeft:
            path.moveTo(x, y)
            path.lineTo(x + w, y)
            path.lineTo(x + w, y + h - pad)
            path.lineTo(x + 2 * pad, y + h - pad)
            path.lineTo(x + pad, y + h)
            path.lineTo(x, y + h - pad)
            path.lineTo(x, y)

        # create a path for a south based popup
        elif anchor == XPopupWidget.Anchor.BottomCenter:
            path.moveTo(x, y)
            path.lineTo(x + w, y)
            path.lineTo(x + w, y + h - pad)
            path.lineTo(x + ((w / 2) + pad), y + h - pad)
            path.lineTo(x + (w / 2), y + h)
            path.lineTo(x + ((w / 2) - pad), y + h - pad)
            path.lineTo(x, y + h - pad)
            path.lineTo(x, y)

        # create a path for a bottom-right based popup
        elif anchor == XPopupWidget.Anchor.BottomRight:
            path.moveTo(x, y)
            path.lineTo(x + w, y)
            path.lineTo(x + w, y + h - pad)
            path.lineTo(x + w - pad, y + h)
            path.lineTo(x + w - 2 * pad, y + h - pad)
            path.lineTo(x, y + h - pad)
            path.lineTo(x, y)

        # create a path for a right-top based popup
        elif anchor == XPopupWidget.Anchor.RightTop:
            path.moveTo(x, y)
            path.lineTo(x + w - pad, y)
            path.lineTo(x + w, y + pad)
            path.lineTo(x + w - pad, y + 2 * pad)
            path.lineTo(x + w - pad, y + h)
            path.lineTo(x, y + h)
            path.lineTo(x, y)

        # create a path for a right-center based popup
        elif anchor == XPopupWidget.Anchor.RightCenter:
            path.moveTo(x, y)
            path.lineTo(x + w - pad, y)
            path.lineTo(x + w - pad, y + ((h / 2) - pad))
            path.lineTo(x + w, y + (h / 2))
            path.lineTo(x + w - pad, y + ((h / 2) + pad))
            path.lineTo(x + w - pad, y + h)
            path.lineTo(x, y + h)
            path.lineTo(x, y)

        # create a path for a right-bottom based popup
        elif anchor == XPopupWidget.Anchor.RightBottom:
            path.moveTo(x, y)
            path.lineTo(x + w - pad, y)
            path.lineTo(x + w - pad, y + h - 2 * pad)
            path.lineTo(x + w, y + h - pad)
            path.lineTo(x + w - pad, y + h)
            path.lineTo(x, y + h)
            path.lineTo(x, y)

        # create a path for a left-top based popup
        elif anchor == XPopupWidget.Anchor.LeftTop:
            path.moveTo(x + pad, y)
            path.lineTo(x + w, y)
            path.lineTo(x + w, y + h)
            path.lineTo(x + pad, y + h)
            path.lineTo(x + pad, y + 2 * pad)
            path.lineTo(x, y + pad)
            path.lineTo(x + pad, y)

        # create a path for an left-center based popup
        elif anchor == XPopupWidget.Anchor.LeftCenter:
            path.moveTo(x + pad, y)
            path.lineTo(x + w, y)
            path.lineTo(x + w, y + h)
            path.lineTo(x + pad, y + h)
            path.lineTo(x + pad, y + ((h / 2) + pad))
            path.lineTo(x, y + (h / 2))
            path.lineTo(x + pad, y + ((h / 2) - pad))
            path.lineTo(x + pad, y)

        # create a path for a left-bottom based popup
        elif anchor == XPopupWidget.Anchor.LeftBottom:
            path.moveTo(x + pad, y)
            path.lineTo(x + w, y)
            path.lineTo(x + w, y + h)
            path.lineTo(x + pad, y + h)
            path.lineTo(x, y + h - pad)
            path.lineTo(x + pad, y + h - 2 * pad)
            path.lineTo(x + pad, y)

        return path

    def buttonBox(self):
        """
        Returns the button box that is used to control this popup widget.
        
        :return     <QDialogButtonBox>
        """
        return self._buttonBox

    def centralWidget(self):
        """
        Returns the central widget that is being used by this popup.
        
        :return     <QWidget>
        """
        return self._scrollArea.widget()

    def close(self):
        """
        Closes the popup widget and central widget.
        """
        widget = self.centralWidget()
        if widget and not widget.close():
            return

        super(XPopupWidget, self).close()

    def closeEvent(self, event):
        widget = self.centralWidget()
        if widget and not widget.close() and \
           self.currentMode() != XPopupWidget.Mode.ToolTip:
            event.ignore()
        else:
            super(XPopupWidget, self).closeEvent(event)

        self.closed.emit()

    def currentMode(self):
        """
        Returns the current mode for this widget.
        
        :return     <XPopupWidget.Mode>
        """
        return self._currentMode

    @deprecatedmethod('XPopupWidget',
                      'Direction is no longer used, use anchor instead')
    def direction(self):
        """
        Returns the current direction parameter for this widget.
        
        :return     <XPopupWidget.Direction>
        """
        anchor = self.anchor()
        if (anchor &
            (XPopupWidget.Anchor.TopLeft | XPopupWidget.Anchor.TopCenter
             | XPopupWidget.Anchor.TopRight)):
            return XPopupWidget.Direction.North

        elif (
                anchor &
            (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter
             | XPopupWidget.Anchor.BottomRight)):
            return XPopupWidget.Direction.South

        elif (anchor &
              (XPopupWidget.Anchor.LeftTop | XPopupWidget.Anchor.LeftCenter
               | XPopupWidget.Anchor.LeftBottom)):
            return XPopupWidget.Direction.East

        else:
            return XPopupWidget.Direction.West

    def eventFilter(self, object, event):
        """
        Processes when the window is moving to update the position for the
        popup if in popup mode.
        
        :param      object | <QObject>
                    event  | <QEvent>
        """
        links = self.positionLinkedTo()
        is_dialog = self.currentMode() == self.Mode.Dialog
        if object not in links:
            return False

        if event.type() == event.Close:
            self.close()
            return False

        if event.type() == event.Hide and not is_dialog:
            self.hide()
            return False

        if event.type() == event.Move and not is_dialog:
            deltaPos = event.pos() - event.oldPos()
            self.move(self.pos() + deltaPos)
            return False

        if self.currentMode() != self.Mode.ToolTip:
            return False

        if event.type() == event.Leave:
            pos = object.mapFromGlobal(QCursor.pos())
            if (not object.rect().contains(pos)):
                self.close()
                event.accept()
                return True

        if event.type() in (event.MouseButtonPress, event.MouseButtonDblClick):
            self.close()
            event.accept()
            return True

        return False

    @qt.Slot(QAbstractButton)
    def handleButtonClick(self, button):
        """
        Handles the button click for this widget.  If the Reset button was
        clicked, then the resetRequested signal will be emitted.  All buttons
        will emit the buttonClicked signal.
        
        :param      button | <QAbstractButton>
        """
        if (self.signalsBlocked()):
            return

        if (button == self._buttonBox.button(QDialogButtonBox.Reset)):
            self.resetRequested.emit()

        self.buttonClicked.emit(button)

    def isAnimated(self):
        """
        Returns whether or not the popup widget should animate its opacity
        when it is shown.
        
        :return     <bool>
        """
        return self._animated

    def isResizable(self):
        """
        Returns if this popup is resizable or not.
        
        :return     <bool>
        """
        return self._resizable

    def keyPressEvent(self, event):
        """
        Looks for the Esc key to close the popup.
        
        :param      event | <QKeyEvent>
        """
        if (event.key() == Qt.Key_Escape):
            self.reject()
            event.accept()
            return

        elif (event.key() in (Qt.Key_Return, Qt.Key_Enter)):
            if self._autoDefault:
                self.accept()
                event.accept()
            return

        super(XPopupWidget, self).keyPressEvent(event)

    def mapAnchorFrom(self, widget, globalPos):
        """
        Returns the anchor point that best fits within the given widget from
        the inputed global position.
        
        :param      widget      | <QWidget>
                    globalPos   | <QPoint>
        
        :return     <XPopupWidget.Anchor>
        """
        localPos = widget.mapFromGlobal(globalPos)

        x = localPos.x()
        y = localPos.y()
        w = widget.width()
        h = widget.height()

        cw = self.width() / 2
        ch = self.height() / 2

        # by default, try to do a center point, so make sure the center point
        # is at least 1/2 the width longer from each edge
        if x < cw and h - y < ch:
            return XPopupWidget.Anchor.BottomLeft
        elif x < cw:
            return XPopupWidget.Anchor.TopLeft
        elif w - x < cw and h - y < ch:
            return XPopupWidget.Anchor.BottomRight
        elif w - x < cw:
            return XPopupWidget.Anchor.TopRight
        elif h - y < ch:
            return XPopupWidget.Anchor.BottomCenter
        else:
            return XPopupWidget.Anchor.TopCenter

    def popup(self, pos=None):
        """
        Pops up this widget at the inputed position.  The inputed point should \
        be in global space.
        
        :param      pos | <QPoint>
        
        :return     <bool> success
        """
        if self._first and self.centralWidget() is not None:
            self.adjustSize()
            self._first = False

        if not self.signalsBlocked():
            self.aboutToShow.emit()

        if not pos:
            pos = QCursor.pos()

        if self.currentMode() == XPopupWidget.Mode.Dialog and \
             self.isVisible():
            return False

        elif self.currentMode() == XPopupWidget.Mode.Dialog:
            self.setPopupMode()

        # auto-calculate the point
        if self.autoCalculateAnchor():
            self.setAnchor(self.mapAnchorFrom(self.parent(), pos))

        pad = self.popupPadding()

        # determine where to move based on the anchor
        anchor = self.anchor()

        # MODIFY X POSITION
        # align x-left
        if (anchor &
            (XPopupWidget.Anchor.TopLeft | XPopupWidget.Anchor.BottomLeft)):
            pos.setX(pos.x() - pad)

        # align x-center
        elif (anchor & (XPopupWidget.Anchor.TopCenter
                        | XPopupWidget.Anchor.BottomCenter)):
            pos.setX(pos.x() - self.width() / 2)

        # align x-right
        elif (
                anchor &
            (XPopupWidget.Anchor.TopRight | XPopupWidget.Anchor.BottomRight)):
            pos.setX(pos.x() - self.width() + pad)

        # align x-padded
        elif (anchor &
              (XPopupWidget.Anchor.RightTop | XPopupWidget.Anchor.RightCenter
               | XPopupWidget.Anchor.RightBottom)):
            pos.setX(pos.x() - self.width())

        # MODIFY Y POSITION
        # align y-top
        if (anchor &
            (XPopupWidget.Anchor.LeftTop | XPopupWidget.Anchor.RightTop)):
            pos.setY(pos.y() - pad)

        # align y-center
        elif (anchor & (XPopupWidget.Anchor.LeftCenter
                        | XPopupWidget.Anchor.RightCenter)):
            pos.setY(pos.y() - self.height() / 2)

        # align y-bottom
        elif (anchor & (XPopupWidget.Anchor.LeftBottom
                        | XPopupWidget.Anchor.RightBottom)):
            pos.setY(pos.y() - self.height() + pad)

        # align y-padded
        elif (
                anchor &
            (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter
             | XPopupWidget.Anchor.BottomRight)):
            pos.setY(pos.y() - self.height())

        self.adjustMask()
        self.move(pos)
        self.update()
        self.setUpdatesEnabled(True)

        if self.isAnimated():
            anim = QPropertyAnimation(self, 'windowOpacity')
            anim.setParent(self)
            anim.setStartValue(0.0)
            anim.setEndValue(self.windowOpacity())
            anim.setDuration(500)
            anim.finished.connect(anim.deleteLater)
            self.setWindowOpacity(0.0)
        else:
            anim = None

        self.show()

        if self.currentMode() != XPopupWidget.Mode.ToolTip:
            self.activateWindow()

            widget = self.centralWidget()
            if widget:
                self.centralWidget().setFocus()

        if anim:
            anim.start()

        if not self.signalsBlocked():
            self.shown.emit()

        return True

    def paintEvent(self, event):
        """
        Overloads the paint event to handle painting pointers for the popup \
        mode.
        
        :param      event | <QPaintEvent>
        """
        # use the base technique for the dialog mode
        if self.currentMode() == XPopupWidget.Mode.Dialog:
            super(XPopupWidget, self).paintEvent(event)
            return

        # setup the coloring options
        palette = self.palette()

        painter = QPainter()
        painter.begin(self)

        pen = QPen(palette.color(palette.Window).darker(130))
        pen.setWidthF(1.75)
        painter.setPen(pen)
        painter.setRenderHint(painter.Antialiasing)
        painter.setBrush(palette.color(palette.Window))
        painter.drawPath(self.borderPath())
        painter.end()

    def popupPadding(self):
        """
        Returns the amount of pixels to pad the popup arrow for this widget.
        
        :return     <int>
        """
        return self._popupPadding

    def positionLinkedTo(self):
        """
        Returns the widget that this popup is linked to for positional changes.
        
        :return     [<QWidget>, ..]
        """
        return self._positionLinkedTo

    @qt.Slot()
    def reject(self):
        """
        Emits the accepted signal and closes the popup.
        """
        if not self.signalsBlocked():
            self.rejected.emit()

        if self.autoCloseOnReject():
            self.close()

    def resizeEvent(self, event):
        """
        Resizes this widget and updates the mask.
        
        :param      event | <QResizeEvent>
        """
        self.setUpdatesEnabled(False)
        super(XPopupWidget, self).resizeEvent(event)

        self.adjustMask()
        self.setUpdatesEnabled(True)

        x = self.width() - self._sizeGrip.width()
        y = self.height() - self._sizeGrip.height()

        self._leftSizeGrip.move(0, y)
        self._sizeGrip.move(x, y)

    def scrollArea(self):
        """
        Returns the scroll area widget for this popup.
        
        :return     <QScrollArea>
        """
        return self._scrollArea

    def setAnimated(self, state):
        """
        Sets whether or not the popup widget should animate its opacity
        when it is shown.
        
        :param      state | <bool>
        """
        self._animated = state
        self.setAttribute(Qt.WA_TranslucentBackground, state)

    def setAutoCloseOnAccept(self, state):
        """
        Sets whether or not the popup handles closing for accepting states.
        
        :param      state | <bool>
        """
        self._autoCloseOnAccept = state

    def setAutoCloseOnReject(self, state):
        """
        Sets whether or not the popup handles closing for rejecting states.
        
        :param      state | <bool>
        """
        self._autoCloseOnReject = state

    def setAutoDefault(self, state):
        """
        Sets whether or not the buttons should respond to defaulting options
        when the user is interacting with it.
        
        :param      state | <bool>
        """
        self._autoDefault = state
        for button in self.buttonBox().buttons():
            button.setAutoDefault(state)
            button.setDefault(state)

    def setAnchor(self, anchor):
        """
        Sets the anchor position for this popup widget to the inputed point.
        
        :param      anchor | <XPopupWidget.Anchor>
        """
        self._anchor = anchor
        self.adjustContentsMargins()

    def setAutoCalculateAnchor(self, state):
        """
        Sets whether or not this widget should auto-calculate the anchor point
        based on the parent position when the popup is triggered.
        
        :param      state | <bool>
        """
        self._autoCalculateAnchor = state

    def setAutoCloseOnFocusOut(self, state):
        """
        Sets whether or not this popup widget should auto-close when the user
        clicks off the view.
        
        :param     state | <bool>
        """
        self._autoCloseOnFocusOut = state
        self.updateModeSettings()

    def setCentralWidget(self, widget):
        """
        Sets the central widget that will be used by this popup.
        
        :param      widget | <QWidget> || None
        """
        self._scrollArea.takeWidget()
        self._scrollArea.setWidget(widget)

        self.adjustSize()

    def setCurrentMode(self, mode):
        """
        Sets the current mode for this dialog to the inputed mode.
        
        :param      mode | <XPopupWidget.Mode>
        """
        if (self._currentMode == mode):
            return

        self._currentMode = mode
        self.updateModeSettings()

    @qt.Slot()
    def setDialogMode(self):
        """
        Sets the current mode value to Dialog.
        """
        self.setCurrentMode(XPopupWidget.Mode.Dialog)

    @deprecatedmethod('XPopupWidget',
                      'Direction is no longer used, use setAnchor instead')
    def setDirection(self, direction):
        """
        Sets the direction for this widget to the inputed direction.
        
        :param      direction | <XPopupWidget.Direction>
        """
        if (direction == XPopupWidget.Direction.North):
            self.setAnchor(XPopupWidget.Anchor.TopCenter)

        elif (direction == XPopupWidget.Direction.South):
            self.setAnchor(XPopupWidget.Anchor.BottomCenter)

        elif (direction == XPopupWidget.Direction.East):
            self.setAnchor(XPopupWidget.Anchor.LeftCenter)

        else:
            self.setAnchor(XPopupWidget.Anchor.RightCenter)

    def setPalette(self, palette):
        """
        Sets the palette for this widget and the scroll area.
        
        :param      palette | <QPalette>
        """
        super(XPopupWidget, self).setPalette(palette)
        self._scrollArea.setPalette(palette)

    def setPopupMode(self):
        """
        Sets the current mode value to Popup.
        """
        self.setCurrentMode(XPopupWidget.Mode.Popup)

    def setPopupPadding(self, padding):
        """
        Sets the amount to pad the popup area when displaying this widget.
        
        :param      padding | <int>
        """
        self._popupPadding = padding
        self.adjustContentsMargins()

    def setPositionLinkedTo(self, widgets):
        """
        Sets the widget that this popup will be linked to for positional
        changes.
        
        :param      widgets | <QWidget> || [<QWidget>, ..]
        """
        if type(widgets) in (list, set, tuple):
            new_widgets = list(widgets)
        else:
            new_widgets = []
            widget = widgets
            while widget:
                widget.installEventFilter(self)
                new_widgets.append(widget)
                widget = widget.parent()

        self._positionLinkedTo = new_widgets

    def setResizable(self, state):
        self._resizable = state
        self._sizeGrip.setVisible(state)
        self._leftSizeGrip.setVisible(state)

    def setShowButtonBox(self, state):
        self._buttonBoxVisible = state
        self.buttonBox().setVisible(state)

    def setShowTitleBar(self, state):
        self._titleBarVisible = state
        self._dialogButton.setVisible(state)
        self._closeButton.setVisible(state)

    def setToolTipMode(self):
        """
        Sets the mode for this popup widget to ToolTip
        """
        self.setCurrentMode(XPopupWidget.Mode.ToolTip)

    def setVisible(self, state):
        super(XPopupWidget, self).setVisible(state)
        widget = self.centralWidget()
        if widget:
            widget.setVisible(state)

    def timerEvent(self, event):
        """
        When the timer finishes, hide the tooltip popup widget.
        
        :param      event | <QEvent>
        """
        if self.currentMode() == XPopupWidget.Mode.ToolTip:
            self.killTimer(event.timerId())
            event.accept()
            self.close()
        else:
            super(XPopupWidget, self).timerEvent(event)

    def updateModeSettings(self):
        mode = self.currentMode()
        is_visible = self.isVisible()

        # display as a floating dialog
        if mode == XPopupWidget.Mode.Dialog:
            self.setWindowFlags(Qt.Dialog | Qt.Tool)
            self.setAttribute(Qt.WA_TransparentForMouseEvents, False)
            self._closeButton.setVisible(False)
            self._dialogButton.setVisible(False)

        # display as a user tooltip
        elif mode == XPopupWidget.Mode.ToolTip:
            flags = Qt.Popup | Qt.FramelessWindowHint

            self.setWindowFlags(flags)
            self.setBackgroundRole(QPalette.Window)
            self.setAttribute(Qt.WA_TransparentForMouseEvents)
            self.setShowTitleBar(False)
            self.setShowButtonBox(False)
            self.setFocusPolicy(Qt.NoFocus)

            # hide the scrollbars
            policy = Qt.ScrollBarAlwaysOff
            self._scrollArea.setVerticalScrollBarPolicy(policy)
            self._scrollArea.setHorizontalScrollBarPolicy(policy)

        # display as a popup widget
        else:
            flags = Qt.Popup | Qt.FramelessWindowHint

            if not self.autoCloseOnFocusOut():
                flags |= Qt.Tool

            self.setWindowFlags(flags)
            self._closeButton.setVisible(self._titleBarVisible)
            self._dialogButton.setVisible(self._titleBarVisible)
            self.setBackgroundRole(QPalette.Button)

        self.adjustContentsMargins()

        if (is_visible):
            self.show()

    @staticmethod
    @deprecatedmethod('XPopupWidget',
                      'This method no longer has an effect as we are not '\
                      'storing references to the tooltip.')
    def hideToolTip(key=None):
        """
        Hides any existing tooltip popup widgets.
        
        :warning    This method is deprecated!
        """
        pass

    @staticmethod
    def showToolTip(text,
                    point=None,
                    anchor=None,
                    parent=None,
                    background=None,
                    foreground=None,
                    key=None,
                    seconds=5):
        """
        Displays a popup widget as a tooltip bubble.
        
        :param      text        | <str>
                    point       | <QPoint> || None
                    anchor      | <XPopupWidget.Mode.Anchor> || None
                    parent      | <QWidget> || None
                    background  | <QColor> || None
                    foreground  | <QColor> || None
                    key         | <str> || None
                    seconds     | <int>
        """
        if point is None:
            point = QCursor.pos()

        if parent is None:
            parent = QApplication.activeWindow()

        if anchor is None and parent is None:
            anchor = XPopupWidget.Anchor.TopCenter

        # create a new tooltip widget
        widget = XPopupWidget(parent)
        widget.setToolTipMode()
        widget.setResizable(False)

        # create the tooltip label
        label = QLabel(text, widget)
        label.setOpenExternalLinks(True)
        label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        label.setMargin(3)
        label.setIndent(3)
        label.adjustSize()

        widget.setCentralWidget(label)

        # update the tip
        label.adjustSize()
        widget.adjustSize()

        palette = widget.palette()
        if not background:
            background = palette.color(palette.ToolTipBase)
        if not foreground:
            foreground = palette.color(palette.ToolTipText)

        palette.setColor(palette.Window, QColor(background))
        palette.setColor(palette.WindowText, QColor(foreground))
        widget.setPalette(palette)
        widget.centralWidget().setPalette(palette)

        if anchor is None:
            widget.setAutoCalculateAnchor(True)
        else:
            widget.setAnchor(anchor)

        widget.setAutoCloseOnFocusOut(True)
        widget.setAttribute(Qt.WA_DeleteOnClose)
        widget.popup(point)
        widget.startTimer(1000 * seconds)

        return widget