Ejemplo n.º 1
0
 def dragMoveEvent(self, event):
     QTreeView.dragMoveEvent(self, event)
     self.setDropIndicatorShown(False)
     index = self.indexAt(event.pos())
     if not index.isValid():
         return
     src_is_tb = event.mimeData().hasFormat('application/calibre+from_tag_browser')
     item = index.data(Qt.UserRole)
     if item.type == TagTreeItem.ROOT:
         return
     flags = self._model.flags(index)
     if item.type == TagTreeItem.TAG and flags & Qt.ItemIsDropEnabled:
         self.setDropIndicatorShown(not src_is_tb)
         return
     if item.type == TagTreeItem.CATEGORY and not item.is_gst:
         fm_dest = self.db.metadata_for_field(item.category_key)
         if fm_dest['kind'] == 'user':
             if src_is_tb:
                 if event.dropAction() == Qt.MoveAction:
                     data = bytes(event.mimeData().data('application/calibre+from_tag_browser'))
                     src = json_loads(data)
                     for s in src:
                         if s[0] == TagTreeItem.TAG and \
                                 (not s[1].startswith('@') or s[2]):
                             return
                 self.setDropIndicatorShown(True)
                 return
             md = event.mimeData()
             if hasattr(md, 'column_name'):
                 fm_src = self.db.metadata_for_field(md.column_name)
                 if md.column_name in ['authors', 'publisher', 'series'] or \
                         (fm_src['is_custom'] and (
                          (fm_src['datatype'] in ['series', 'text', 'enumeration'] and not fm_src['is_multiple']) or (
                              fm_src['datatype'] == 'composite' and fm_src['display'].get('make_category', False)))):
                     self.setDropIndicatorShown(True)
Ejemplo n.º 2
0
 def mouseMoveEvent(self, event):
     dex = self.indexAt(event.pos())
     if dex.isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     if not event.buttons() & Qt.LeftButton:
         return
     if self.in_drag_drop or not dex.isValid():
         QTreeView.mouseMoveEvent(self, event)
         return
     # Must deal with odd case where the node being dragged is 'virtual',
     # created to form a hierarchy. We can't really drag this node, but in
     # addition we can't allow drag recognition to notice going over some
     # other node and grabbing that one. So we set in_drag_drop to prevent
     # this from happening, turning it off when the user lifts the button.
     self.in_drag_drop = True
     if not self._model.flags(dex) & Qt.ItemIsDragEnabled:
         QTreeView.mouseMoveEvent(self, event)
         return
     md = self._model.mimeData([dex])
     pixmap = dex.data(DRAG_IMAGE_ROLE).pixmap(self.iconSize())
     drag = QDrag(self)
     drag.setPixmap(pixmap)
     drag.setMimeData(md)
     if self._model.is_in_user_category(dex):
         drag.exec_(Qt.CopyAction|Qt.MoveAction, Qt.CopyAction)
     else:
         drag.exec_(Qt.CopyAction)
Ejemplo n.º 3
0
    def __init__(self, *args):
        QTreeView.__init__(self, *args)
        self.delegate = Delegate(self)
        self.setItemDelegate(self.delegate)
        self.setMinimumWidth(80)
        self.header().close()
        self.setMouseTracking(True)
        self.setStyleSheet('''
                QTreeView {
                    background-color: palette(window);
                    color: palette(window-text);
                    border: none;
                }

                QTreeView::item {
                    border: 1px solid transparent;
                    padding-top:0.5ex;
                    padding-bottom:0.5ex;
                }

                QTreeView::item:hover {
                    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
                    border: 1px solid #bfcde4;
                    border-radius: 6px;
                }
        ''')
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.context_menu)
Ejemplo n.º 4
0
    def __init__(self, parent=None):
        QTreeView.__init__(self, parent=None)
        self.alter_tb = None
        self.disable_recounting = False
        self.setUniformRowHeights(True)
        self.setCursor(Qt.PointingHandCursor)
        self.setIconSize(QSize(20, 20))
        self.setTabKeyNavigation(True)
        self.setAnimated(True)
        self.setHeaderHidden(True)
        self.setItemDelegate(TagDelegate(self))
        self.made_connections = False
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDragDropMode(self.DragDrop)
        self.setDropIndicatorShown(True)
        self.in_drag_drop = False
        self.setAutoExpandDelay(500)
        self.pane_is_visible = False
        self.search_icon = QIcon(I("search.png"))
        self.user_category_icon = QIcon(I("tb_folder.png"))
        self.delete_icon = QIcon(I("list_remove.png"))
        self.rename_icon = QIcon(I("edit-undo.png"))

        self._model = TagsModel(self)
        self._model.search_item_renamed.connect(self.search_item_renamed)
        self._model.refresh_required.connect(self.refresh_required, type=Qt.QueuedConnection)
        self._model.tag_item_renamed.connect(self.tag_item_renamed)
        self._model.restriction_error.connect(self.restriction_error)
        self._model.user_categories_edited.connect(self.user_categories_edited, type=Qt.QueuedConnection)
        self._model.drag_drop_finished.connect(self.drag_drop_finished)
        stylish_tb = """
                QTreeView {
                    background-color: palette(window);
                    color: palette(window-text);
                    border: none;
                }
        """
        self.setStyleSheet(
            """
                QTreeView::item {
                    border: 1px solid transparent;
                    padding-top:0.8ex;
                    padding-bottom:0.8ex;
                }

                QTreeView::item:hover {
                    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
                    border: 1px solid #bfcde4;
                    border-radius: 6px;
                }
        """
            + ("" if gprefs["tag_browser_old_look"] else stylish_tb)
        )
        if gprefs["tag_browser_old_look"]:
            self.setAlternatingRowColors(True)
        # Allowing keyboard focus looks bad in the Qt Fusion style and is useless
        # anyway since the enter/spacebar keys do nothing
        self.setFocusPolicy(Qt.NoFocus)
Ejemplo n.º 5
0
    def __init__(self, *args):
        QTreeView.__init__(self,*args)

        self._model = Matches()
        self.setModel(self._model)

        self.rt_delegate = RichTextDelegate(self)

        for i in self._model.HTML_COLS:
            self.setItemDelegateForColumn(i, self.rt_delegate)
Ejemplo n.º 6
0
 def __init__(self, parent=None):
     QTreeView.__init__(self, parent)
     self.setHeaderHidden(True)
     self.setAnimated(True)
     self.activated.connect(self.item_activated)
     self.clicked.connect(self.item_activated)
     pi = plugins['progress_indicator'][0]
     if hasattr(pi, 'set_no_activate_on_click'):
         pi.set_no_activate_on_click(self)
     self.initialized = False
     self.setExpandsOnDoubleClick(False)
Ejemplo n.º 7
0
 def keyPressEvent(self, event):
     try:
         if self.handle_shortcuts(event):
             return
     except AttributeError:
         pass
     return QTreeView.keyPressEvent(self, event)
Ejemplo n.º 8
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self._layout = l = QGridLayout()
     self.setLayout(self._layout)
     self.header = QLabel(_('Double click on any entry to change the'
         ' keyboard shortcuts associated with it'))
     l.addWidget(self.header, 0, 0, 1, 3)
     self.view = QTreeView(self)
     self.view.setAlternatingRowColors(True)
     self.view.setHeaderHidden(True)
     self.view.setAnimated(True)
     l.addWidget(self.view, 1, 0, 1, 3)
     self.delegate = Delegate()
     self.view.setItemDelegate(self.delegate)
     self.delegate.sizeHintChanged.connect(self.editor_opened,
             type=Qt.QueuedConnection)
     self.delegate.changed_signal.connect(self.changed_signal)
     self.search = SearchBox2(self)
     self.search.initialize('shortcuts_search_history',
             help_text=_('Search for a shortcut by name'))
     self.search.search.connect(self.find)
     l.addWidget(self.search, 2, 0, 1, 1)
     self.nb = QPushButton(QIcon(I('arrow-down.png')), _('&Next'), self)
     self.pb = QPushButton(QIcon(I('arrow-up.png')), _('&Previous'), self)
     self.nb.clicked.connect(self.find_next)
     self.pb.clicked.connect(self.find_previous)
     l.addWidget(self.nb, 2, 1, 1, 1)
     l.addWidget(self.pb, 2, 2, 1, 1)
     l.setColumnStretch(0, 100)
Ejemplo n.º 9
0
 def keyPressEvent(self, event):
     try:
         if self.handle_shortcuts(event):
             return
     except AttributeError:
         pass
     return QTreeView.keyPressEvent(self, event)
Ejemplo n.º 10
0
 def setup_ui(self):
     self.l = l = QVBoxLayout(self)
     self.recipes = r = QTreeView(self)
     r.setAnimated(True)
     r.setHeaderHidden(True)
     self.model = ChooseBuiltinRecipeModel(self)
     self.model.setSourceModel(self.recipe_model)
     r.setModel(self.model)
     r.doubleClicked.connect(self.accept)
     self.search = s = SearchBox2(self)
     self.search.initialize('scheduler_search_history')
     self.search.setMinimumContentsLength(15)
     self.search.search.connect(self.recipe_model.search)
     self.recipe_model.searched.connect(self.search.search_done,
                                        type=Qt.QueuedConnection)
     self.recipe_model.searched.connect(self.search_done)
     self.go_button = b = QToolButton(self)
     b.setText(_("Go"))
     b.clicked.connect(self.search.do_search)
     h = QHBoxLayout()
     h.addWidget(s), h.addWidget(b)
     l.addLayout(h)
     l.addWidget(self.recipes)
     l.addWidget(self.bb)
     self.search.setFocus(Qt.OtherFocusReason)
Ejemplo n.º 11
0
    def dragMoveEvent(self, event):
        QTreeView.dragMoveEvent(self, event)
        self.setDropIndicatorShown(False)
        index = self.indexAt(event.pos())
        if not index.isValid():
            return
        src_is_tb = event.mimeData().hasFormat('application/calibre+from_tag_browser')
        item = index.data(Qt.UserRole)
        if item.type == TagTreeItem.ROOT:
            return

        if src_is_tb:
            src = json_loads(bytes(event.mimeData().data('application/calibre+from_tag_browser')))
            if len(src) == 1:
                src_item = self._model.get_node(self._model.index_for_path(src[0][5]))
                if (src_item.type == TagTreeItem.TAG and
                        src_item.tag.category == item.tag.category and
                        not item.temporary and
                        self._model.is_key_a_hierarchical_category(src_item.tag.category)):
                    event.setDropAction(Qt.MoveAction)
                    self.setDropIndicatorShown(True)
                    return
        if item.type == TagTreeItem.TAG and self._model.flags(index) & Qt.ItemIsDropEnabled:
            event.setDropAction(Qt.CopyAction)
            self.setDropIndicatorShown(not src_is_tb)
            return
        if item.type == TagTreeItem.CATEGORY and not item.is_gst:
            fm_dest = self.db.metadata_for_field(item.category_key)
            if fm_dest['kind'] == 'user':
                if src_is_tb:
                    if event.dropAction() == Qt.MoveAction:
                        # src is initialized above
                        for s in src:
                            if s[0] == TagTreeItem.TAG and \
                                    (not s[1].startswith('@') or s[2]):
                                return
                    self.setDropIndicatorShown(True)
                    return
                md = event.mimeData()
                if hasattr(md, 'column_name'):
                    fm_src = self.db.metadata_for_field(md.column_name)
                    if md.column_name in ['authors', 'publisher', 'series'] or \
                            (fm_src['is_custom'] and (
                             (fm_src['datatype'] in ['series', 'text', 'enumeration'] and not fm_src['is_multiple']) or (
                                 fm_src['datatype'] == 'composite' and fm_src['display'].get('make_category', False)))):
                        self.setDropIndicatorShown(True)
Ejemplo n.º 12
0
    def __init__(self, *args):
        QTreeView.__init__(self,*args)
            
        self._model = Matches([p for p in store_plugins()])
        self.setModel(self._model)
        
        self.setIconSize(QSize(24, 24))

        self.rt_delegate = RichTextDelegate(self)

        for i in self._model.HTML_COLS:
            self.setItemDelegateForColumn(i, self.rt_delegate)

        for i in xrange(self._model.columnCount()):
            self.resizeColumnToContents(i)
            
        self.model().sort(1, Qt.AscendingOrder)
        self.header().setSortIndicator(self.model().sort_col, self.model().sort_order)
Ejemplo n.º 13
0
    def __init__(self, *args):
        QTreeView.__init__(self,*args)

        self._model = Matches([p for p in store_plugins()])
        self.setModel(self._model)

        self.setIconSize(QSize(24, 24))

        self.rt_delegate = RichTextDelegate(self)

        for i in self._model.HTML_COLS:
            self.setItemDelegateForColumn(i, self.rt_delegate)

        for i in range(self._model.columnCount()):
            self.resizeColumnToContents(i)

        self.model().sort(1, Qt.AscendingOrder)
        self.header().setSortIndicator(self.model().sort_col, self.model().sort_order)
Ejemplo n.º 14
0
    def setLeftPage(self):

        self.treeView = QTreeView(self)
        self.treeView.setObjectName("treeView")
        self.left_page_Layout.addWidget(self.treeView)
        self.treeView.activated.connect(self.changeCurrentSet)
        self.tree_model = TreeModel(self.model)
        self.treeView.setModel(self.tree_model)
        self.treeView.setWindowTitle("Simple Tree Model")
        self.treeView.header().hide()
        self.treeView.setAlternatingRowColors(True)
Ejemplo n.º 15
0
    def __init__(self, parent=None):
        QTreeView.__init__(self, parent=None)
        self.setMouseTracking(True)
        self.alter_tb = None
        self.disable_recounting = False
        self.setUniformRowHeights(True)
        self.setIconSize(QSize(20, 20))
        self.setTabKeyNavigation(True)
        self.setAnimated(True)
        self.setHeaderHidden(True)
        self.setItemDelegate(TagDelegate(self))
        self.made_connections = False
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDragDropMode(self.DragDrop)
        self.setDropIndicatorShown(True)
        self.in_drag_drop = False
        self.setAutoExpandDelay(500)
        self.pane_is_visible = False
        self.search_icon = QIcon(I('search.png'))
        self.search_copy_icon = QIcon(I("search_copy_saved.png"))
        self.user_category_icon = QIcon(I('tb_folder.png'))
        self.edit_metadata_icon = QIcon(I('edit_input.png'))
        self.delete_icon = QIcon(I('list_remove.png'))
        self.rename_icon = QIcon(I('edit-undo.png'))

        self._model = TagsModel(self)
        self._model.search_item_renamed.connect(self.search_item_renamed)
        self._model.refresh_required.connect(self.refresh_required,
                                             type=Qt.QueuedConnection)
        self._model.tag_item_renamed.connect(self.tag_item_renamed)
        self._model.restriction_error.connect(self.restriction_error)
        self._model.user_categories_edited.connect(self.user_categories_edited,
                                                   type=Qt.QueuedConnection)
        self._model.drag_drop_finished.connect(self.drag_drop_finished)
        self.set_look_and_feel()
        # Allowing keyboard focus looks bad in the Qt Fusion style and is useless
        # anyway since the enter/spacebar keys do nothing
        self.setFocusPolicy(Qt.NoFocus)
        QApplication.instance().palette_changed.connect(
            self.set_style_sheet, type=Qt.QueuedConnection)
Ejemplo n.º 16
0
    def update_usb_devices(self):
        model = QStandardItemModel()
        bus = dbus.SystemBus()
        self.iface = 'org.freedesktop.DBus.ObjectManager'
        #bus.add_signal_receiver(self.callback_function, signal, iface)
        proxy = bus.get_object("org.freedesktop.UDisks2",
                               "/org/freedesktop/UDisks2")
        self.iface = dbus.Interface(proxy, "org.freedesktop.UDisks2")

        self.iface.connect_to_signal('DeviceAdded', self.device_added_callback)
        self.iface.connect_to_signal('DeviceRemoved',
                                     self.device_removed_callback)
        self.iface.connect_to_signal('InterfacesAdded',
                                     self.device_changed_callback)

        dev1 = get_usb()
        items = get_usb()

        #for text, checked in items:
        for text in sorted(items):

            text_item = QStandardItem(text)
            #checked_item = QStandardItem()
            #checked_item.setData(QVariant(checked), Qt.CheckStateRole)
            model.appendRow(text_item)  #([text_item, checked_item])

        view = QTreeView()
        view.header().hide()
        view.setRootIsDecorated(False)

        combo = self.ui.comboBox_device
        combo.setView(view)
        combo.setModel(model)
        combo.show()
Ejemplo n.º 17
0
 def dragMoveEvent(self, event):
     QTreeView.dragMoveEvent(self, event)
     self.setDropIndicatorShown(False)
     index = self.indexAt(event.pos())
     if not index.isValid():
         return
     src_is_tb = event.mimeData().hasFormat(
         'application/calibre+from_tag_browser')
     item = index.data(Qt.UserRole)
     if item.type == TagTreeItem.ROOT:
         return
     flags = self._model.flags(index)
     if item.type == TagTreeItem.TAG and flags & Qt.ItemIsDropEnabled:
         self.setDropIndicatorShown(not src_is_tb)
         return
     if item.type == TagTreeItem.CATEGORY and not item.is_gst:
         fm_dest = self.db.metadata_for_field(item.category_key)
         if fm_dest['kind'] == 'user':
             if src_is_tb:
                 if event.dropAction() == Qt.MoveAction:
                     data = str(event.mimeData().data(
                         'application/calibre+from_tag_browser'))
                     src = cPickle.loads(data)
                     for s in src:
                         if s[0] == TagTreeItem.TAG and \
                                 (not s[1].startswith('@') or s[2]):
                             return
                 self.setDropIndicatorShown(True)
                 return
             md = event.mimeData()
             if hasattr(md, 'column_name'):
                 fm_src = self.db.metadata_for_field(md.column_name)
                 if md.column_name in ['authors', 'publisher', 'series'] or \
                         (fm_src['is_custom'] and (
                          (fm_src['datatype'] in ['series', 'text', 'enumeration'] and
                           not fm_src['is_multiple']) or
                          (fm_src['datatype'] == 'composite' and
                           fm_src['display'].get('make_category', False)))):
                     self.setDropIndicatorShown(True)
Ejemplo n.º 18
0
    def __init__(self, parent=None):
        QTreeView.__init__(self, parent=None)
        self.setMouseTracking(True)
        self.alter_tb = None
        self.disable_recounting = False
        self.setUniformRowHeights(True)
        self.setIconSize(QSize(20, 20))
        self.setTabKeyNavigation(True)
        self.setAnimated(True)
        self.setHeaderHidden(True)
        self.setItemDelegate(TagDelegate(self))
        self.made_connections = False
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDragDropMode(self.DragDrop)
        self.setDropIndicatorShown(True)
        self.in_drag_drop = False
        self.setAutoExpandDelay(500)
        self.pane_is_visible = False
        self.search_icon = QIcon(I('search.png'))
        self.search_copy_icon = QIcon(I("search_copy_saved.png"))
        self.user_category_icon = QIcon(I('tb_folder.png'))
        self.delete_icon = QIcon(I('list_remove.png'))
        self.rename_icon = QIcon(I('edit-undo.png'))

        self._model = TagsModel(self)
        self._model.search_item_renamed.connect(self.search_item_renamed)
        self._model.refresh_required.connect(self.refresh_required,
                type=Qt.QueuedConnection)
        self._model.tag_item_renamed.connect(self.tag_item_renamed)
        self._model.restriction_error.connect(self.restriction_error)
        self._model.user_categories_edited.connect(self.user_categories_edited,
                type=Qt.QueuedConnection)
        self._model.drag_drop_finished.connect(self.drag_drop_finished)
        self.set_look_and_feel()
        # Allowing keyboard focus looks bad in the Qt Fusion style and is useless
        # anyway since the enter/spacebar keys do nothing
        self.setFocusPolicy(Qt.NoFocus)
Ejemplo n.º 19
0
 def mouseMoveEvent(self, event):
     dex = self.indexAt(event.pos())
     if self.in_drag_drop or not dex.isValid():
         QTreeView.mouseMoveEvent(self, event)
         return
     # Must deal with odd case where the node being dragged is 'virtual',
     # created to form a hierarchy. We can't really drag this node, but in
     # addition we can't allow drag recognition to notice going over some
     # other node and grabbing that one. So we set in_drag_drop to prevent
     # this from happening, turning it off when the user lifts the button.
     self.in_drag_drop = True
     if not self._model.flags(dex) & Qt.ItemIsDragEnabled:
         QTreeView.mouseMoveEvent(self, event)
         return
     md = self._model.mimeData([dex])
     pixmap = dex.data(Qt.DecorationRole).pixmap(25, 25)
     drag = QDrag(self)
     drag.setPixmap(pixmap)
     drag.setMimeData(md)
     if self._model.is_in_user_category(dex):
         drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction)
     else:
         drag.exec_(Qt.CopyAction)
Ejemplo n.º 20
0
 def dragMoveEvent(self, event):
     QTreeView.dragMoveEvent(self, event)
     self.setDropIndicatorShown(False)
     index = self.indexAt(event.pos())
     if not index.isValid():
         return
     src_is_tb = event.mimeData().hasFormat("application/calibre+from_tag_browser")
     item = index.data(Qt.UserRole)
     if item.type == TagTreeItem.ROOT:
         return
     flags = self._model.flags(index)
     if item.type == TagTreeItem.TAG and flags & Qt.ItemIsDropEnabled:
         self.setDropIndicatorShown(not src_is_tb)
         return
     if item.type == TagTreeItem.CATEGORY and not item.is_gst:
         fm_dest = self.db.metadata_for_field(item.category_key)
         if fm_dest["kind"] == "user":
             if src_is_tb:
                 if event.dropAction() == Qt.MoveAction:
                     data = str(event.mimeData().data("application/calibre+from_tag_browser"))
                     src = cPickle.loads(data)
                     for s in src:
                         if s[0] == TagTreeItem.TAG and (not s[1].startswith("@") or s[2]):
                             return
                 self.setDropIndicatorShown(True)
                 return
             md = event.mimeData()
             if hasattr(md, "column_name"):
                 fm_src = self.db.metadata_for_field(md.column_name)
                 if md.column_name in ["authors", "publisher", "series"] or (
                     fm_src["is_custom"]
                     and (
                         (fm_src["datatype"] in ["series", "text", "enumeration"] and not fm_src["is_multiple"])
                         or (fm_src["datatype"] == "composite" and fm_src["display"].get("make_category", False))
                     )
                 ):
                     self.setDropIndicatorShown(True)
Ejemplo n.º 21
0
    def __init__(self, *args):
        QTreeView.__init__(self, *args)
        self.setMinimumWidth(80)
        self.header().close()
        self.setMouseTracking(True)
        self.setStyleSheet('''
                QTreeView {
                    background-color: palette(window);
                    color: palette(window-text);
                    border: none;
                }

                QTreeView::item {
                    border: 1px solid transparent;
                    padding-top:0.5ex;
                    padding-bottom:0.5ex;
                }

                QTreeView::item:hover {
                    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
                    border: 1px solid #bfcde4;
                    border-radius: 6px;
                }
        ''')
Ejemplo n.º 22
0
    def __init__(self, *args):
        QTreeView.__init__(self, *args)
        self.setCursor(Qt.PointingHandCursor)
        self.setMinimumWidth(80)
        self.header().close()
        self.setStyleSheet('''
                QTreeView {
                    background-color: palette(window);
                    color: palette(window-text);
                    border: none;
                }

                QTreeView::item {
                    border: 1px solid transparent;
                    padding-top:0.5ex;
                    padding-bottom:0.5ex;
                }

                QTreeView::item:hover {
                    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
                    border: 1px solid #bfcde4;
                    border-radius: 6px;
                }
        ''')
Ejemplo n.º 23
0
 def init_UI(self):
     """creates the UI
     """
     self.log.debug("Setting up Navigation area UI...")
     self.tree = QTreeView()
     self.tree.doubleClicked.connect(self.onDoubleClick)
     self.grid = QGridLayout()
     self.setLayout(self.grid)
     self.header_lbl = QLabel("Projects and Samples:", self)
     self.header_lbl.setStyleSheet(general.label_style_2nd)
     self.grid.addWidget(self.header_lbl, 0,0)
     
     self.grid.addWidget(self.tree, 1, 0)
     header = self.tree.header()
     header.hide()
     self.log.debug("\t=> Done!")
class Widget(QWidget):
    def __init__(self):
        super().__init__()

        path = QDir.rootPath()

        self.model = QFileSystemModel()
        self.model.setRootPath(path)

        self.tree_view = QTreeView()
        self.tree_view.setModel(self.model)
        self.tree_view.setSelectionMode(QTreeView.ExtendedSelection)
        self.tree_view.selectionModel().selectionChanged.connect(
            self._on_selection_changed)

        self.list_files = QListWidget()

        self.button_add = QPushButton('Добавить!')
        self.button_add.setEnabled(False)
        self.button_add.clicked.connect(self._on_add)

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.tree_view)
        splitter.addWidget(self.list_files)

        main_layout = QVBoxLayout(self)
        main_layout.addWidget(splitter)
        main_layout.addWidget(self.button_add)

    def _on_selection_changed(self, selected, deselected):
        has = self.tree_view.selectionModel().hasSelection()
        self.button_add.setEnabled(has)

    def _on_add(self):
        for row in self.tree_view.selectionModel().selectedRows():
            path = self.model.filePath(row)
            self.list_files.addItem(path)
Ejemplo n.º 25
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.l = l = QVBoxLayout(self)
        self.h = h = QHBoxLayout()

        self.filter_edit = e = QLineEdit(self)
        l.addWidget(e)
        e.setPlaceholderText(_('Filter'))
        self.model = m = self.MODEL(self)
        self.proxy = p = self.PROXY(self)
        p.setSourceModel(m)
        self.view = f = QTreeView(self)
        f.setAlternatingRowColors(True)
        f.setHeaderHidden(True), f.setExpandsOnDoubleClick(False)
        f.setModel(p)
        l.addWidget(f)
        f.doubleClicked.connect(self.double_clicked)
        e.textChanged.connect(p.filter_text)

        l.addLayout(h)
        h.addWidget(QLabel(_('Sort by:')))
        self.counts_button = b = QRadioButton(_('&Counts'), self)
        b.setChecked(self.read_state('sort-on-counts', True))
        h.addWidget(b)
        self.name_button = b = QRadioButton(_('&Name'), self)
        b.setChecked(not self.read_state('sort-on-counts', True))
        h.addWidget(b)
        b.toggled.connect(self.resort)
        h.addStrut(20)
        self._sort_order = o = QComboBox(self)
        o.addItems([_('Ascending'), _('Descending')])
        o.setCurrentIndex(0 if self.read_state('sort-ascending', True) else 1)
        o.setEditable(False)
        o.currentIndexChanged[int].connect(self.resort)
        h.addWidget(o)
        h.addStretch(10)
        self.summary = la = QLabel('\xa0')
        h.addWidget(la)
Ejemplo n.º 26
0
 def mouseMoveEvent(self, event):
     dex = self.indexAt(event.pos())
     if dex.isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     if not event.buttons() & Qt.LeftButton:
         return
     if self.in_drag_drop or not dex.isValid():
         QTreeView.mouseMoveEvent(self, event)
         return
     # don't start drag/drop until the mouse has moved a bit.
     if ((event.pos() - self.possible_drag_start).manhattanLength() <
                                 QApplication.startDragDistance()):
         QTreeView.mouseMoveEvent(self, event)
         return
     # Must deal with odd case where the node being dragged is 'virtual',
     # created to form a hierarchy. We can't really drag this node, but in
     # addition we can't allow drag recognition to notice going over some
     # other node and grabbing that one. So we set in_drag_drop to prevent
     # this from happening, turning it off when the user lifts the button.
     self.in_drag_drop = True
     if not self._model.flags(dex) & Qt.ItemIsDragEnabled:
         QTreeView.mouseMoveEvent(self, event)
         return
     md = self._model.mimeData([dex])
     pixmap = dex.data(DRAG_IMAGE_ROLE).pixmap(self.iconSize())
     drag = QDrag(self)
     drag.setPixmap(pixmap)
     drag.setMimeData(md)
     if (self._model.is_in_user_category(dex) or
                 self._model.is_index_on_a_hierarchical_category(dex)):
         '''
         Things break if we specify MoveAction as the default, which is
         what we want for drag on hierarchical categories. Dragging user
         categories stops working. Don't know why. To avoid the problem
         we fix the action in dragMoveEvent.
         '''
         drag.exec_(Qt.CopyAction|Qt.MoveAction, Qt.CopyAction)
     else:
         drag.exec_(Qt.CopyAction)
Ejemplo n.º 27
0
 def mousePressEvent(self, event):
     if event.buttons() & Qt.LeftButton:
         self.possible_drag_start = event.pos()
     return QTreeView.mousePressEvent(self, event)
Ejemplo n.º 28
0
 def setModel(self, model):
     QTreeView.setModel(self, model)
     model.current_toc_nodes_changed.connect(
         self.current_toc_nodes_changed,
         type=Qt.ConnectionType.QueuedConnection)
Ejemplo n.º 29
0
 def __init__(self, parent):
     QTreeView.__init__(self, parent)
Ejemplo n.º 30
0
class Explorer(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''

        root = Container("Root")
        model = root.add(Model("Model"))
        test = model.add(Container("test"))
        cns = model.add(Model("Cns"))

        root2 = root.add(Container("Model 2"))
        leg = root2.add(Container("Leg"))
        bones = Model("Fk")
        leg.add(bones)

        bones.transform.scale.y.constrainer = cns.transform.scale.y
        cns.transform.scale = Vector(2, 3, 4)

        self.model = SceneGraphModel(root)
        self.view = QTreeView()
        self.view.setDragEnabled(True)
        self.view.setAcceptDrops(True)
        self.view.setDropIndicatorShown(True)
        self.view.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.view.setModel(self.model)

        self.objEditor = Obj3dEditor()
        self.objEditor.setModel(self.model)

        self.transformEditor = TransformEditor()
        self.transformEditor.setModel(self.model)

        self.view.selectionModel().currentChanged.connect(self.setSelection)

        self.view.setStyleSheet("""
        .QTreeView {
            background-color:rgb(61, 63, 65);
            color: #bbb;
            font-size : 12px;
            }
        .QHeaderView::section {
            height: 20px;
            font-size : 12px;
            background-color: rgb(65, 74, 91);
            color: #bbb;
            border: 1px solid rgba(20, 24, 24,0);
        }
        """)

    def setSelection(self, current, old):
        self.objEditor.setSelection(current, old)
        self.transformEditor.setSelection(current, old)

    def show(self):
        self.view.show()
Ejemplo n.º 31
0
 def mouseMoveEvent(self, ev):
     if self.indexAt(ev.pos()).isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     return QTreeView.mouseMoveEvent(self, ev)
Ejemplo n.º 32
0
 def mouseMoveEvent(self, ev):
     if self.indexAt(ev.pos()).isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     return QTreeView.mouseMoveEvent(self, ev)
Ejemplo n.º 33
0
 def setModel(self, model):
     QTreeView.setModel(self, model)
     model.auto_expand_nodes.connect(
         self.auto_expand_indices, type=Qt.ConnectionType.QueuedConnection)
Ejemplo n.º 34
0
class BookWarriorHomepage ( QWidget,Ui_BookWarriorHomepage):
    updateSelection = pyqtSignal()
    def __init__ (self,model,parent=None):
        super(BookWarriorHomepage,self).__init__(parent)
        self.setupUi(self)
        self.max_vignettes = 20
        self.nb_col = 0
        self.nb_row = 0
        self.vignettes_liste = []
        self.model = model
        self.settings = Config().instance.settings
        self.list_warrior = []  # utilise pour maj selection depuis warrrior layout
    def setLeftPage(self):

        self.treeView = QTreeView(self)
        self.treeView.setObjectName("treeView")
        self.left_page_Layout.addWidget(self.treeView)
        self.treeView.activated.connect(self.changeCurrentSet)
        self.tree_model = TreeModel(self.model)
        self.treeView.setModel(self.tree_model)
        self.treeView.setWindowTitle("Simple Tree Model")
        self.treeView.header().hide()
        self.treeView.setAlternatingRowColors(True)

#         i = 0
#         self.treeKingdom.setColumnCount(3)
#         for faction in self.model.factions.values() :
#             item_f = QTreeWidgetItem(self.treeKingdom)
#             #self.treeKingdom.insertTopLevelItem(i,item_f)
#             item_f.setText(i,faction.name)
#             i = i +1
#             for empire in faction.empires.values():
#                 item_e = QTreeWidgetItem()
#                 item_e.setText(i,empire.name)
#                 item_f.addChild(item_e)
#                 for kingdom in empire.kingdoms.values():
#                     item_k = QTreeWidgetItem()
#                     item_k.setText(i,kingdom.name)
#                     item_e.addChild(item_k)
#                     for groupe in kingdom.groupes.values():
#                         item_g = QTreeWidgetItem()
#                         item_g.setText(i,groupe.name)
#                         print ('groupe',groupe.name)
#                         item_k.addChild(item_g)
    
    def setRightContent (self, list_warrior):
        self.list_warrior = list_warrior
        for v in self.vignettes_liste : 
            v.setParent(None)
            self.gridLayout.removeWidget(v)
#         while self.gridLayout.takeAt(0) !=  None :
#             del self.gridLayout.takeAt(0).widget
#             item =  self.gridLayout.takeAt(0)
#             print ('ll')
#             del item
        self.nb_col = 0
        self.nb_row = 0
        self.vignettes_liste = []
        for i in range (min(len(list_warrior),self.max_vignettes)):
            self.addVignette(list_warrior[i],i)

    def updateContent(self):
        pass
        
    def addVignette (self,warrior,i):
        widget_vignette = QWidget(self.vignettes)        
        layout_one_vignette = QVBoxLayout(widget_vignette)
        layout_one_vignette.setSpacing(0)
        layout_one_vignette.setContentsMargins(0, 0, 0, 0)
        warrior_button = QPushButton(widget_vignette)
        # on met plus car dans le cas du signal clicked on enverra True ou False (0 ou 1)
        warrior_button.setObjectName(str(i+2))
        warrior_button.clicked.connect(self.parent().goWarriorPage)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        warrior_button.setFixedSize(QtCore.QSize(100,120))
        warrior_button.setSizePolicy(sizePolicy)
        layout_one_vignette.addWidget(warrior_button)
        
        # label
        warrior_label = HerosLabel(warrior,widget_vignette)
        layout_one_vignette.addWidget(warrior_label)
        
        max_col  = 3
        groupe_name = warrior.groupe().name
        if warrior.masterGroupe() != None : 
            groupe_name = warrior.masterGroupe().name+"/"+groupe_name
        

        #path = os.path.join(Config().instance.path_to_pic(),faction_name,empire_name,kingdom_name,"Picture",groupe_name,warrior_name
        icon = QIcon(warrior.thumb)

        #print (basepath+"/"+faction_name+"/"+empire_name+"/"+kingdom_name+"/Picture/"+groupe_name+"/"+warrior.name+"/portrait_thumbnail.jpg")
        warrior_button.setIcon(icon)
        warrior_button.setIconSize(QtCore.QSize(100,120))

        if self.nb_col == 0:
            self.nb_row = self.nb_row + 1


        self.gridLayout.addWidget(widget_vignette,self.nb_row,self.nb_col)
        self.vignettes_liste.append(widget_vignette)
        self.nb_col = (self.nb_col +1)%max_col
        
    def changeCurrentSet(self,index):
        print ('changecurrentset:')
        item = self.tree_model.metadata(index, QtCore.Qt.DecorationRole)
        list_warrior = item.getWarriorList()
        self.setRightContent(list_warrior)
        self.updateSelection.emit()
Ejemplo n.º 35
0
 def currentChanged(self, current, previous):
     QTreeView.currentChanged(self, current, previous)
     self.parent().current_changed(current, previous)
Ejemplo n.º 36
0
 def mouseReleaseEvent(self, event):
     # Swallow everything except leftButton so context menus work correctly
     if event.button() == Qt.LeftButton or self.in_drag_drop:
         QTreeView.mouseReleaseEvent(self, event)
         self.in_drag_drop = False
Ejemplo n.º 37
0
 def __init__(self, parent):
     QTreeView.__init__(self, parent)
     self.setAnimated(True)
     self.setHeaderHidden(True)
     self.setObjectName('recipes')
     self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
Ejemplo n.º 38
0
class ShortcutConfig(QWidget):  # {{{

    changed_signal = pyqtSignal()

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self._layout = l = QVBoxLayout(self)
        self.header = QLabel(
            _('Double click on any entry to change the'
              ' keyboard shortcuts associated with it'))
        l.addWidget(self.header)
        self.view = QTreeView(self)
        self.view.setAlternatingRowColors(True)
        self.view.setHeaderHidden(True)
        self.view.setAnimated(True)
        l.addWidget(self.view)
        self.delegate = Delegate()
        self.view.setItemDelegate(self.delegate)
        self.delegate.sizeHintChanged.connect(
            self.editor_opened, type=Qt.ConnectionType.QueuedConnection)
        self.delegate.changed_signal.connect(self.changed_signal)
        self.search = SearchBox2(self)
        self.search.initialize('shortcuts_search_history',
                               help_text=_('Search for a shortcut by name'))
        self.search.search.connect(self.find)
        self._h = h = QHBoxLayout()
        l.addLayout(h)
        h.addWidget(self.search)
        self.nb = QPushButton(QIcon(I('arrow-down.png')), _('&Next'), self)
        self.pb = QPushButton(QIcon(I('arrow-up.png')), _('&Previous'), self)
        self.nb.clicked.connect(self.find_next)
        self.pb.clicked.connect(self.find_previous)
        h.addWidget(self.nb), h.addWidget(self.pb)
        h.setStretch(0, 100)

    def restore_defaults(self):
        self._model.restore_defaults()
        self.changed_signal.emit()

    def commit(self):
        if self.view.state() == self.view.EditingState:
            self.delegate.accept_changes()
        self._model.commit()

    def initialize(self, keyboard):
        self._model = ConfigModel(keyboard, parent=self)
        self.view.setModel(self._model)

    def editor_opened(self, index):
        self.view.scrollTo(index, self.view.EnsureVisible)

    @property
    def is_editing(self):
        return self.view.state() == self.view.EditingState

    def find(self, query):
        if not query:
            return
        try:
            idx = self._model.find(query)
        except ParseException:
            self.search.search_done(False)
            return
        self.search.search_done(True)
        if not idx.isValid():
            info_dialog(self,
                        _('No matches'),
                        _('Could not find any shortcuts matching %s') % query,
                        show=True,
                        show_copy_button=False)
            return
        self.highlight_index(idx)

    def highlight_index(self, idx):
        self.view.scrollTo(idx)
        self.view.selectionModel().select(
            idx,
            self.view.selectionModel().ClearAndSelect)
        self.view.setCurrentIndex(idx)
        self.view.setFocus(Qt.FocusReason.OtherFocusReason)

    def find_next(self, *args):
        idx = self.view.currentIndex()
        if not idx.isValid():
            idx = self._model.index(0, 0)
        idx = self._model.find_next(idx,
                                    unicode_type(self.search.currentText()))
        self.highlight_index(idx)

    def find_previous(self, *args):
        idx = self.view.currentIndex()
        if not idx.isValid():
            idx = self._model.index(0, 0)
        idx = self._model.find_next(idx,
                                    unicode_type(self.search.currentText()),
                                    backwards=True)
        self.highlight_index(idx)

    def highlight_group(self, group_name):
        idx = self.view.model().index_for_group(group_name)
        if idx is not None:
            self.view.expand(idx)
            self.view.scrollTo(idx, self.view.PositionAtTop)
            self.view.selectionModel().select(
                idx,
                self.view.selectionModel().ClearAndSelect)
            self.view.setCurrentIndex(idx)
            self.view.setFocus(Qt.FocusReason.OtherFocusReason)
Ejemplo n.º 39
0
 def currentChanged(self, current, previous):
     QTreeView.currentChanged(self, current, previous)
     self.parent().current_changed(current, previous)
Ejemplo n.º 40
0
class ShortcutConfig(QWidget):  # {{{

    changed_signal = pyqtSignal()

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self._layout = l = QGridLayout()
        self.setLayout(self._layout)
        self.header = QLabel(_('Double click on any entry to change the'
            ' keyboard shortcuts associated with it'))
        l.addWidget(self.header, 0, 0, 1, 3)
        self.view = QTreeView(self)
        self.view.setAlternatingRowColors(True)
        self.view.setHeaderHidden(True)
        self.view.setAnimated(True)
        l.addWidget(self.view, 1, 0, 1, 3)
        self.delegate = Delegate()
        self.view.setItemDelegate(self.delegate)
        self.delegate.sizeHintChanged.connect(self.editor_opened,
                type=Qt.QueuedConnection)
        self.delegate.changed_signal.connect(self.changed_signal)
        self.search = SearchBox2(self)
        self.search.initialize('shortcuts_search_history',
                help_text=_('Search for a shortcut by name'))
        self.search.search.connect(self.find)
        l.addWidget(self.search, 2, 0, 1, 1)
        self.nb = QPushButton(QIcon(I('arrow-down.png')), _('&Next'), self)
        self.pb = QPushButton(QIcon(I('arrow-up.png')), _('&Previous'), self)
        self.nb.clicked.connect(self.find_next)
        self.pb.clicked.connect(self.find_previous)
        l.addWidget(self.nb, 2, 1, 1, 1)
        l.addWidget(self.pb, 2, 2, 1, 1)
        l.setColumnStretch(0, 100)

    def restore_defaults(self):
        self._model.restore_defaults()
        self.changed_signal.emit()

    def commit(self):
        if self.view.state() == self.view.EditingState:
            self.delegate.accept_changes()
        self._model.commit()

    def initialize(self, keyboard):
        self._model = ConfigModel(keyboard, parent=self)
        self.view.setModel(self._model)

    def editor_opened(self, index):
        self.view.scrollTo(index, self.view.EnsureVisible)

    @property
    def is_editing(self):
        return self.view.state() == self.view.EditingState

    def find(self, query):
        if not query:
            return
        try:
            idx = self._model.find(query)
        except ParseException:
            self.search.search_done(False)
            return
        self.search.search_done(True)
        if not idx.isValid():
            info_dialog(self, _('No matches'),
                    _('Could not find any shortcuts matching %s')%query,
                    show=True, show_copy_button=False)
            return
        self.highlight_index(idx)

    def highlight_index(self, idx):
        self.view.scrollTo(idx)
        self.view.selectionModel().select(idx,
                self.view.selectionModel().ClearAndSelect)
        self.view.setCurrentIndex(idx)
        self.view.setFocus(Qt.OtherFocusReason)

    def find_next(self, *args):
        idx = self.view.currentIndex()
        if not idx.isValid():
            idx = self._model.index(0, 0)
        idx = self._model.find_next(idx,
                unicode(self.search.currentText()))
        self.highlight_index(idx)

    def find_previous(self, *args):
        idx = self.view.currentIndex()
        if not idx.isValid():
            idx = self._model.index(0, 0)
        idx = self._model.find_next(idx,
            unicode(self.search.currentText()), backwards=True)
        self.highlight_index(idx)

    def highlight_group(self, group_name):
        idx = self.view.model().index_for_group(group_name)
        if idx is not None:
            self.view.expand(idx)
            self.view.scrollTo(idx, self.view.PositionAtTop)
            self.view.selectionModel().select(idx,
                    self.view.selectionModel().ClearAndSelect)
            self.view.setCurrentIndex(idx)
            self.view.setFocus(Qt.OtherFocusReason)
Ejemplo n.º 41
0
 def mouseReleaseEvent(self, event):
     # Swallow everything except leftButton so context menus work correctly
     if event.button() == Qt.LeftButton or self.in_drag_drop:
         QTreeView.mouseReleaseEvent(self, event)
         self.in_drag_drop = False
Ejemplo n.º 42
0
 def __init__(self, parent):
     QTreeView.__init__(self, parent)
     self.setAnimated(True)
     self.setHeaderHidden(True)
     self.setObjectName('recipes')
     self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
Ejemplo n.º 43
0
class Navigation(QWidget):
    """a navigation widget, 
    displaying all known projects and samples
    """
    changed_projects = pyqtSignal(str, str)
    changed_allele = pyqtSignal(str, int, str)
    change_view = pyqtSignal(int)
    refresh = pyqtSignal(str)
    
    def __init__(self, log, settings):
        self.log = log
        self.settings = settings
        super().__init__()
        self.init_UI()
        self.create_model()
        self.tree.expand(self.open_node)
        self.tree.clicked.connect(self.onClicked)
        
        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.customContextMenuRequested.connect(self.open_menu)
        
    def init_UI(self):
        """creates the UI
        """
        self.log.debug("Setting up Navigation area UI...")
        self.tree = QTreeView()
        self.tree.doubleClicked.connect(self.onDoubleClick)
        self.grid = QGridLayout()
        self.setLayout(self.grid)
        self.header_lbl = QLabel("Projects and Samples:", self)
        self.header_lbl.setStyleSheet(general.label_style_2nd)
        self.grid.addWidget(self.header_lbl, 0,0)
        
        self.grid.addWidget(self.tree, 1, 0)
        header = self.tree.header()
        header.hide()
        self.log.debug("\t=> Done!")
        
    def create_model(self):
        """creates or recreates the model
        """
        self.log.debug("Updating Navigation area...")
        root_node = Node("All")
        openNode = Node("Open", root_node)
        closedNode = Node("Closed", root_node)
        project_nodes = {}
        
        query = """select distinct sample_id_int, projects.project_name, project_status, allele_status, allele_nr 
        from projects left join alleles
            on projects.project_name = alleles.project_name 
        order by project_status desc, projects.project_name desc, sample_id_int
        """
        q = QtSql.QSqlQuery()
        q.exec_(query)
        while q.next():
            sample = q.value(0)
            project = q.value(1)
            pstatus = q.value(2)
            astatus = q.value(3)
            nr = q.value(4)
            try:
                pnode = project_nodes[project]
            except KeyError:
                if pstatus == "Closed":
                    topnode = closedNode
                else:
                    topnode = openNode
                pnode = Node(project, topnode, "Project")
                project_nodes[project] = pnode
            if sample:
                if nr != 1:
                    sample = "{} ({})".format(sample, nr)
                Node(sample, pnode, "Sample", astatus)
        
        self.model = NavigationModel(root_node)
        self.tree.setModel(self.model)
        
        self.open_node = self.model.index(0, 0, QModelIndex())
        self.closed_node = self.model.index(1, 0, QModelIndex())
        self.root_node = self.open_node.parent()
        self.log.debug("\t=> Done!")
        
    @pyqtSlot(str, str)
    def expand_project(self, project, status = None):
        """expands the node of the given project, 
        returns its index and parent-node's index 
        """
        self.log.debug("Expanding project {} ({})...".format(project, status))
        if not status in (None, "Open", "Closed"):
            return None, None
        myindex = self.open_node
        myparent_node = self.open_node
        if status == "Open":
            self.log.debug("Open")
            parent_node = self.open_node
            self.tree.expand(parent_node)
            self.tree.collapse(self.closed_node)
        elif status == "Closed":
            self.log.debug("Closed")
            parent_node = self.closed_node
            self.tree.expand(parent_node)
            self.tree.collapse(self.open_node)
        
        else: # figure out whether project is open or closed
            self.log.debug("Status unknown...")
            try:
                for i in range(self.model.rowCount(self.root_node)):
                    parent_node = self.model.index(i, 0, self.root_node)
                    status = self.model.data(parent_node, Qt.DisplayRole)
                    
                    for row in range(self.model.rowCount(parent_node)):
                        index = self.model.index(row, 0, parent_node)
                        myproj = self.model.data(index, Qt.DisplayRole)
                        if myproj == project:
                            myindex = index
                            myparent_node = parent_node 
                            self.tree.expand(myindex)
            except Exception as E:
                self.log.error(E)
                self.log.exception(E)
        self.select_project(project)
        self.log.debug("\t=> project found ({}) and successfully expanded".format(status))
        return myindex, myparent_node
    
    @pyqtSlot(QModelIndex)
    def onClicked(self, index):
        """emits signals when a project or sample is selected
        """
        data = self.model.data(index, Qt.DisplayRole)
        nodetype = self.model.nodeType(index)
        if nodetype == "Sample":
            if ("(") in data:
                data = data.split("(")
                sample = data[0].strip()
                nr = int(data[1].strip()[:-1])
            else:
                sample = data
                nr = 1
            project = self.model.data(self.model.parent(index), Qt.DisplayRole)
            self.changed_allele.emit(sample, nr, project)
            self.log.debug("Navigation emitted 'Allele changed to {} #{} (project {})'".format(sample, nr, project))
        elif nodetype == "Project":
            status = self.model.data(self.model.parent(index), Qt.DisplayRole)
            self.changed_projects.emit(data, status)
            self.log.debug("Navigation emitted 'Project changed to {}'".format(data))
    
    @pyqtSlot(QPoint)
    def open_menu(self, pos):
        """provides a context menu
        """
        index = self.tree.indexAt(pos)
        nodetype = self.model.nodeType(index)
        self.log.debug("Opening navigation menu...")
        if nodetype == "Project":
            menu = QMenu()
            open_project_act = menu.addAction("Open Project View")
            action = menu.exec_(self.tree.mapToGlobal(pos))
            
            if action == open_project_act:
                project = self.model.data(index, Qt.DisplayRole)
                status = self.model.data(self.model.parent(index), Qt.DisplayRole)
                self.changed_projects.emit(project, status)
                self.change_view.emit(3)
                self.log.debug("Navigation emitted changed_projects & change_view to ProjectView")
            
        elif nodetype == "Sample":
            menu = QMenu()
            open_sample_act = menu.addAction("Open Sample View")
            delete_sample_act = menu.addAction("Delete Allele (admin-only!)")
            action = menu.exec_(self.tree.mapToGlobal(pos))
            
            if action:
                sample_list = self.model.data(index, Qt.DisplayRole).split()
                sample = sample_list[0]
                if len(sample_list) > 1:
                    nr = int(sample_list[1][1:-1])
                else:
                    nr = 1
                project = self.model.data(self.model.parent(index), Qt.DisplayRole)
                status = self.model.data(self.model.parent(self.model.parent(index)), Qt.DisplayRole)
                if action == open_sample_act:
                    try:
                        self.changed_allele.emit(sample, nr, project)
                        self.change_view.emit(4)
                        self.log.debug("Navigation emitted changed_alleles & change_view to AlleleView")
                    except Exception as E:
                        self.log.exception(E)
                elif action == delete_sample_act:
                    self.log.info("Deleting {} #{} of project {}".format(sample, nr, project))
                    self.delete_sample(sample, nr, project, status)
    
    @pyqtSlot(QModelIndex)
    def onDoubleClick(self, index):
        """open SampleView or ProjectView
        """
        nodetype = self.model.nodeType(index)
        if nodetype == "Project":
            project = self.model.data(index, Qt.DisplayRole)
            status = self.model.data(self.model.parent(index), Qt.DisplayRole)
            self.changed_projects.emit(project, status)
            self.change_view.emit(3)
            self.log.debug("Navigation emitted changed_projects & change_view to ProjectView")
            
        elif nodetype == "Sample":
            sample_list = self.model.data(index, Qt.DisplayRole).split()
            sample = sample_list[0]
            if len(sample_list) > 1:
                nr = int(sample_list[1][1:-1])
            else:
                nr = 1
            project = self.model.data(self.model.parent(index), Qt.DisplayRole)
            status = self.model.data(self.model.parent(self.model.parent(index)), Qt.DisplayRole)
            self.changed_allele.emit(sample, nr, project)
            self.change_view.emit(4)
            self.log.debug("Navigation emitted changed_alleles & change_view to AlleleView")
                    
    @pyqtSlot(str)
    def select_project(self, project):
        """looks for <project> in the tree-model and selects it if found;
        selects it and returns its index 
        """
        for top_node in [self.open_node, self.closed_node]:
            index = self.model.findValue(top_node, project)
            if index.isValid():
                self.tree.setCurrentIndex(index)
                return index
        return QModelIndex()
        
    @pyqtSlot(str)
    def select_sample(self, project, sample, nr):
        """looks for <sample> in <project> in the tree-model and selects it if found;
        selects it and returns its index
        """
        pindex = self.select_project(project)
        if int(nr) > 1:
            sample = "{} ({})".format(sample, nr)
        index = self.model.findValue(pindex, sample)
        if index.isValid():
            self.tree.setCurrentIndex(index)
            return index       
        return QModelIndex()
    
    def delete_sample(self, sample, nr, project, status):
        """delete a sample from the database & file system
        """
        self.log.debug("Attempting to delete sample '{}' allele {} of project '{}' from database...".format(sample, nr, project))
        if self.settings["login"] == "admin":
            pass
        else:
            pwd, ok = QInputDialog.getText(self, "Enter Password", "Please provide password:"******"ichdarfdas":
                    pass
                else:
                    return
            else:
                return
        self.log.debug("Asking for confirmation before deleting allele...")
        reply = QMessageBox.question(self, 'Message',
            "Are you really sure you want to delete sample {} allele #{} from project {}?".format(sample, nr, project), QMessageBox.Yes | 
            QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            # delete from database:
            delete_q_alleles = "delete from alleles where sample_id_int = '{}' and allele_nr = {} and project_name = '{}'".format(sample, nr, project)
            success, _ = db_internal.execute_query(delete_q_alleles, 0, self.log, "Deleting sample {} allele #{} from ALLELES table".format(sample, nr), "Sample Deletion Error", self)
            if success:
                self.log.debug("\t=> Successfully deleted sample from table ALLELES")
            
            more_projects_query = "select project_name from alleles where sample_id_int = '{}'".format(sample)
            success, data = db_internal.execute_query(more_projects_query, 1, self.log, "Finding more rows with sample {} in ALLELES table".format(sample), "Sample Deletion Error", self)
            
            single_allele = False
            if success:
                if not data: # sample was only contained in this project and only had one allele
                    single_allele = True
                    delete_q_samples = "delete from SAMPLES where sample_id_int = '{}'".format(sample)
                    success, _ = db_internal.execute_query(delete_q_samples, 0, self.log, "Deleting sample {} from SAMPLES table".format(sample), "Sample Deletion Error", self)
                    if success:
                        self.log.debug("\t=> Successfully deleted sample from table SAMPLES")
                
                files_q = "select raw_file, fasta, blast_xml, ena_file, ena_response_file, ipd_submission_file from FILES where sample_id_int = '{}' and allele_nr = {}".format(sample, nr)
                success, files = db_internal.execute_query(files_q, 6, self.log, "Getting files of sample {} #{} from FILES table".format(sample, nr), "Sample Deletion Error", self)
                if success:
                    
                    delete_q_files = "delete from FILES where sample_id_int = '{}' and allele_nr = {}".format(sample, nr)
                    success, _ = db_internal.execute_query(delete_q_files, 0, self.log, "Deleting sample {} from FILES table".format(sample), "Sample Deletion Error", self)
                    if success:
                        self.log.debug("\t=> Successfully deleted sample from table FILES")
            
            # delete from disk space:
            self.log.debug("Attempting to delete sample {} allele #{} of project '{}' from file system...".format(sample, nr, project))
            sample_dir = os.path.join(self.settings["projects_dir"], project, sample)
            if files:
                for myfile in files[0]:
                    if myfile:
                        self.log.debug("\tDeleting {}...".format(myfile))
                        try:
                            os.remove(os.path.join(sample_dir, myfile))
                        except Exception:
                            self.log.debug("\t\t=> Could not delete")
            
            if single_allele:
                self.log.debug("\tDeleting sample dir {}...".format(sample_dir))
                os.removedirs(sample_dir)
            self.log.debug("=> Sample {} #{} of project {} successfully deleted from database and file system".format(sample, nr, project))
            self.refresh.emit(project)
            self.changed_projects.emit(project, status)