Пример #1
0
 def _init_models(self):
     self._hierarchy_model = QStandardItemModel()
     self._hierarchy_model.setColumnCount(2)
     self._hierarchy_model.setHorizontalHeaderLabels(['class', 'dn'])
     self._details_model = QStandardItemModel()
     self._details_model.setColumnCount(2)
     self._details_model.setHorizontalHeaderLabels(['Property', 'Value'])
Пример #2
0
    def __init__(self, app, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.app = app
        self.closed = False
        self.sort_order = None
        self.ui = Ui_List()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())

        self.notebooksModel = QStandardItemModel()
        self.ui.notebooksList.setModel(self.notebooksModel)
        self.ui.notebooksList.selection.connect(self.selection_changed)
        self.ui.notebooksList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notebooksList.customContextMenuRequested.connect(
            self.notebook_context_menu)

        self.notesModel = QStandardItemModel()
        self.notesModel.setHorizontalHeaderLabels(
            [self.tr('Title'), self.tr('Last Updated')])

        self.ui.notesList.setModel(self.notesModel)
        self.ui.notesList.doubleClicked.connect(self.note_dblclicked)
        self.ui.notesList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notesList.customContextMenuRequested.connect(
            self.note_context_menu)
        self.ui.notesList.header().sortIndicatorChanged.connect(
            self.sort_order_updated)

        self.ui.newNotebookBtn.setIcon(QIcon.fromTheme('folder-new'))
        self.ui.newNotebookBtn.clicked.connect(self.new_notebook)

        self.ui.newNoteBtn.setIcon(QIcon.fromTheme('document-new'))
        self.ui.newNoteBtn.clicked.connect(self.new_note)
Пример #3
0
    def __init__(self):
        QStandardItemModel.__init__(self)

        self.item = self.invisibleRootItem()
        self.item.setEnabled(True)

        self.__projectGitCollection = ProjectGitCollection()
Пример #4
0
    def _createCompleterModel(self, completionPrefix):
        """
        Creates a QStandardModel that holds the suggestion from the completion
        models for the QCompleter

        :param completionPrefix:
        """
        # build the completion model
        cc_model = QStandardItemModel()
        cptSuggestion = 0
        displayedTexts = []
        self.__tooltips.clear()
        for model in self._models:
            for s in model.suggestions:
                # skip redundant completion
                if s.display != completionPrefix and \
                        not s.display in displayedTexts:
                    displayedTexts.append(s.display)
                    items = []
                    item = QStandardItem()
                    items.append(item)
                    item.setData(s.display, Qt.DisplayRole)
                    if s.description is not None:
                        self.__tooltips[s.display] = s.description
                    if s.decoration is not None:
                        item.setData(QIcon(s.decoration), Qt.DecorationRole)
                    cc_model.appendRow(items)
                    cptSuggestion += 1
            # do we need to use more completion model?
            if cptSuggestion >= self.minSuggestions:
                break  # enough suggestions
        return cc_model, cptSuggestion
Пример #5
0
    def __init__(self, app, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.app = app
        self.closed = False
        self.sort_order = None
        self.ui = Ui_List()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())

        self.notebooksModel = QStandardItemModel()
        self.ui.notebooksList.setModel(self.notebooksModel)
        self.ui.notebooksList.selection.connect(self.selection_changed)
        self.ui.notebooksList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notebooksList.customContextMenuRequested.connect(self.notebook_context_menu)

        self.notesModel = QStandardItemModel()
        self.notesModel.setHorizontalHeaderLabels(
            [self.tr('Title'), self.tr('Last Updated')])

        self.ui.notesList.setModel(self.notesModel)
        self.ui.notesList.doubleClicked.connect(self.note_dblclicked)
        self.ui.notesList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notesList.customContextMenuRequested.connect(self.note_context_menu)
        self.ui.notesList.header().sortIndicatorChanged.connect(self.sort_order_updated)

        self.ui.newNotebookBtn.setIcon(QIcon.fromTheme('folder-new'))
        self.ui.newNotebookBtn.clicked.connect(self.new_notebook)

        self.ui.newNoteBtn.setIcon(QIcon.fromTheme('document-new'))
        self.ui.newNoteBtn.clicked.connect(self.new_note)

        self.ui.newNoteBtn.setShortcut(QKeySequence(self.tr('Ctrl+n')))
        self.ui.newNotebookBtn.setShortcut(QKeySequence(self.tr('Ctrl+Shift+n')))
        QShortcut(QKeySequence(self.tr('Ctrl+q')), self, self.close)
Пример #6
0
    def __init__(self, parent=None):
        super(TemplateSelectDialog, self).__init__(parent)

        self.setWindowTitle(_("Select a template"))

        self.template_id = []

        self.model = QStandardItemModel()
        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.verticalHeader().setVisible(False)
        self.view.horizontalHeader().setVisible(False)
        self.view.setMinimumSize(500, 200)
        self.view.setShowGrid(True)
        self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.view.setSelectionBehavior(QAbstractItemView.SelectRows)

        l = QVBoxLayout()

        l.addWidget(QLabel(_("Please select one or more template.")))
        self.view.doubleClicked.connect(self._doubleClicked)

        l.addWidget(QLabel(u"<h3>{}</h3>".format(_("Documents Templates"))))
        l.addWidget(self.view)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton(QDialogButtonBox.StandardButton.Cancel)
        self.buttons.addButton(QDialogButtonBox.Ok)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

        l.addWidget(self.buttons)

        self.setLayout(l)
Пример #7
0
    def __init__(self, parent):
        super(FilteredTable, self).__init__(parent)

        self.model = QStandardItemModel(600, 600)
        for i in range(self.model.rowCount()):
            for j in range(self.model.columnCount()):
                self.model.setData(self.model.index(i, j), str(i * j),
                                   Qt.DisplayRole)

        self.m = FilteringModel(self)
        self.m.setSourceModel(self.model)

        d = ['a'] * 300 + ['b'] * 200 + ['c'] * 99 + ['d']
        self.m.setIndexData(d)

        t = QTableView(self)
        t.setModel(self.m)

        self.line_in = QLineEdit(self)
        self.line_in.textChanged.connect(self.m.setFilterFixedString)

        l = QVBoxLayout()
        l.addWidget(self.line_in)
        l.addWidget(t)
        self.setLayout(l)
Пример #8
0
 def _init_tags(self):
     self._current_tag = None
     self.tagsModel = QStandardItemModel()
     self.ui.tagsList.setModel(self.tagsModel)
     self.ui.tagsList.selection.connect(self.tag_selection_changed)
     self.ui.tagsList.setContextMenuPolicy(Qt.CustomContextMenu)
     self.ui.tagsList.customContextMenuRequested.connect(
         self.tag_context_menu)
Пример #9
0
    def __init__(self, lookup):
        super().__init__()

        self._lookup = lookup
        self._model = QStandardItemModel()  # (4, 4)

        self.initUI()
        self.initDB()
Пример #10
0
    def __init__(self,enumeration,parent=None):
        StandardTableDelegate.__init__(self,parent)

        items = enumeration.symbols()

        self.model = QStandardItemModel(len(items), 1)
        for i in range(len(items)):
            self.model.setData( self.model.index(i,0), items[i].description, Qt.DisplayRole)
            self.model.setData( self.model.index(i,0), items[i], Qt.UserRole)
Пример #11
0
 def dropEvent(self, e):
     """Accept drop events."""
     model = QStandardItemModel()
     model.dropMimeData(
         e.mimeData(), Qt.CopyAction, 0, 0, QModelIndex())
     name = model.item(0).text()
     item = None
     if name in ['And', 'Or', 'Nand', 'Nor', 'Not', 'Xor', 'Xnor']:
         item = CircuitItem(
             getattr(engine.gates, name + 'Gate')(None, self.mainCircuit))
     elif name == 'RSFlipFlop':
         item = CircuitItem(RSFlipFlop(None, self.mainCircuit))
     elif name == 'JKFlipFlop':
         item = CircuitItem(JKFlipFlop(None, self.mainCircuit))
     elif name == self.str_I:
         item = PlugItem(Plug(True, None, self.mainCircuit))
     elif name == self.str_O:
         item = PlugItem(Plug(False, None, self.mainCircuit))
     elif name == self.str_Clock:
         if not self.clockPlug:
             self.clockPlug = Clock(self.mainCircuit)
             self.clockPlug.clkThread.set_extern(self.clockUpdate)
             item = PlugItem(self.clockPlug)
         else:
             self.write(self.str_onlyOneClock)
     elif model.item(0, 1).text() == 'user':
         c = Circuit(None, self.mainCircuit)
         f = open(filePath('user/') + name + '.crc', 'rb')
         children = pickle.load(f)
         f.close()
         for child in children:
             if isinstance(child[0], Plug):
                 child[0].owner = c
                 if child[0].isInput:
                     c.inputList.append(child[0])
                 else:
                     c.outputList.append(child[0])
             elif isinstance(child[0], Circuit):
                 child[0].owner = c
                 c.circuitList.append(child[0])
         c.category = name
         item = CircuitItem(c)
     if item:
         # Fixes the default behaviour of centering the first
         # item added to scene.
         if not len(self.scene().items()):
             self.scene().setSceneRect(0, 0, 1, 1)
         else:
             self.scene().setSceneRect(0, 0, 0, 0)
         self.scene().addItem(item)
         item.setupPaint()
         item.setPos(
             closestGridPoint(item.mapFromScene(self.mapToScene(e.pos()))))
         for i in self.scene().selectedItems():
             i.setSelected(False)
         item.setSelected(True)
         self.timer.start()
Пример #12
0
def make_header_model(titles,headers=None):
    if headers is None:
        headers = QStandardItemModel(1, len(titles))

    i = 0
    for p in titles:
        headers.setHeaderData(i, Qt.Orientation.Horizontal, p)
        i = i + 1
    return headers
    def _on_level_selected_changed(self, index):
        level_name = self.mClassList.itemData(index)
        level = self.levels_dict[level_name]
        model = QStandardItemModel()
        for verb in level.verbs_list:
            item = QStandardItem(verb.base_verbal)
            item.setData(verb.base_verbal)
            model.appendRow(item)

        self.mVerbsList.setModel(model)
Пример #14
0
    def __init__(self,parent=None):
        super(PriorityCombo, self).__init__(parent)

        self.model = QStandardItemModel(len(priority_stars()), 1)
        for i,stars in priority_stars():
            ndx = self.model.index( i-1, 0)
            self.model.setData( ndx, stars, Qt.DisplayRole)
            self.model.setData( ndx, i, Qt.UserRole)

        self.setModel( self.model)
Пример #15
0
    def __init__(self,parent):
        global dao
        super(FindOrderDialog,self).__init__(parent)

        title = _("Find order")
        self.setWindowTitle(title)
        top_layout = QVBoxLayout()
        self.title_widget = TitleWidget(title,self)
        top_layout.addWidget(self.title_widget)

        hlayout = QHBoxLayout()
        hlayout.addWidget(QLabel(_("Search")))
        self.search_criteria = QLineEdit()
        self.search_criteria.setObjectName("search_criteria")
        hlayout.addWidget(self.search_criteria)
        top_layout.addLayout(hlayout)



        self.search_results_view = QTableView()

        self.headers_view = QHeaderView(Qt.Orientation.Horizontal)
        self.header_model = make_header_model([_("Preorder Nr"),_("Order Nr"),_("Customer Nr"),_("Customer"),_("Order Part")])
        self.headers_view.setModel(self.header_model) # qt's doc : The view does *not* take ownership (bt there's something with the selecion mode

        self.search_results_model = QStandardItemModel()
        self.search_results_view.setModel(self.search_results_model)

        self.search_results_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.search_results_view.setHorizontalHeader(self.headers_view)
        self.search_results_view.verticalHeader().hide()
        # self.search_results_view.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
        self.search_results_view.horizontalHeader().setResizeMode(3, QHeaderView.Stretch)
        self.search_results_view.horizontalHeader().setResizeMode(4, QHeaderView.Stretch)

        self.search_results_view.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton( QDialogButtonBox.StandardButton.Cancel)
        self.buttons.addButton( QDialogButtonBox.Ok)
        self.buttons.button(QDialogButtonBox.Ok).setObjectName("go_search")

        top_layout.addWidget(self.search_results_view)
        top_layout.setStretch(2,1000)
        top_layout.addWidget(self.buttons)
        self.setLayout(top_layout)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.search_results_view.activated.connect(self.row_activated)
        self.search_criteria.returnPressed.connect(self.search_criteria_submitted)

        self.setMinimumSize(800,640)
Пример #16
0
    def __init__(self, enumeration, parent=None):
        StandardTableDelegate.__init__(self, parent)

        assert issubclass(enumeration, enum.Enum)

        # We expect : symbol = description (short), description (long)
        self.model = QStandardItemModel(len(enumeration), 1)
        i = 0
        for item in enumeration:
            self.model.setData(self.model.index(i, 0), item.value,
                               Qt.DisplayRole)
            self.model.setData(self.model.index(i, 0), item, Qt.UserRole)
            i += 1
Пример #17
0
    def _init_notes(self):
        self._current_note = None
        self.notesModel = QStandardItemModel()
        self.notesModel.setHorizontalHeaderLabels(
            [self.tr('Title'), self.tr('Last Updated')])

        self.ui.notesList.setModel(self.notesModel)
        self.ui.notesList.selection.connect(self.note_selection_changed)
        self.ui.notesList.doubleClicked.connect(self.note_dblclicked)
        self.ui.notesList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notesList.customContextMenuRequested.connect(
            self.note_context_menu)
        self.ui.notesList.header().sortIndicatorChanged.connect(
            self.sort_order_updated)
Пример #18
0
    def testRefCount(self):
        model = QStandardItemModel(5, 5)
        items = []
        for r in range(5):
            row = []
            for c in range(5):
                row.append(QStandardItem("%d,%d" % (r,c)) )
                self.assertEqual(sys.getrefcount(row[c]), 2)

            model.insertRow(r, row)

            for c in range(5):
                ref_after = sys.getrefcount(row[c])
                # check if the ref count was incremented after insertRow
                self.assertEqual(ref_after, 3)

            items.append(row)
            row = None

        for r in range(3):
            my_row = model.takeRow(0)
            my_row = None
            for c in range(5):
                # only rest 1 reference
                self.assertEqual(sys.getrefcount(items[r][c]), 2)

        my_i = model.item(0,0)
        # ref(my_i) + parent_ref + items list ref
        self.assertEqual(sys.getrefcount(my_i), 4)

        model.clear()
        # ref(my_i)
        self.assertEqual(sys.getrefcount(my_i), 3)
Пример #19
0
class PriorityCombo(QComboBox):
    def __init__(self,parent=None):
        super(PriorityCombo, self).__init__(parent)

        self.model = QStandardItemModel(len(priority_stars()), 1)
        for i,stars in priority_stars():
            ndx = self.model.index( i-1, 0)
            self.model.setData( ndx, stars, Qt.DisplayRole)
            self.model.setData( ndx, i, Qt.UserRole)

        self.setModel( self.model)

    def current_priority(self):
        return self.currentIndex().data(Qt.UserRole)
Пример #20
0
class QStandardItemModelTest(UsesQApplication):

    def setUp(self):
       super(QStandardItemModelTest, self).setUp()
       self.window = QWidget()
       self.model = QStandardItemModel(0, 3, self.window)

    def tearDown(self):
       del self.window
       del self.model
       super(QStandardItemModelTest, self).tearDown()

    def testInsertRow(self):
        # bug #227
        self.model.insertRow(0)
Пример #21
0
 def testLen(self):
     model = QStandardItemModel(2, 2)
     model.insertRow(0)
     model.insertRow(1)
     model.insertColumn(0)
     model.insertColumn(1)
     selection = QItemSelection(model.index(0, 0), model.index(1, 1))
     self.assertEqual(len(selection), 1)
Пример #22
0
    def __init__(self, parent):
        super(QuickOrderViewWidget, self).__init__("Quick view", None, parent)

        self._table_model = QStandardItemModel(1, 2, None)
        self.table_view = QTableView(self)
        self.table_view.setModel(self._table_model)
        self.layout().addWidget(self.table_view)

        self._table_model.setHorizontalHeaderLabels(
            ['Part Nr.', 'Description'])

        self.table_view.verticalHeader().hide()
        headers_view = self.table_view.horizontalHeader()
        headers_view.setResizeMode(0, QHeaderView.ResizeToContents)
        headers_view.setResizeMode(1, QHeaderView.Stretch)
Пример #23
0
 def __init__(self):
     self.tree = QtGui.QTreeView()
     self.keys = {}
     self.data = None
     self.model = QStandardItemModel()
     self.tree.setHeaderHidden(True)
     self.brushConflictInChild = QtGui.QBrush(QtGui.QColor(255, 136, 139))
     self.brushConflictInChild.setStyle(QtCore.Qt.SolidPattern)
     self.brushConflictInItem = QtGui.QBrush(QtGui.QColor(255, 0, 0))
     self.brushConflictInItem.setStyle(Qt.SolidPattern)
     self.brushChangedItem = QtGui.QBrush(QtGui.QColor(249, 233, 170))
     self.brushChangedItem.setStyle(Qt.SolidPattern)
     self.brushAddedItem = QtGui.QBrush(QtGui.QColor(221, 252, 199))
     self.brushAddedItem.setStyle(Qt.SolidPattern)
     self.whiteBrush = QtGui.QBrush(QtGui.QColor(177, 177, 177))
     self.whiteBrush.setStyle(Qt.SolidPattern)
Пример #24
0
 def _init_tags(self):
     self._current_tag = None
     self.tagsModel = QStandardItemModel()
     self.ui.tagsList.setModel(self.tagsModel)
     self.ui.tagsList.selection.connect(self.tag_selection_changed)
     self.ui.tagsList.setContextMenuPolicy(Qt.CustomContextMenu)
     self.ui.tagsList.customContextMenuRequested.connect(self.tag_context_menu)
Пример #25
0
    def __init__(self):
        super(TreeviewWidgetSelectProve, self).__init__()
        ui_file_path = os.path.join(
            '/home/n130s/link/ROS/groovy_quantal/catkin_ws/src/rqt_prove',
            'resource', 'treeview_2.ui')

        loader = QUiLoader(self)
        ui_file = QFile(ui_file_path)
        self._widget_top = loader.load(ui_file, self)

        self._std_model = QStandardItemModel()
        self._rootitem = self._std_model.invisibleRootItem()

        item_r_1 = QStandardItem("r1")

        self._rootitem.appendRow(item_r_1)
        # self._rootitem.appendRow(item_r_2)
        print('_rootitem index={}'.format(self._rootitem.index()))

        self._treeview = self._widget_top.findChild(QTreeView, '_treeview')
        self._treeview.setModel(self._std_model)
        self.selectionModel = self._widget_top._treeview.selectionModel()

        print('del/sel?\tde/sel index\tde/sel.row\tde/sel.dat\tparent\tinternal id')
        self._widget_top.show()
Пример #26
0
class QuickOrderViewWidget(SubFrame):
    def __init__(self, parent):
        super(QuickOrderViewWidget, self).__init__("Quick view", None, parent)

        self._table_model = QStandardItemModel(1, 2, None)
        self.table_view = QTableView(self)
        self.table_view.setModel(self._table_model)
        self.layout().addWidget(self.table_view)

        self._table_model.setHorizontalHeaderLabels(
            ['Part Nr.', 'Description'])

        self.table_view.verticalHeader().hide()
        headers_view = self.table_view.horizontalHeader()
        headers_view.setResizeMode(0, QHeaderView.ResizeToContents)
        headers_view.setResizeMode(1, QHeaderView.Stretch)

    def selected_order(self, cur, prev):
        if cur.isValid():
            order_id = cur.model().index(cur.row(), 0).data(Qt.UserRole)

            self._table_model.removeRows(0, self._table_model.rowCount())
            row = 0
            for label, description in dao.order_dao.load_quick_view(order_id):
                self._table_model.appendRow(
                    [QStandardItem(label),
                     QStandardItem(description)])
Пример #27
0
    def testRefCount(self):
        model = QStandardItemModel(5, 5)
        items = []
        for r in range(5):
            row = []
            for c in range(5):
                row.append(QStandardItem("%d,%d" % (r,c)) )
                self.assertEqual(sys.getrefcount(row[c]), 2)

            model.insertRow(r, row)

            for c in range(5):
                ref_after = sys.getrefcount(row[c])
                # check if the ref count was incremented after insertRow
                self.assertEqual(ref_after, 3)

            items.append(row)
            row = None

        for r in range(3):
            my_row = model.takeRow(0)
            my_row = None
            for c in range(5):
                # only rest 1 reference
                self.assertEqual(sys.getrefcount(items[r][c]), 2)

        my_i = model.item(0,0)
        # ref(my_i) + parent_ref + items list ref
        self.assertEqual(sys.getrefcount(my_i), 4)

        model.clear()
        # ref(my_i)
        self.assertEqual(sys.getrefcount(my_i), 3)
Пример #28
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.mainwindow = Ui_MainWindow()
        self.mainwindow.setupUi(self)

        it1 = Category(title='it1')
        it2 = Page('it2', 'This is it2\'s content')
        it3 = Page('it3', 'This is it3\'s content')
        it1.setChild(it1.rowCount(), it2)
        it1.setChild(it1.rowCount(), it3)
        model = QStandardItemModel()
        model.appendRow(it1)
        tv = self.mainwindow.treeView
        tv.setModel(model)
        tv.setRootIsDecorated(True)
        tv.setSelectionMode(QAbstractItemView.SingleSelection)
        tv.setSelectionBehavior(QAbstractItemView.SelectItems)
        tv.clicked.connect(self.printData)
Пример #29
0
 def testLen(self):
     model = QStandardItemModel(2, 2)
     model.insertRow(0)
     model.insertRow(1)
     model.insertColumn(0)
     model.insertColumn(1)
     selection = QItemSelection(model.index(0,0), model.index(1,1))
     self.assertEqual(len(selection), 1)
Пример #30
0
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     self.setupUi()
     # setup a sample model
     self.model = QStandardItemModel(self)
     self.model.setHorizontalHeaderLabels(self.COLUMNS)
     for row, item in enumerate(self.ITEMS):
         for column, cell in enumerate(item):
             self.model.setItem(row, column, QStandardItem(cell))
     self.proxy = QSortFilterProxyModel(self)
     self.proxy.setSourceModel(self.model)
     # filter all columns (use 0, 1, etc. to only filter by a specific column)
     self.proxy.setFilterKeyColumn(-1)
     # filter text case insensitively
     self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
     self.view.setModel(self.proxy)
     for column, _ in enumerate(self.COLUMNS):
         self.view.resizeColumnToContents(column)
     self.searchBox.textChanged.connect(self.updateFilter)
Пример #31
0
class MainWindow(QMainWindow):

    COLUMNS = ['Name', 'Comment']

    ITEMS = [
        ('Ford', "Don't panic"),
        ('Marvin', "I'm feeling so depressed")
    ]

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi()
        # setup a sample model
        self.model = QStandardItemModel(self)
        self.model.setHorizontalHeaderLabels(self.COLUMNS)
        for row, item in enumerate(self.ITEMS):
            for column, cell in enumerate(item):
                self.model.setItem(row, column, QStandardItem(cell))
        self.proxy = QSortFilterProxyModel(self)
        self.proxy.setSourceModel(self.model)
        # filter all columns (use 0, 1, etc. to only filter by a specific column)
        self.proxy.setFilterKeyColumn(-1)
        # filter text case insensitively
        self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.view.setModel(self.proxy)
        for column, _ in enumerate(self.COLUMNS):
            self.view.resizeColumnToContents(column)
        self.searchBox.textChanged.connect(self.updateFilter)

    def updateFilter(self, text):
        self.proxy.setFilterFixedString(text)

    def setupUi(self):
        centralWidget = QWidget(self)
        centralWidget.setLayout(QVBoxLayout(centralWidget))
        self.view = QTableView(centralWidget)
        self.view.setSortingEnabled(True)
        centralWidget.layout().addWidget(self.view)
        self.searchBox = QLineEdit(centralWidget)
        centralWidget.layout().addWidget(self.searchBox)
        self.setCentralWidget(centralWidget)
        self.searchBox.setFocus()
Пример #32
0
	def doLayout(self):
		central_window = QWidget(self)
		vlayout = QVBoxLayout(central_window)

		self.FileListView = QListView(self)
		self.SafeModeCheckbox = QCheckBox(self.tr('Safeモードで読み込み(エラーが出る場合に使用ください。改行やページ番号等崩れる場合があります。)'), self)
		convert_button = QPushButton(self.tr('変換'), central_window)

		vlayout.addWidget(QLabel(self.tr('ドラッグ&ドロップでファイルを読み込みます'), self))
		vlayout.addWidget(self.FileListView)
		vlayout.addWidget(self.SafeModeCheckbox)
		vlayout.addWidget(convert_button)
		convert_button.clicked.connect(self.onConvert)

		self.FileListModel = QStandardItemModel(self)
		self.FileListModel.setHorizontalHeaderLabels([self.tr('ファイル名')])
		self.FileListView.setModel(self.FileListModel)
		self.FileListView.setAcceptDrops(True)

		self.setCentralWidget(central_window)
Пример #33
0
    def __init__(self, strategy):
        QListView.__init__(self)

        self.item_strat = strategy

        self.itemmodel = QStandardItemModel()
        self.proxymodel = QSortFilterProxyModel()
        self.proxymodel.setSourceModel(self.itemmodel)
        self.proxymodel.setDynamicSortFilter(True)
        self.setModel(self.proxymodel)
        self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
Пример #34
0
class LibraryListView(QListView):
    def __init__(self, strategy):
        QListView.__init__(self)

        self.item_strat = strategy

        self.itemmodel = QStandardItemModel()
        self.proxymodel = QSortFilterProxyModel()
        self.proxymodel.setSourceModel(self.itemmodel)
        self.proxymodel.setDynamicSortFilter(True)
        self.setModel(self.proxymodel)
        self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)

    def add(self, obj):
        item = self.item_strat.get_item(obj)
        self.itemmodel.appendRow(item)
        return item

    def filter(self, field, value):
        self.proxymodel.setFilterRole(field)
        self.proxymodel.setFilterFixedString(value)
Пример #35
0
class QStandardItemModelTest(UsesQApplication):
    def setUp(self):
        super(QStandardItemModelTest, self).setUp()
        self.window = QWidget()
        self.model = QStandardItemModel(0, 3, self.window)

    def tearDown(self):
        del self.window
        del self.model
        super(QStandardItemModelTest, self).tearDown()

    def testInsertRow(self):
        # bug #227
        self.model.insertRow(0)

    def testClear(self):

        model = QStandardItemModel()
        root = model.invisibleRootItem()
        model.clear()
        self.assertFalse(shiboken.isValid(root))
class QStandardItemModelTest(UsesQApplication):
    def setUp(self):
        super(QStandardItemModelTest, self).setUp()
        self.window = QWidget()
        self.model = QStandardItemModel(0, 3, self.window)

    def tearDown(self):
        del self.window
        del self.model
        super(QStandardItemModelTest, self).tearDown()

    def testInsertRow(self):
        # bug #227
        self.model.insertRow(0)

    def testClear(self):

        model = QStandardItemModel()
        root = model.invisibleRootItem()
        model.clear()
        self.assertFalse(shiboken.isValid(root))
Пример #37
0
    def __init__(self, strategy):
        QListView.__init__(self)
        self.ctrl = None
        self.item_strat = strategy

        self.itemmodel = QStandardItemModel()
        self.proxymodel = LuneSortFilterProxyModel()
        self.proxymodel.setSourceModel(self.itemmodel)
        self.setModel(self.proxymodel)
        self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.proxymodel.setSortCaseSensitivity(QtCore.Qt.CaseSensitivity.CaseInsensitive)
        self.proxymodel.sort(0)
Пример #38
0
    def _init_notes(self):
        self._current_note = None
        self.notesModel = QStandardItemModel()
        self.notesModel.setHorizontalHeaderLabels(
            [self.tr('Title'), self.tr('Last Updated')])

        self.ui.notesList.setModel(self.notesModel)
        self.ui.notesList.selection.connect(self.note_selection_changed)
        self.ui.notesList.doubleClicked.connect(self.note_dblclicked)
        self.ui.notesList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notesList.customContextMenuRequested.connect(self.note_context_menu)
        self.ui.notesList.header().sortIndicatorChanged.connect(self.sort_order_updated)
Пример #39
0
class MainWindow(QMainWindow):

    COLUMNS = ['Name', 'Comment']

    ITEMS = [('Ford', "Don't panic"), ('Marvin', "I'm feeling so depressed")]

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi()
        # setup a sample model
        self.model = QStandardItemModel(self)
        self.model.setHorizontalHeaderLabels(self.COLUMNS)
        for row, item in enumerate(self.ITEMS):
            for column, cell in enumerate(item):
                self.model.setItem(row, column, QStandardItem(cell))
        self.proxy = QSortFilterProxyModel(self)
        self.proxy.setSourceModel(self.model)
        # filter all columns (use 0, 1, etc. to only filter by a specific column)
        self.proxy.setFilterKeyColumn(-1)
        # filter text case insensitively
        self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.view.setModel(self.proxy)
        for column, _ in enumerate(self.COLUMNS):
            self.view.resizeColumnToContents(column)
        self.searchBox.textChanged.connect(self.updateFilter)

    def updateFilter(self, text):
        self.proxy.setFilterFixedString(text)

    def setupUi(self):
        centralWidget = QWidget(self)
        centralWidget.setLayout(QVBoxLayout(centralWidget))
        self.view = QTableView(centralWidget)
        self.view.setSortingEnabled(True)
        centralWidget.layout().addWidget(self.view)
        self.searchBox = QLineEdit(centralWidget)
        centralWidget.layout().addWidget(self.searchBox)
        self.setCentralWidget(centralWidget)
        self.searchBox.setFocus()
Пример #40
0
    def __init__(self, repoDict):
        QStandardItemModel.__init__(self)

        self.item = self.invisibleRootItem()
        self.item.setEnabled(True)

        self.__repoDict = repoDict
        self.__profileList = self.__repoDict.keys()
        self.__profileList.sort()

        if "general" in self.__profileList:
            self.__selectedRepo = "general"
        else:
            if len(self.__profileList) > 0:
                self.__selectedRepo = self.__profileList[0]

        for p in self.__profileList:
            profile = QStandardItem(p)
            for rName, rUrl in self.__repoDict[p]:
                st = rName + " (" + rUrl + ")"
                profile.appendRow(QStandardItem(st))
            self.item.appendRow(profile)
Пример #41
0
    def __init__(self, parent):
        super(WeekViewWidget, self).__init__("Week", None, parent)

        self._table_model = QStandardItemModel(1, 2, None)
        self._table_model.setHorizontalHeaderLabels(
            [_("# Ord."), _("Customer")])

        self.table_view = LeftRightTableView(self)
        self.table_view.setModel(self._table_model)
        self.table_view.verticalHeader().hide()
        self.table_view.setAlternatingRowColors(True)
        self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_view.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table_view.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.table_view.horizontalHeader().setResizeMode(
            0, QHeaderView.ResizeToContents)
        self.table_view.horizontalHeader().setStretchLastSection(True)

        self.preorder_brush = QBrush(QColor(255, 255, 128))
        self.completed_order_brush = QBrush(QColor(128, 255, 128))

        self.layout().addWidget(self.table_view)
Пример #42
0
class LibraryListView(QListView):
    def __init__(self, strategy):
        QListView.__init__(self)
        self.ctrl = None
        self.item_strat = strategy

        self.itemmodel = QStandardItemModel()
        self.proxymodel = LuneSortFilterProxyModel()
        self.proxymodel.setSourceModel(self.itemmodel)
        self.setModel(self.proxymodel)
        self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.proxymodel.setSortCaseSensitivity(QtCore.Qt.CaseSensitivity.CaseInsensitive)
        self.proxymodel.sort(0)

    def add(self, obj):
        item = self.item_strat.get_item(obj)
        self.itemmodel.appendRow(item)
        if self.ctrl:
            self.ctrl.update()

        return item

    def remove(self, obj):
        index = self.model().sourceModel().indexFromItem(obj.item)
        self.model().sourceModel().removeRow(index.row())

    def filter(self, field, value):
        self.proxymodel.setFilterRole(field)
        self.proxymodel.setFilterFixedString(value)
        if self.ctrl:
            self.ctrl.update()

    def sort(self, sort):
        self.ctrl.set_sort(sort)

    def set_ctrl(self, ctrl):
        self.ctrl = ctrl
Пример #43
0
    def makeTopLayout(self):
        """Make a QHBoxLayout containing clickable buttons like 'Pause', and filters ('errors', 'warnings'...)"""
        top = QtGui.QHBoxLayout()
        top.setAlignment( Qt.AlignLeft )

        btn = QtGui.QPushButton("Pause")
        btn.setCheckable(True)
        btn.pressed.connect( self.toggle_paused )
        top.addWidget( btn )

        btn = QtGui.QPushButton("Run")
        btn.pressed.connect( self.run_yaml )
        top.addWidget( btn )

        btn = QtGui.QPushButton("Stop")
        btn.pressed.connect( self.stop_yaml )
        top.addWidget( btn )

        top.addWidget( QtGui.QLabel("Filters:") )
        
        model = QStandardItemModel()
        combo = QtGui.QComboBox()
        combo.setModel(model)
        self.filter_model = model

        ix = 0
        for label,str in config.FILTERS:
            item = QStandardItem(label)
            model.appendRow(item)
            combo.setItemData(ix, str)
            ix += 1

        combo.currentIndexChanged.connect( lambda ix, combo=combo : self.filter_combo_changed(ix, combo) )
        top.addWidget(combo)
        
        return top
Пример #44
0
    def testOperators(self):
        model = QStandardItemModel()
        for i in range(100):
            model.appendRow(QStandardItem("Item: %d"%i))

        first = model.index(0, 0)
        second = model.index(10, 0)
        third = model.index(20, 0)
        fourth = model.index(30, 0)

        sel = QItemSelection(first, second)
        sel2 = QItemSelection()
        sel2.select(third, fourth)

        sel3 = sel + sel2 #check operator +
        self.assertEqual(len(sel3), 2)
        sel4 = sel
        sel4 += sel2 #check operator +=
        self.assertEqual(len(sel4), 2)
        self.assertEqual(sel4, sel3)
Пример #45
0
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     self.setupUi()
     # setup a sample model
     self.model = QStandardItemModel(self)
     self.model.setHorizontalHeaderLabels(self.COLUMNS)
     for row, item in enumerate(self.ITEMS):
         for column, cell in enumerate(item):
             self.model.setItem(row, column, QStandardItem(cell))
     self.proxy = QSortFilterProxyModel(self)
     self.proxy.setSourceModel(self.model)
     # filter all columns (use 0, 1, etc. to only filter by a specific column)
     self.proxy.setFilterKeyColumn(-1)
     # filter text case insensitively
     self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
     self.view.setModel(self.proxy)
     for column, _ in enumerate(self.COLUMNS):
         self.view.resizeColumnToContents(column)
     self.searchBox.textChanged.connect(self.updateFilter)
    def __init__(self):
        super(LoaduiProve, self).__init__()
        print ('QT_BINDING=' + QT_BINDING)
        ui_file_path = os.path.join(
            '/home/n130s/link/ROS/groovy_quantal/catkin_ws/src/rqt_prove',
            'resource', 'treeview_3.ui')

        #uiw = loadUi(ui_file_path)
        uiw = loadUi(ui_file_path,
               #{'LoaduiProve': LoaduiProve,
               {'CustomQTableview': CustomQTableview,
               'CustomQTreeview': CustomQTreeview})

        self._std_model = QStandardItemModel()
        self._rootitem = self._std_model.invisibleRootItem()

        uiw._treeview.setModel(self._std_model)
        self.selectionModel = self._treeview.selectionModel()

        self.show()
Пример #47
0
    def testOperators(self):
        model = QStandardItemModel()
        for i in range(100):
            model.appendRow(QStandardItem("Item: %d" % i))

        first = model.index(0, 0)
        second = model.index(10, 0)
        third = model.index(20, 0)
        fourth = model.index(30, 0)

        sel = QItemSelection(first, second)
        sel2 = QItemSelection()
        sel2.select(third, fourth)

        sel3 = sel + sel2  # check operator +
        self.assertEqual(len(sel3), 2)
        sel4 = sel
        sel4 += sel2  # check operator +=
        self.assertEqual(len(sel4), 2)
        self.assertEqual(sel4, sel3)
Пример #48
0
    def __init__(self,parent= None):
#        QMainWindow.__init__(self)
        super(client, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.userModel = QStandardItemModel()
        self.itemHeadFriend=QStandardItem()
        self.itemHeadFriend.setData("linkMan",QtCore.Qt.DisplayRole)
        self.itemHeadStatis=QStandardItem()
        self.itemHeadStatis.setData("status",QtCore.Qt.DisplayRole)
        self.userModel.setHorizontalHeaderItem(0,self.itemHeadFriend)
        self.userModel.setHorizontalHeaderItem(1,self.itemHeadStatis)

                
        self.itemFriend=QStandardItem()
        self.itemFriend.setData("friend",QtCore.Qt.DisplayRole)
        self.userModel.insertRow(0,self.itemFriend)
        self.ui.linkManTreeView.setModel(self.userModel)

        self.connecting=None
        QtCore.QObject.connect(self.ui.linkManTreeView, QtCore.SIGNAL("clicked(QModelIndex)"), self,QtCore.SLOT("createMessageFrame(QModelIndex)"))
        self.messageFrame={}
Пример #49
0
    def data(self, index, role=Qt.DisplayRole):
        """

        :param index:
        :type index: QModelIndex
        :param role:
        :type role: int
        :return:
        :rtype: QBrush
        """
        item = self.itemFromIndex(index)
        idx = self._tree_view.model().mapFromSource(index)
        row = item.get_parent_row()

        if role == Qt.BackgroundRole:
            color = row.bg_color()

            if idx.row() % 2 == 0:
                color = color.darker(120)
            if not item.isEnabled():
                color = color.darker(110)
            return QBrush(color)

        return QStandardItemModel.data(self, index, role)
Пример #50
0
    def setData(self,data):
        """ data = [ (role, role.description, role active or not (True or False, not None)) ]
        """
        m = QStandardItemModel(len(data),2)

        row = 0
        for d in data:
            item = QStandardItem()
            item.setData(d[2],Qt.EditRole)
            m.setItem(row,0,item)

            item = QStandardItem()
            item.setData(d[0],Qt.UserRole)
            item.setData(d[1],Qt.DisplayRole)
            m.setItem(row,1,item)

            row += 1

        self.setModel(m)
        self.resizeColumnsToContents()
Пример #51
0
class List(QDialog):
    """All Notes dialog"""

    def __init__(self, app, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.app = app
        self.closed = False
        self.sort_order = None
        self.ui = Ui_List()
        self.ui.setupUi(self)
        self.setWindowIcon(get_icon())

        self.notebooksModel = QStandardItemModel()
        self.ui.notebooksList.setModel(self.notebooksModel)
        self.ui.notebooksList.selection.connect(self.selection_changed)
        self.ui.notebooksList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notebooksList.customContextMenuRequested.connect(self.notebook_context_menu)

        self.notesModel = QStandardItemModel()
        self.notesModel.setHorizontalHeaderLabels(
            [self.tr('Title'), self.tr('Last Updated')])

        self.ui.notesList.setModel(self.notesModel)
        self.ui.notesList.doubleClicked.connect(self.note_dblclicked)
        self.ui.notesList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.notesList.customContextMenuRequested.connect(self.note_context_menu)
        self.ui.notesList.header().sortIndicatorChanged.connect(self.sort_order_updated)

        self.ui.newNotebookBtn.setIcon(QIcon.fromTheme('folder-new'))
        self.ui.newNotebookBtn.clicked.connect(self.new_notebook)

        self.ui.newNoteBtn.setIcon(QIcon.fromTheme('document-new'))
        self.ui.newNoteBtn.clicked.connect(self.new_note)

        self.ui.newNoteBtn.setShortcut(QKeySequence(self.tr('Ctrl+n')))
        self.ui.newNotebookBtn.setShortcut(QKeySequence(self.tr('Ctrl+Shift+n')))
        QShortcut(QKeySequence(self.tr('Ctrl+q')), self, self.close)

    @Slot(QItemSelection, QItemSelection)
    def selection_changed(self, selected, deselected):
        if len(selected.indexes()):
            self.notebook_selected(selected.indexes()[-1])

    def showEvent(self, *args, **kwargs):
        QDialog.showEvent(self, *args, **kwargs)
        self._reload_notebooks_list()
        self.readSettings()

    def writeSettings(self):
        self.app.settings.setValue('list-geometry', self.saveGeometry())
        for key, widget in self._getRestorableItems():
            self.app.settings.setValue(key, widget.saveState())

    def _getRestorableItems(self):
        return (
            ('list-splitter-state', self.ui.splitter),
            ('list-header-state', self.ui.notesList.header()),
        )

    def readSettings(self):
        geometry = self.app.settings.value('list-geometry')
        if geometry:
            self.restoreGeometry(geometry)

        for key, widget in self._getRestorableItems():
            state = self.app.settings.value(key)
            if state:
                widget.restoreState(state)

    def closeEvent(self, event):
        self.writeSettings()
        event.ignore()
        self.closed = True
        self.hide()

    @Slot(int, Qt.SortOrder)
    def sort_order_updated(self, logicalIndex, order):
        self.sort_order = (logicalIndex, order.name)
        self.app.settings.setValue('list-notes-sort-order', self.sort_order)

    def notebook_selected(self, index):
        self.notesModel.setRowCount(0)

        item = self.notebooksModel.itemFromIndex(index)
        if hasattr(item, 'notebook'):
            notebook_id = item.notebook.id
        else:
            notebook_id = 0
        notebook_filter = [notebook_id] if notebook_id > 0 else dbus.Array([], signature='i')
        notes = self.app.provider.find_notes(
            '', notebook_filter, dbus.Array([], signature='i'),
            0, 2 ** 31 - 1, Note.ORDER_TITLE, -1,
        )  # fails with sys.maxint in 64
        for note_struct in notes:
            note = Note.from_tuple(note_struct)
            self.notesModel.appendRow(QNoteItemFactory(note).make_items())

        sort_order = self.sort_order
        if sort_order is None:
            sort_order = self.app.settings.value('list-notes-sort-order')

        if sort_order:
            logicalIndex, order = sort_order
            order = Qt.SortOrder.values[order]
            self.ui.notesList.sortByColumn(int(logicalIndex), order)

    @Slot()
    def note_dblclicked(self, index):
        item = self.notesModel.itemFromIndex(index)
        self.app.indicator.open(item.note)

    @Slot()
    def new_notebook(self):
        name, status = self._notebook_new_name(self.tr('Create new notebook'))
        if status:
            notebook_struct = self.app.provider.create_notebook(name)
            notebook = Notebook.from_tuple(notebook_struct)

            self.app.send_notify(self.tr('Notebook "%s" created!') % notebook.name)
            self._reload_notebooks_list(notebook.id)

    @Slot()
    def rename_notebook(self):
        index = self.ui.notebooksList.currentIndex()
        item = self.notebooksModel.itemFromIndex(index)
        notebook = item.notebook
        name, status = self._notebook_new_name(
            self.tr('Rename notebook'), notebook.name,
        )
        if status:
            notebook.name = name
            self.app.provider.update_notebook(notebook.struct)
            self.app.send_notify(self.tr('Notebook "%s" renamed!') % notebook.name)
            self._reload_notebooks_list(notebook.id)

    @Slot()
    def remove_notebook(self):
        msg = QMessageBox(
            QMessageBox.Critical,
            self.tr("You are trying to delete a notebook"),
            self.tr("Are you sure want to delete this notebook and its notes?"),
            QMessageBox.Yes | QMessageBox.No
        )
        if msg.exec_() == QMessageBox.Yes:
            index = self.ui.notebooksList.currentIndex()
            item = self.notebooksModel.itemFromIndex(index)
            self.app.provider.delete_notebook(item.notebook.id)
            self.app.send_notify(self.tr('Notebook "%s" deleted!') % item.notebook.name)
            self._reload_notebooks_list()

    @Slot()
    def new_note(self):
        index = self.ui.notebooksList.currentIndex()
        notebook_id = NONE_ID
        if index.row():
            item = self.notebooksModel.itemFromIndex(index)
            notebook_id = item.notebook.id

        self.app.indicator.create(notebook_id=notebook_id)

    @Slot()
    def edit_note(self):
        index = self.ui.notesList.currentIndex()
        item = self.notesModel.itemFromIndex(index)
        self.app.indicator.open(item.note)

    @Slot()
    def remove_note(self):
        index = self.ui.notesList.currentIndex()
        item = self.notesModel.itemFromIndex(index)
        msgBox = QMessageBox(
            QMessageBox.Critical,
            self.tr("You are trying to delete a note"),
            self.tr('Are you sure want to delete note "%s"?') % item.note.title,
            QMessageBox.Yes | QMessageBox.No
        )
        if msgBox.exec_() == QMessageBox.Yes:
            self.app.provider.delete_note(item.note.id)
            self.app.send_notify(self.tr('Note "%s" deleted!') % item.note.title)
            self.notebook_selected(self.ui.notebooksList.currentIndex())

    @Slot(QPoint)
    def notebook_context_menu(self, pos):
        index = self.ui.notebooksList.currentIndex()
        item = self.notebooksModel.itemFromIndex(index)
        if hasattr(item, 'notebook'):
            menu = QMenu(self.ui.notebooksList)
            menu.addAction(QIcon.fromTheme('gtk-edit'), self.tr('Rename'), self.rename_notebook)
            menu.addAction(QIcon.fromTheme('gtk-delete'), self.tr('Remove'), self.remove_notebook)
            menu.exec_(self.ui.notebooksList.mapToGlobal(pos))

    @Slot(QPoint)
    def note_context_menu(self, pos):
        menu = QMenu(self.ui.notesList)
        menu.addAction(QIcon.fromTheme('gtk-edit'), self.tr('Edit'), self.edit_note)
        menu.addAction(QIcon.fromTheme('gtk-delete'), self.tr('Remove'), self.remove_note)
        menu.exec_(self.ui.notesList.mapToGlobal(pos))

    def _reload_notebooks_list(self, select_notebook_id=None):
        self.notebooksModel.clear()
        root = QStandardItem(QIcon.fromTheme('user-home'), self.tr('All Notes'))
        self.notebooksModel.appendRow(root)

        selected_item = root
        for notebook_struct in self.app.provider.list_notebooks():
            notebook = Notebook.from_tuple(notebook_struct)
            count = self.app.provider.get_notebook_notes_count(notebook.id)
            item = QNotebookItem(notebook, count)
            root.appendRow(item)

            if select_notebook_id and notebook.id == select_notebook_id:
                selected_item = item

        self.ui.notebooksList.expandAll()
        if selected_item:
            index = self.notebooksModel.indexFromItem(selected_item)
            self.ui.notebooksList.setCurrentIndex(index)
            self.notebook_selected(index)

    def _notebook_new_name(self, title, exclude=''):
        names = map(lambda nb: Notebook.from_tuple(nb).name, self.app.provider.list_notebooks())
        try:
            names.remove(exclude)
        except ValueError:
            pass
        name, status = QInputDialog.getText(self, title, self.tr('Enter notebook name:'), text=exclude)
        while name in names and status:
            message = self.tr('Notebook with this name already exist. Enter notebook name')
            name, status = QInputDialog.getText(self, title, message)
        return name, status
Пример #52
0
    def testClear(self):

        model = QStandardItemModel()
        root = model.invisibleRootItem()
        model.clear()
        self.assertFalse(shiboken.isValid(root))
Пример #53
0
 def setUp(self):
    super(QStandardItemModelTest, self).setUp()
    self.window = QWidget()
    self.model = QStandardItemModel(0, 3, self.window)
Пример #54
0
    def __init__(self, parent=None):

        super(MainWindow, self).__init__(parent)
        self.main_frame = Ui_MainWindow()
        self.main_frame.setupUi(self)
        self.MONGODB_URI = 'mongodb://*****:*****@ds047040.mongolab.com:47040/magresdata' 
        self.dataDict = {}

        # define the dictionary search terms
        self.setTypeValue = False
        self.macroMoleculeValue = False
        self.operatorValue = False
        self.osmolyteValue = False

        # make connection to database instance
        #self.conn = pymongo.MongoClient(self.MONGODB_URI) # Connect to the database that I purchased
        #db = self.conn.magresdata # 'dynamicalTransition' is the name of my test database
        #self.collection = db.hanLabODNPTest # This is my test collection
        self.conn = pymongo.MongoClient('localhost',27017) # Connect to the database that I purchased
        db = self.conn.homeDB # 'dynamicalTransition' is the name of my test database
        self.collection = db.localData # This is my test collection
        # populate the comboBoxes
        keyVals = [str(k) for k in self.collection.distinct('setType')]
        keyVals.insert(0,'Select')
        self.main_frame.setTypeComboBox.addItems(keyVals)
        self.main_frame.setTypeComboBox.setEditable(True)
        keyVals = [str(k) for k in self.collection.distinct('macroMolecule')]
        keyVals.insert(0,'Select')
        self.main_frame.macroMoleculeComboBox.addItems(keyVals)
        self.main_frame.macroMoleculeComboBox.setEditable(True)
        keyVals = [str(k) for k in self.collection.distinct('osmolyte')]
        keyVals.insert(0,'Select')
        self.main_frame.osmolyteComboBox.addItems(keyVals)
        self.main_frame.osmolyteComboBox.setEditable(True)
        keyVals = [str(k) for k in self.collection.distinct('operator')]
        keyVals.insert(0,'Select')
        self.main_frame.operatorComboBox.addItems(keyVals)
        self.main_frame.operatorComboBox.setEditable(True)

        ### Connect the combobox events#{{{
        self.main_frame.osmolyteComboBox.currentIndexChanged.connect(self.osmolyteFromBox)
        self.main_frame.operatorComboBox.currentIndexChanged.connect(self.operatorFromBox)
        self.main_frame.macroMoleculeComboBox.currentIndexChanged.connect(self.macroMoleculeFromBox)
        self.main_frame.setTypeComboBox.currentIndexChanged.connect(self.setTypeFromBox)#}}}

        self.main_frame.plotButton.clicked.connect(self.plotDataListViewItems)
        self.main_frame.listWidget.itemClicked.connect(self.listGetItem)
        self.main_frame.addToPlotButton.clicked.connect(self.addToDataSets)
        self.main_frame.findSetButton.clicked.connect(self.findSets)
        #self.main_frame.clearPlotButton.clicked.connect(self.clearPlots)
        self.main_frame.clearPlotButton.clicked.connect(self.launchMPLWindow)

        # for the list checkbox
        self.main_frame.checkableList = QStandardItemModel(self.main_frame.dataListView)
        self.main_frame.checkableList.itemChanged.connect(self.onItemChanged)

        # For opening a new window.
        #self.dialogTextBrowser = MyDialog(self)
        #self.main_frame.findSetButton.clicked.connect(self.onOpenBrowser)

        # Set up the plotting widgets#{{{
        # the first plot widget
        self.main_frame.plotWidget = MatplotlibWidget(self.main_frame.widget)
        self.main_frame.plotWidget.setGeometry(QtCore.QRect(0,0,481,551./2))
        self.main_frame.plotWidget.setObjectName("plotWidget")

        # the second plot widget
        self.main_frame.plotWidget1 = MatplotlibWidget(self.main_frame.widget)
        self.main_frame.plotWidget1.setGeometry(QtCore.QRect(0,551./2,481,551./2))
        self.main_frame.plotWidget1.setObjectName("plotWidget1")#}}}
Пример #55
0
class TreeViewWidget:
    def __init__(self):
        self.tree = QtGui.QTreeView()
        self.keys = {}
        self.data = None
        self.model = QStandardItemModel()
        self.tree.setHeaderHidden(True)
        self.brushConflictInChild = QtGui.QBrush(QtGui.QColor(255, 136, 139))
        self.brushConflictInChild.setStyle(QtCore.Qt.SolidPattern)
        self.brushConflictInItem = QtGui.QBrush(QtGui.QColor(255, 0, 0))
        self.brushConflictInItem.setStyle(Qt.SolidPattern)
        self.brushChangedItem = QtGui.QBrush(QtGui.QColor(249, 233, 170))
        self.brushChangedItem.setStyle(Qt.SolidPattern)
        self.brushAddedItem = QtGui.QBrush(QtGui.QColor(221, 252, 199))
        self.brushAddedItem.setStyle(Qt.SolidPattern)
        self.whiteBrush = QtGui.QBrush(QtGui.QColor(177, 177, 177))
        self.whiteBrush.setStyle(Qt.SolidPattern)

    def _GetStyleSheet(self):
        return '\n\n                QTreeView {\n\n                }\n                QTreeView::item {\n                    background: none;\n                }\n                QTreeView::item:selected {\n                    background: none;\n                }\n                QTreeView::item:selected:active {\n                    background: none;\n                }\n                QTreeView::item:focus\n                {\n                    background: none;\n                }\n                QTreeView::branch {\n                    background: none;\n                }\n                QListWidget::item:selected {\n                    background: none;\n                }\n                QListWidget::item:selected:active {\n                    background: none;\n                }\n                QWidget::item:selected {\n                    background: none;\n                }\n\n               '

    def _WrapWord(self, columnWidth, value):
        valueAsList = list(value)
        currentIndex = 0
        doInsert = False
        for i in range(0, len(valueAsList)):
            if currentIndex * 7 > columnWidth and i > 0:
                doInsert = True
                currentIndex = 0
            currentIndex += 1
            if doInsert and valueAsList[i] == ' ':
                valueAsList[i] = '\n'
                doInsert = False

        value = ''.join(valueAsList)
        return value

    def BuildTree(self, data, columnWidth=0):
        self.model = QStandardItemModel()
        self.data = data
        self.AddItems(self.model, data, columnWidth=columnWidth)
        self.tree.setModel(self.model)

    def ClearPathToItem(self, location):
        self.ColorItemInLocation(location, self.whiteBrush)

    def UpdateSingleItem(self, data):
        itemIndex = self.tree.selectedIndexes()[0]
        item = self.model.itemFromIndex(itemIndex)
        if item is not None:
            if data is not None:
                item.removeRows(0, item.rowCount())
                itemData = item.data(0).split(': ')
                if type(data) in (dict, list):
                    item.setText(itemData[0])
                    self.AddItems(item, data)
                else:
                    if type(data) is unicode:
                        dataValue = data
                    else:
                        dataValue = str(data)
                    item.setText(itemData[0] + ': ' + dataValue)
            elif item.parent() is None:
                self.model.removeRow(itemIndex.row())
            else:
                item.parent().removeRow(itemIndex.row())

    def ConvertDataToString(self, data):
        value = ''
        if type(data) not in (list, dict):
            if type(data) is unicode:
                value = data
            elif data is None:
                value = '(DELETED)'
            else:
                value = str(data)
        return value

    def _MakeItemUneditable(self, item):
        item.setFlags(item.flags() & ~Qt.ItemIsEditable)

    def _AddDictToTree(self, data, parent, columnWidth=0):
        sortedKeys = sorted(data.keys())
        for key in sortedKeys:
            value = self.ConvertDataToString(data[key])
            if value == '':
                item = QStandardItem(str(key))
            else:
                item = QStandardItem(str(key) + ': ' + value)
                if len(value) > 10:
                    item.setToolTip(value)
            self._MakeItemUneditable(item)
            parent.appendRow(item)
            if type(data[key]) in (dict, list):
                self.AddItems(item, data[key], columnWidth=columnWidth)

    def _AddListToTree(self, data, parent):
        for attribute in data:
            item = QStandardItem(str(attribute))
            self._MakeItemUneditable(item)
            parent.appendRow(item)

    def _AddPrimitiveToTree(self, data, parent, columnWidth=0):
        if type(data) in (str, unicode):
            value = self._WrapWord(columnWidth, data)
        else:
            value = self.ConvertDataToString(data)
        item = QStandardItem(value)
        self._MakeItemUneditable(item)
        parent.appendRow(item)

    def AddItems(self, parent, data, columnWidth=0):
        if type(data) is dict:
            self._AddDictToTree(data, parent, columnWidth=columnWidth)
        elif type(data) is list:
            self._AddListToTree(data, parent)
        else:
            self._AddPrimitiveToTree(data, parent, columnWidth=columnWidth)

    def _BinarySearchKeys(self, keys, key, currentMin, currentMax):
        while currentMax >= currentMin:
            mid = currentMin + (currentMax - currentMin) / 2
            if keys[mid] < key:
                currentMin = mid + 1
            elif keys[mid] > key:
                currentMax = mid - 1
            else:
                return mid

        return -1

    def _FindIndexOfKey(self, currentData, key):
        if type(currentData) is dict:
            sortedKeys = sorted(currentData.keys())
            return self._BinarySearchKeys(sortedKeys, key, 0,
                                          len(sortedKeys) - 1)
        else:
            for index, data in enumerate(currentData):
                if index == key:
                    return key

            return -1

    def _GetNextRoot(self, index, root):
        if root is None:
            root = self.model.index(index, 0)
        else:
            root = root.child(index, 0)
        return root

    def _GetChildDataByKey(self, currentData, key):
        if type(currentData) is dict:
            return currentData.get(key, None)
        else:
            return key + 1

    def ColorItem(self, item, brush):
        item.setData(QtGui.QBrush(QtGui.QColor(brush.color())),
                     Qt.ForegroundRole)

    def ColorItemInLocation(self, location, brush):
        root = None
        currentData = self.data
        for key in location:
            index = self._FindIndexOfKey(currentData, key)
            root = self._GetNextRoot(index, root)
            if root is not None:
                item = self.model.itemFromIndex(root)
                if item is not None:
                    self.ColorItem(item, brush)
            else:
                break
            currentData = self._GetChildDataByKey(currentData, key)

    def ColorAddedItems(self, locations):
        for location in locations:
            self.ColorItemInLocation(location, self.brushAddedItem)

    def ColorChangedItems(self, locations):
        for location in locations:
            self.ColorItemInLocation(location, self.brushChangedItem)

    def _ColorText(self, data, color):
        return "<b><font style='font-size: 14px; color: " + color + ";'>" + data + '</font></b>'

    def _DiffTreeDataIsValid(self, data):
        if data is None:
            return False
        if data == '(DELETED)':
            return False
        if data == '(DOES NOT EXIST)':
            return False
        return True

    def _AddDiffInfoAsTooltipForItem(self, item, itemData, base):
        result = ''
        if self._DiffTreeDataIsValid(itemData) and self._DiffTreeDataIsValid(
                base):
            if not item.hasChildren():
                if ':' in itemData:
                    diffTreeData = itemData.split(':')[1]
                else:
                    diffTreeData = itemData
            else:
                diffTreeData = itemData
            diffBaseData = base
            if type(itemData) is not unicode:
                diffTreeData = str(diffTreeData)
            if type(base) is not unicode:
                diffBaseData = str(diffBaseData)
            for diff in difflib.ndiff(diffTreeData, diffBaseData):
                if diff.startswith('- '):
                    result += self._ColorText(diff.split('- ')[1], '#00ff00')
                elif diff.startswith('+ '):
                    result += self._ColorText(diff.split('+ ')[1], '#ff0000')
                else:
                    result += diff.split('  ')[1]

            item.setToolTip(result)

    def _FindItemByLocation(self, location):
        root = None
        currentData = self.data
        item = None
        for key in location:
            index = self._FindIndexOfKey(currentData, key)
            root = self._GetNextRoot(index, root)
            if root is not None:
                item = self.model.itemFromIndex(root)
            currentData = self._GetChildDataByKey(currentData, key)

        return item

    def AddDiffTooltipToLocations(self, locations):
        for data in locations:
            location = data[0]
            baseData = data[1]
            item = self._FindItemByLocation(location)
            if item is None:
                item = self.model.itemFromIndex(self.model.index(0, 0))
            if type(baseData) is list:
                lastItemIndex = 0
                if len(location) > 0:
                    lastItemIndex = len(location) - 1
                self._AddDiffInfoAsTooltipForItem(item,
                                                  item.data(lastItemIndex),
                                                  baseData[lastItemIndex])
            else:
                self._AddDiffInfoAsTooltipForItem(item, item.data(0), baseData)

    def _ColorLocationWithKeys(self, finalKey, keys):
        root = None
        currentData = self.data
        for key in keys:
            index = self._FindIndexOfKey(currentData, key)
            root = self._GetNextRoot(index, root)
            if root is not None:
                try:
                    item = self.model.itemFromIndex(root)
                    if key == finalKey:
                        brush = self.brushConflictInItem
                    else:
                        brush = self.brushConflictInChild
                    self.ColorItem(item, brush)
                except AttributeError:
                    pass

            else:
                break
            currentData = self._GetChildDataByKey(currentData, key)

    def ColorLocationsInTree(self, conflicts, base=None):
        if self.data is not None:
            for keys in conflicts:
                try:
                    finalKey = keys[-1]
                except IndexError:
                    continue

                self._ColorLocationWithKeys(finalKey, keys)

    def ExpandAndMoveTo(self, keys):
        if self.data is not None:
            root = None
            currentData = self.data
            for key in keys:
                if currentData is not None:
                    index = self._FindIndexOfKey(currentData, key)
                    root = self._GetNextRoot(index, root)
                    self.tree.setExpanded(root, True)
                    currentData = currentData.get(key, None)

            if root is not None:
                self.tree.setCurrentIndex(root)

    def GetWidget(self):
        return self.tree
Пример #56
0
    def __init__(self, _app, parent=None):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.iTrayIcon = QSystemTrayIcon()
        self.iTrayIcon.setIcon(QIcon("drapes.ico"))
        self.iTrayIcon.show()
        self.iTrayIcon.setToolTip("One world, One dream!")
        self.iTrayIcon.activated.connect(self.iconActivated)
        self.quitAction = QAction("&Quit", self, triggered=QApplication.quit)
        self.trayIconMenu = QMenu(self)
        self.trayIconMenu.addAction(self.quitAction)
        self.iTrayIcon.setContextMenu(self.trayIconMenu)

        #选择MYSQL保留用户信息
        QObject.connect(self.ui.mysql_groupBox, SIGNAL("clicked()"), self, SLOT("choiceSql()"))
        #选择XT文件留用户信息
        QObject.connect(self.ui.text_groupBox, SIGNAL("clicked()"), self, SLOT("choiceTxt()"))
        #选择XML文件留用户信息
        QObject.connect(self.ui.xml_groupBox, SIGNAL("clicked()"), self, SLOT("choiceXml()"))                
        #节面显示英文
        QObject.connect(self.ui.actionEnglish, SIGNAL("activated()"), self, SLOT("loadEnglish()"))
        #节面显示中文
        QObject.connect(self.ui.actionChinese, SIGNAL("activated()"), self, SLOT("loadChinese()"))
        
        #加载配置文件
        QObject.connect(self.ui.actionLoad_Config, SIGNAL("activated()"), self, SLOT("loadConfig()"))
        #保留配置文件
        QObject.connect(self.ui.actionSave_Config, SIGNAL("activated()"), self, SLOT("saveConfig()"))
        #about操作
        QObject.connect(self.ui.actionAbout, SIGNAL("activated()"), self, SLOT("about()"))
        
        #选择XML文件
        QObject.connect(self.ui.openXml_pushButton, SIGNAL("clicked()"), self, SLOT("xml_open()"))
        #选择TXT文件
        QObject.connect(self.ui.openText_pushButton, SIGNAL("clicked()"), self, SLOT("txt_open()"))
        #启动服务
        QObject.connect(self.ui.startServer_pushButton, SIGNAL("clicked()"), self, SLOT("startServer()"))
        #停止服务
        QObject.connect(self.ui.stopServer_pushButton, SIGNAL("clicked()"), self, SLOT("stopServer()"))

        self.ui.sqlTypeComboBox.activated[str].connect(self.sqlServer)
                
        QObject.connect(self.ui.openSqlpushButton, SIGNAL("clicked()"), self, SLOT("database_open()"))
        

        #界面语言
        self.translator = None
        self.app = _app
        self.translator = QTranslator() 
        self.connect = None
        self.users = None
        self.ControlMediaPath = None
        self.ControlMedia = None
        self.delUsrInfo = None

        self.userModel = QStandardItemModel()
        self.userModel.setHorizontalHeaderItem(0, QStandardItem("user"))
        self.userModel.setHorizontalHeaderItem(1, QStandardItem("friends"))
        

        self.userModel.setVerticalHeaderItem(0, QStandardItem("1"))
        self.userModel.setVerticalHeaderItem(1, QStandardItem("2"))
        self.userModel.setVerticalHeaderItem(2, QStandardItem("3"))

        self.loginUserModel = QStandardItemModel()
        self.loginUserModel.setHorizontalHeaderItem(0, QStandardItem("user"))
        self.loginUserModel.setHorizontalHeaderItem(1, QStandardItem("instance"))
        
        self.messageModel = QStandardItemModel()
        self.messageModel.setHorizontalHeaderItem(0, QStandardItem("message"))

        #读取系统配置文件
        self.readConfig(configFile)
        self.statusBar().showMessage("server is stopped!")
        
        self.ui.userInfo_tableView.setModel(self.userModel)
        self.createUserInfoContextMenu()
        self.ui.loginUsers_tableView.setModel(self.loginUserModel)
        self.createloginUsersContextMenu()
        self.ui.messageLogs_listView.setModel(self.messageModel)

        #界面多语处理
        self.updateLanguage(self.language)
        
        self.center()
Пример #57
0
class BrowserWindow(QMainWindow):

    MO_ROLE = Qt.UserRole+1

    def __init__(self, conn):
        super(BrowserWindow, self).__init__()
        self._conn = conn
        self._resolver = AsyncResolver()
        self._resolver.object_resolved.connect(self._data_resolved)
        self._resolver.start()
        self._init_models()
        self._init_gui()
        self._init_data()
        self._init_connections()

    def __del__(self):
        self._resolver.stop_work()
        self._resolver.terminate()

    def _init_models(self):
        self._hierarchy_model = QStandardItemModel()
        self._hierarchy_model.setColumnCount(2)
        self._hierarchy_model.setHorizontalHeaderLabels(['class', 'dn'])
        self._details_model = QStandardItemModel()
        self._details_model.setColumnCount(2)
        self._details_model.setHorizontalHeaderLabels(['Property', 'Value'])

    def _init_gui(self):
        self._widget = QSplitter(self, Qt.Horizontal)
        self._hierarchy_view = QTreeView(self._widget)
        self._details_view = QTableView(self._widget)

        self._widget.addWidget(self._hierarchy_view)
        self._widget.addWidget(self._details_view)
        self._widget.setStretchFactor(0, 2)
        self._widget.setStretchFactor(1, 1)
        self.setCentralWidget(self._widget)

        self._hierarchy_view.setModel(self._hierarchy_model)
        self._details_view.setModel(self._details_model)

        self._hierarchy_view.expanded.connect(self._mo_item_expand)

    def _init_data(self):
        item = self._row_for_mo(self._conn.resolve_dn(''))
        self._hierarchy_model.insertRow(0, item)

    def _init_connections(self):
        self.connect(self._resolver,
                        SIGNAL('object_resolved(QVariant)'),
                     self,
                        SLOT('_data_resolved(QVariant)'))
        self._hierarchy_view.activated.connect(self._item_activated)
        #self.connect(self._hierarchy_view.selectionModel(),
        #                SIGNAL('currentChanged(QModelIndex,QModelIndex)'),
        #             self,
        #                SLOT('_current_changed(QModelIndex, QModelIndex)'))
        self.connect(self._hierarchy_view.selectionModel(),
                        SIGNAL('activated(QModelIndex)'),
                     self,
                        SLOT('_item_activated(QModelIndex)'))


    def _row_for_mo(self, mo):
        row = [QStandardItem(mo.ucs_class), QStandardItem(mo.dn)]
        for item in row:
            item.setEditable(False)
        row[0].appendColumn([QStandardItem('Loading...')])
        row[0].setData(mo, self.MO_ROLE)
        return row

    def _add_mo_in_tree(self, mo, index=QtCore.QModelIndex()):
        item = None
        if index.isValid():
            item = self._hierarchy_model.itemFromIndex(index)
        else:
            item = self._get_item_for_dn(self._parent_dn(mo.dn))
        if item:
            item.appendColumn([self._row_for_mo(mo)[0]])
        self.auto_width()

    def _add_mos_in_tree(self, mos, index=QtCore.QModelIndex()):
        item = None
        if index.isValid():
            item = self._hierarchy_model.itemFromIndex(index)
        else:
            if not mos:
                return
            item = self._get_item_for_dn(self._parent_dn(mos[0].dn))
        while item.columnCount():
            item.removeColumn(0)
        items = map(self._row_for_mo, mos)
        if items:
            for x in xrange(len(items[0])):
                item.appendColumn([row[x] for row in items])
        self.auto_width()

    @staticmethod
    def _parent_dn(dn):
        parent_dn, _, rn = dn.rpartition('/')
        return parent_dn

    def _get_item_for_dn(self, dn):
        parent_dn = dn
        items = self._hierarchy_model.findItems(parent_dn, column=1)
        if items:
            return self._hierarchy_model.item(items[0].row())
        return None

    @QtCore.Slot('_data_resolved(QVariant)')
    def _data_resolved(self, datav):
        print 'Data resolved: ', datav
        index, data = datav
        if isinstance(data, UcsmObject):
            self._add_mo_in_tree(data, index=index)
        else:
            self._add_mos_in_tree(data, index=index)

    @QtCore.Slot('_current_changed(QModelIndex,QModelIndex)')
    def _current_changed(self, curr, prev):
        self._item_activated(curr)

    @QtCore.Slot('_item_activated(QModelIndex)')
    def _item_activated(self, index):
        print 'Activated: %s data %s' % (index, index.data(self.MO_ROLE))
        if index.sibling(0, 0).isValid():
            index = index.sibling(0, 0)
            data = index.data(self.MO_ROLE)
            self.set_detail_object(data)

    def _mo_item_expand(self, index):
        obj = index.data(self.MO_ROLE)
        print 'Expanded object: %s' % obj
        try:
            self._resolver.add_task(lambda: (index,
                                        self._conn.resolve_children(obj.dn)))
        except (KeyError, AttributeError):
            QtGui.QMessageBox.critical(0, 'Error', 'Object does not have dn')

    def auto_width(self):
        for view in [self._hierarchy_view, self._details_view]:
            for col in xrange(view.model().columnCount()):
                view.resizeColumnToContents(col)

    def set_detail_object(self, object):
        self._details_model.removeRows(0, self._details_model.rowCount())
        for k, v in object.attributes.iteritems():
            row = [QStandardItem(k), QStandardItem(v)]
            for item in row:
                item.setEditable(False)
            self._details_model.appendRow(row)
        self.auto_width()
Пример #58
0
    def __init__(self, parent=None):
        """Initialize the parent class of this instance."""
        super(window, self).__init__(parent)
        app.aboutToQuit.connect(self.myExitHandler)

        self.style_sheet = self.styleSheet('style')
        # app.setStyle(QStyleFactory.create('Macintosh'))
        #app.setStyleSheet(self.style_sheet)
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0,0,0,0)

        app.setOrganizationName("Eivind Arvesen")
        app.setOrganizationDomain("https://github.com/eivind88/raskolnikov")
        app.setApplicationName("Raskolnikov")
        app.setApplicationVersion("0.0.1")
        settings = QSettings()

        self.data_location = QDesktopServices.DataLocation
        self.temp_location = QDesktopServices.TempLocation
        self.cache_location = QDesktopServices.CacheLocation

        self.startpage = "https://duckduckgo.com/"
        self.new_tab_behavior = "insert"

        global bookmarks

        global saved_tabs
        print "Currently saved_tabs:\n", saved_tabs

        global menubar
        menubar = QMenuBar()

        # Initialize a statusbar for the window
        self.statusbar = self.statusBar()
        self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.statusbar.setStyleSheet(self.style_sheet)
        self.statusbar.setMinimumHeight(15)

        self.pbar = QProgressBar()
        self.pbar.setMaximumWidth(100)
        self.statusbar.addPermanentWidget(self.pbar)

        self.statusbar.hide()

        self.setMinimumSize(504, 235)
        # self.setWindowModified(True)
        # app.alert(self, 0)
        self.setWindowTitle("Raskolnikov")
        # toolbar = self.addToolBar('Toolbar')
        # toolbar.addAction(exitAction)
        # self.setUnifiedTitleAndToolBarOnMac(True)
        self.setWindowIcon(QIcon(""))

        # Create input widgets
        self.bbutton = QPushButton(u"<")
        self.fbutton = QPushButton(u">")
        self.hbutton = QPushButton(u"⌂")
        self.edit = QLineEdit("")
        self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
        self.edit.setPlaceholderText("Enter URL")
        # self.edit.setMinimumSize(400, 24)
        self.rbutton = QPushButton(u"↻")
        self.dbutton = QPushButton(u"☆")
        self.tbutton = QPushButton(u"⁐")
        # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎
        self.nbutton = QPushButton(u"+")
        self.nbutton.setObjectName("NewTab")
        self.nbutton.setMinimumSize(35, 30)
        self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        self.edit.setTextMargins(2, 1, 2, 0)

        # create a horizontal layout for the input
        input_layout = QHBoxLayout()
        input_layout.setSpacing(4)
        input_layout.setContentsMargins(0, 0, 0, 0)

        # add the input widgets to the input layout
        input_layout.addWidget(self.bbutton)
        input_layout.addWidget(self.fbutton)
        input_layout.addWidget(self.hbutton)
        input_layout.addWidget(self.edit)
        input_layout.addWidget(self.rbutton)
        input_layout.addWidget(self.dbutton)
        input_layout.addWidget(self.tbutton)

        # create a widget to hold the input layout
        self.input_widget = QFrame()
        self.input_widget.setObjectName("InputWidget")
        self.input_widget.setStyleSheet(self.style_sheet)

        # set the layout of the widget
        self.input_widget.setLayout(input_layout)
        self.input_widget.setVisible(True)

        # CREATE BOOKMARK-LINE HERE
        self.bookmarks_layout = QHBoxLayout()
        self.bookmarks_layout.setSpacing(0)
        self.bookmarks_layout.setContentsMargins(0, 0, 0, 0)

        for i in bookmarks:
            link = QToolButton()
            link.setDefaultAction(QAction(unicode(i), link))
            link.setObjectName(unicode(i))
            link.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
            link.clicked.connect(self.handleBookmarks)

            self.bookmarks_layout.addWidget(link)

        self.bookmarks_widget = QFrame()
        self.bookmarks_widget.setObjectName("BookmarkWidget")
        self.bookmarks_widget.setStyleSheet(self.style_sheet)
        self.bookmarks_widget.setLayout(self.bookmarks_layout)

        if not bookmarks:
            self.bookmarks_widget.hide()

        # Task list
        self.tasklist = QStandardItemModel()
        #parentItem = self.tasklist.invisibleRootItem()
        #self.tasklist.header().hide()
        self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks'))
        parentItem = QStandardItem("Parent")
        self.tasklist.appendRow(parentItem)
        for i in range(4):
            item = QStandardItem("Item %d" % i)
            parentItem.appendRow(item)
            #parentItem = item

        #self.list.activated[str].connect(self.handleBookmarks)
        #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        # create tabs
        self.tabs = QTabWidget()
        self.tabs.setDocumentMode(True)
        self.tabs.setTabsClosable(True)
        self.tabs.setMovable(True)
        self.tabs.tabBar().hide()
        self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.tabs.setCornerWidget(self.nbutton)
        self.tabs.cornerWidget().setObjectName("CornerWidget")
        self.tabs.cornerWidget().setMinimumSize(10, 24)
        self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        if saved_tabs:
            for tab in saved_tabs['tabs']:
                tasklist = QTreeView()
                tasklist.hide()
                tasklist.setObjectName('taskList')
                tasklist.setMinimumWidth(100)
                tasklist.setMaximumWidth(250)

                new_tab = QWebView()
                new_tab.setObjectName('webView')

                inspector = QWebInspector(self)
                inspector.setObjectName('webInspector')
                inspector.hide()

                page_layout = QVBoxLayout()
                page_layout.setSpacing(0)
                page_layout.setContentsMargins(0, 0, 0, 0)
                page_layout.addWidget(new_tab)
                page_layout.addWidget(inspector)
                page_widget = QFrame()
                page_widget.setObjectName('pageWidget')
                page_widget.setLayout(page_layout)

                complete_tab_layout = QHBoxLayout()
                complete_tab_layout.setSpacing(0)
                complete_tab_layout.setContentsMargins(0, 0, 0, 0)
                complete_tab_layout.addWidget(tasklist)
                complete_tab_layout.addWidget(page_widget)
                complete_tab_widget = QFrame()
                complete_tab_widget.setLayout(complete_tab_layout)

                #for page in tab['history']:
                #    new_tab.load(QUrl(page['url']))
                #print tab['current_history']
                #for item in new_tab.history().items():
                #    print item
                #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history']))
                new_tab.load(QUrl(tab['history'][tab['current_history']]['url']))
                tab['current_history']
                self.tabs.setUpdatesEnabled(False)
                if self.new_tab_behavior == "insert":
                    self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget,
                                        unicode(new_tab.title()))
                elif self.new_tab_behavior == "append":
                    self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title()))
                self.tabs.setUpdatesEnabled(True)
                new_tab.titleChanged.connect(self.change_tab)
                new_tab.urlChanged.connect(self.change_tab)
                new_tab.loadStarted.connect(self.load_start)
                new_tab.loadFinished.connect(self.load_finish)
                new_tab.loadProgress.connect(self.pbar.setValue)
                new_tab.page().linkHovered.connect(self.linkHover)
                inspector.setPage(new_tab.page())

            for index, tab in enumerate(saved_tabs['tabs']):
                self.tabs.setTabText(index, tab['history'][tab['current_history']]['title'])

            self.tabs.setCurrentIndex(saved_tabs['current_tab'])
        else:
            self.new_tab()

        tabs_layout = QVBoxLayout()
        tabs_layout.setSpacing(0)
        tabs_layout.setContentsMargins(0, 0, 0, 0)
        tabs_layout.addWidget(self.tabs)

        self.tabs_widget = QFrame()
        self.tabs_widget.setObjectName("TabLine")
        self.tabs_widget.setStyleSheet(self.style_sheet)
        self.tabs_widget.setLayout(tabs_layout)
        self.tabs_widget.setVisible(True)

        # Webkit settings
        gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings()
        # Basic settings
        gsettings.setAttribute(QWebSettings.AutoLoadImages, True)
        gsettings.setAttribute(QWebSettings.JavascriptEnabled, True)
        gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False)
        gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False)
        gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present
        gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide
        gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled,
            True)
        # Performace settings
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True)
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        # Other settings
        gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False)

        # Create a vertical layout and add widgets
        vlayout = QVBoxLayout()
        vlayout.setSpacing(0)
        vlayout.setContentsMargins(0, 0, 0, 0)
        # toolbar.addWidget(self.input_widget)
        vlayout.addWidget(self.input_widget)
        vlayout.addWidget(self.bookmarks_widget)
        vlayout.addWidget(self.tabs_widget)

        # create a widget to hold the vertical layout
        wrapper_widget = QWidget()
        wrapper_widget.setLayout(vlayout)
        self.setCentralWidget(wrapper_widget)

        self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back)
        self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward)
        self.hbutton.clicked.connect(self.goHome)
        self.edit.returnPressed.connect(self.set_url)
        # Add button signal to "go" slot
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)
        self.dbutton.clicked.connect(self.bookmark)
        self.tbutton.clicked.connect(self.toggleTaskBar)
        self.nbutton.clicked.connect(self.new_tab)
        self.tabs.tabCloseRequested.connect(self.tabs.removeTab)
        self.tabs.currentChanged.connect(self.change_tab)

        widgets = (input_layout.itemAt(i).widget() for i in range(
            input_layout.count()))
        for widget in widgets:
            if isinstance(widget, QPushButton):
                widget.setFixedSize(33, 21)
                widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
                widget.pressed.connect(self.press_button)
                widget.released.connect(self.release_button)

        # make a ctrl+q quit
        sequence = QKeySequence(Qt.CTRL + Qt.Key_Q)
        QShortcut(sequence, self, SLOT("close()"))

        # make an accelerator to toggle fullscreen
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F)
        QShortcut(sequence, self, self.toggle_fullscreen)

        # make an accelerator to toggle input visibility
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L)
        QShortcut(sequence, self, self.toggle_input)

        # make an accelerator to focus adress-bar
        sequence = QKeySequence(Qt.CTRL + Qt.Key_L)
        QShortcut(sequence, self, self.focus_adress)

        # make an accelerator to reload page
        sequence = QKeySequence(Qt.CTRL + Qt.Key_R)
        QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)

        # make an accelerator to create new tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_T)
        QShortcut(sequence, self, self.new_tab)

        # make an accelerator to close tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_W)
        QShortcut(sequence, self, self.close_tab)

        # make an accelerator to navigate tabs
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left)
        QShortcut(sequence, self, self.previous_tab)
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right)
        QShortcut(sequence, self, self.next_tab)

        # make an accelerator to toggle inspector
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U)
        QShortcut(sequence, self, self.handleShowInspector)

        # make an accelerator to toggle bookmark
        sequence = QKeySequence(Qt.CTRL + Qt.Key_D)
        QShortcut(sequence, self, self.bookmark)

        # make an accelerator to toggle task/project-list
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L)
        QShortcut(sequence, self, self.toggleTaskBar)

        # finally set the attribute need to rotate
        # try:
        #     self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
        # except:
        #     print "not maemo"

        self.statusbar.show()
Пример #59
0
class window(QMainWindow):

    """Main window."""

    def __init__(self, parent=None):
        """Initialize the parent class of this instance."""
        super(window, self).__init__(parent)
        app.aboutToQuit.connect(self.myExitHandler)

        self.style_sheet = self.styleSheet('style')
        # app.setStyle(QStyleFactory.create('Macintosh'))
        #app.setStyleSheet(self.style_sheet)
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0,0,0,0)

        app.setOrganizationName("Eivind Arvesen")
        app.setOrganizationDomain("https://github.com/eivind88/raskolnikov")
        app.setApplicationName("Raskolnikov")
        app.setApplicationVersion("0.0.1")
        settings = QSettings()

        self.data_location = QDesktopServices.DataLocation
        self.temp_location = QDesktopServices.TempLocation
        self.cache_location = QDesktopServices.CacheLocation

        self.startpage = "https://duckduckgo.com/"
        self.new_tab_behavior = "insert"

        global bookmarks

        global saved_tabs
        print "Currently saved_tabs:\n", saved_tabs

        global menubar
        menubar = QMenuBar()

        # Initialize a statusbar for the window
        self.statusbar = self.statusBar()
        self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.statusbar.setStyleSheet(self.style_sheet)
        self.statusbar.setMinimumHeight(15)

        self.pbar = QProgressBar()
        self.pbar.setMaximumWidth(100)
        self.statusbar.addPermanentWidget(self.pbar)

        self.statusbar.hide()

        self.setMinimumSize(504, 235)
        # self.setWindowModified(True)
        # app.alert(self, 0)
        self.setWindowTitle("Raskolnikov")
        # toolbar = self.addToolBar('Toolbar')
        # toolbar.addAction(exitAction)
        # self.setUnifiedTitleAndToolBarOnMac(True)
        self.setWindowIcon(QIcon(""))

        # Create input widgets
        self.bbutton = QPushButton(u"<")
        self.fbutton = QPushButton(u">")
        self.hbutton = QPushButton(u"⌂")
        self.edit = QLineEdit("")
        self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
        self.edit.setPlaceholderText("Enter URL")
        # self.edit.setMinimumSize(400, 24)
        self.rbutton = QPushButton(u"↻")
        self.dbutton = QPushButton(u"☆")
        self.tbutton = QPushButton(u"⁐")
        # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎
        self.nbutton = QPushButton(u"+")
        self.nbutton.setObjectName("NewTab")
        self.nbutton.setMinimumSize(35, 30)
        self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        self.edit.setTextMargins(2, 1, 2, 0)

        # create a horizontal layout for the input
        input_layout = QHBoxLayout()
        input_layout.setSpacing(4)
        input_layout.setContentsMargins(0, 0, 0, 0)

        # add the input widgets to the input layout
        input_layout.addWidget(self.bbutton)
        input_layout.addWidget(self.fbutton)
        input_layout.addWidget(self.hbutton)
        input_layout.addWidget(self.edit)
        input_layout.addWidget(self.rbutton)
        input_layout.addWidget(self.dbutton)
        input_layout.addWidget(self.tbutton)

        # create a widget to hold the input layout
        self.input_widget = QFrame()
        self.input_widget.setObjectName("InputWidget")
        self.input_widget.setStyleSheet(self.style_sheet)

        # set the layout of the widget
        self.input_widget.setLayout(input_layout)
        self.input_widget.setVisible(True)

        # CREATE BOOKMARK-LINE HERE
        self.bookmarks_layout = QHBoxLayout()
        self.bookmarks_layout.setSpacing(0)
        self.bookmarks_layout.setContentsMargins(0, 0, 0, 0)

        for i in bookmarks:
            link = QToolButton()
            link.setDefaultAction(QAction(unicode(i), link))
            link.setObjectName(unicode(i))
            link.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
            link.clicked.connect(self.handleBookmarks)

            self.bookmarks_layout.addWidget(link)

        self.bookmarks_widget = QFrame()
        self.bookmarks_widget.setObjectName("BookmarkWidget")
        self.bookmarks_widget.setStyleSheet(self.style_sheet)
        self.bookmarks_widget.setLayout(self.bookmarks_layout)

        if not bookmarks:
            self.bookmarks_widget.hide()

        # Task list
        self.tasklist = QStandardItemModel()
        #parentItem = self.tasklist.invisibleRootItem()
        #self.tasklist.header().hide()
        self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks'))
        parentItem = QStandardItem("Parent")
        self.tasklist.appendRow(parentItem)
        for i in range(4):
            item = QStandardItem("Item %d" % i)
            parentItem.appendRow(item)
            #parentItem = item

        #self.list.activated[str].connect(self.handleBookmarks)
        #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        # create tabs
        self.tabs = QTabWidget()
        self.tabs.setDocumentMode(True)
        self.tabs.setTabsClosable(True)
        self.tabs.setMovable(True)
        self.tabs.tabBar().hide()
        self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
        self.tabs.setCornerWidget(self.nbutton)
        self.tabs.cornerWidget().setObjectName("CornerWidget")
        self.tabs.cornerWidget().setMinimumSize(10, 24)
        self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum)

        if saved_tabs:
            for tab in saved_tabs['tabs']:
                tasklist = QTreeView()
                tasklist.hide()
                tasklist.setObjectName('taskList')
                tasklist.setMinimumWidth(100)
                tasklist.setMaximumWidth(250)

                new_tab = QWebView()
                new_tab.setObjectName('webView')

                inspector = QWebInspector(self)
                inspector.setObjectName('webInspector')
                inspector.hide()

                page_layout = QVBoxLayout()
                page_layout.setSpacing(0)
                page_layout.setContentsMargins(0, 0, 0, 0)
                page_layout.addWidget(new_tab)
                page_layout.addWidget(inspector)
                page_widget = QFrame()
                page_widget.setObjectName('pageWidget')
                page_widget.setLayout(page_layout)

                complete_tab_layout = QHBoxLayout()
                complete_tab_layout.setSpacing(0)
                complete_tab_layout.setContentsMargins(0, 0, 0, 0)
                complete_tab_layout.addWidget(tasklist)
                complete_tab_layout.addWidget(page_widget)
                complete_tab_widget = QFrame()
                complete_tab_widget.setLayout(complete_tab_layout)

                #for page in tab['history']:
                #    new_tab.load(QUrl(page['url']))
                #print tab['current_history']
                #for item in new_tab.history().items():
                #    print item
                #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history']))
                new_tab.load(QUrl(tab['history'][tab['current_history']]['url']))
                tab['current_history']
                self.tabs.setUpdatesEnabled(False)
                if self.new_tab_behavior == "insert":
                    self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget,
                                        unicode(new_tab.title()))
                elif self.new_tab_behavior == "append":
                    self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title()))
                self.tabs.setUpdatesEnabled(True)
                new_tab.titleChanged.connect(self.change_tab)
                new_tab.urlChanged.connect(self.change_tab)
                new_tab.loadStarted.connect(self.load_start)
                new_tab.loadFinished.connect(self.load_finish)
                new_tab.loadProgress.connect(self.pbar.setValue)
                new_tab.page().linkHovered.connect(self.linkHover)
                inspector.setPage(new_tab.page())

            for index, tab in enumerate(saved_tabs['tabs']):
                self.tabs.setTabText(index, tab['history'][tab['current_history']]['title'])

            self.tabs.setCurrentIndex(saved_tabs['current_tab'])
        else:
            self.new_tab()

        tabs_layout = QVBoxLayout()
        tabs_layout.setSpacing(0)
        tabs_layout.setContentsMargins(0, 0, 0, 0)
        tabs_layout.addWidget(self.tabs)

        self.tabs_widget = QFrame()
        self.tabs_widget.setObjectName("TabLine")
        self.tabs_widget.setStyleSheet(self.style_sheet)
        self.tabs_widget.setLayout(tabs_layout)
        self.tabs_widget.setVisible(True)

        # Webkit settings
        gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings()
        # Basic settings
        gsettings.setAttribute(QWebSettings.AutoLoadImages, True)
        gsettings.setAttribute(QWebSettings.JavascriptEnabled, True)
        gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False)
        gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False)
        gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present
        gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide
        gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled,
            True)
        # Performace settings
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True)
        gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        # Other settings
        gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False)

        # Create a vertical layout and add widgets
        vlayout = QVBoxLayout()
        vlayout.setSpacing(0)
        vlayout.setContentsMargins(0, 0, 0, 0)
        # toolbar.addWidget(self.input_widget)
        vlayout.addWidget(self.input_widget)
        vlayout.addWidget(self.bookmarks_widget)
        vlayout.addWidget(self.tabs_widget)

        # create a widget to hold the vertical layout
        wrapper_widget = QWidget()
        wrapper_widget.setLayout(vlayout)
        self.setCentralWidget(wrapper_widget)

        self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back)
        self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward)
        self.hbutton.clicked.connect(self.goHome)
        self.edit.returnPressed.connect(self.set_url)
        # Add button signal to "go" slot
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)
        self.dbutton.clicked.connect(self.bookmark)
        self.tbutton.clicked.connect(self.toggleTaskBar)
        self.nbutton.clicked.connect(self.new_tab)
        self.tabs.tabCloseRequested.connect(self.tabs.removeTab)
        self.tabs.currentChanged.connect(self.change_tab)

        widgets = (input_layout.itemAt(i).widget() for i in range(
            input_layout.count()))
        for widget in widgets:
            if isinstance(widget, QPushButton):
                widget.setFixedSize(33, 21)
                widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal))
                widget.pressed.connect(self.press_button)
                widget.released.connect(self.release_button)

        # make a ctrl+q quit
        sequence = QKeySequence(Qt.CTRL + Qt.Key_Q)
        QShortcut(sequence, self, SLOT("close()"))

        # make an accelerator to toggle fullscreen
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F)
        QShortcut(sequence, self, self.toggle_fullscreen)

        # make an accelerator to toggle input visibility
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L)
        QShortcut(sequence, self, self.toggle_input)

        # make an accelerator to focus adress-bar
        sequence = QKeySequence(Qt.CTRL + Qt.Key_L)
        QShortcut(sequence, self, self.focus_adress)

        # make an accelerator to reload page
        sequence = QKeySequence(Qt.CTRL + Qt.Key_R)
        QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)

        # make an accelerator to create new tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_T)
        QShortcut(sequence, self, self.new_tab)

        # make an accelerator to close tab
        sequence = QKeySequence(Qt.CTRL + Qt.Key_W)
        QShortcut(sequence, self, self.close_tab)

        # make an accelerator to navigate tabs
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left)
        QShortcut(sequence, self, self.previous_tab)
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right)
        QShortcut(sequence, self, self.next_tab)

        # make an accelerator to toggle inspector
        sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U)
        QShortcut(sequence, self, self.handleShowInspector)

        # make an accelerator to toggle bookmark
        sequence = QKeySequence(Qt.CTRL + Qt.Key_D)
        QShortcut(sequence, self, self.bookmark)

        # make an accelerator to toggle task/project-list
        sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L)
        QShortcut(sequence, self, self.toggleTaskBar)

        # finally set the attribute need to rotate
        # try:
        #     self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
        # except:
        #     print "not maemo"

        self.statusbar.show()

    def press_button(self):
        """On button press. Connected."""
        self.sender().setStyleSheet('background-color: rgba(228, 228, 228)')

    def release_button(self):
        """On button release. Connected."""
        self.sender().setStyleSheet('background-color: rgba(252, 252, 252)')

    def goHome(self):
        """Go to startpage."""
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setUrl(QUrl(self.startpage))

    def handleShowInspector(self):
        """Toggle web inspector."""
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).setShown(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden())

    def toggleTaskBar(self):
        """Toggle task bar."""
        if self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden():
            self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setModel(self.tasklist)
        self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setShown(self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden())
        #self.tasklist.setShown(self.tasklist.isHidden())

    def focus_adress(self):
        """Focus adress bar."""
        self.edit.selectAll()
        self.edit.setFocus()

    def toggle_input(self):
        """Toggle input visibility."""
        if self.input_widget.isVisible():
            visible = False
        else:
            visible = True
        self.input_widget.setVisible(visible)

    def toggle_fullscreen(self):
        """Toggle fullscreen."""
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()
        self.change_tab()

    def linkHover(self, l):
        """Show link adress in status bar on mouse hover."""
        self.statusbar.showMessage(l)

    def new_tab(self):
        """Open new tab."""
        tasklist = QTreeView()
        tasklist.hide()
        tasklist.setObjectName('taskList')
        tasklist.setMinimumWidth(100)
        tasklist.setMaximumWidth(250)

        new_tab = QWebView()
        new_tab.setObjectName('webView')

        inspector = QWebInspector(self)
        inspector.setObjectName('webInspector')
        inspector.hide()

        page_layout = QVBoxLayout()
        page_layout.setSpacing(0)
        page_layout.setContentsMargins(0, 0, 0, 0)
        page_layout.addWidget(new_tab)
        page_layout.addWidget(inspector)
        page_widget = QFrame()
        page_widget.setObjectName('pageWidget')
        page_widget.setLayout(page_layout)

        complete_tab_layout = QHBoxLayout()
        complete_tab_layout.setSpacing(0)
        complete_tab_layout.setContentsMargins(0, 0, 0, 0)
        complete_tab_layout.addWidget(tasklist)
        complete_tab_layout.addWidget(page_widget)
        complete_tab_widget = QFrame()
        complete_tab_widget.setLayout(complete_tab_layout)

        new_tab.load(QUrl(self.startpage))
        self.tabs.setUpdatesEnabled(False)
        if self.new_tab_behavior == "insert":
            self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget,
                                    unicode(new_tab.title()))
        elif self.new_tab_behavior == "append":
            self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title()))
        self.tabs.setCurrentWidget(complete_tab_widget)
        self.tabs.setTabText(self.tabs.currentIndex(),
                             unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title()))
        self.tabs.setUpdatesEnabled(True)
        # tab.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        # tab.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        new_tab.titleChanged.connect(self.change_tab)
        new_tab.urlChanged.connect(self.change_tab)
        new_tab.loadStarted.connect(self.load_start)
        new_tab.loadFinished.connect(self.load_finish)
        new_tab.loadProgress.connect(self.pbar.setValue)
        new_tab.page().linkHovered.connect(self.linkHover)
        inspector.setPage(new_tab.page())

    def change_tab(self):
        """Change active tab."""
        if self.tabs.count() <= 1:
            self.tabs.tabBar().hide()
        else:
            self.tabs.tabBar().show()

        try:
            self.edit.setText(str(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()))
            self.tabs.setTabText(self.tabs.currentIndex(),
                                 unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title()))
            self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus()
        except Exception:
            self.tabs.tabBar().hide()
            self.new_tab()

        #print (self.tabs.widget(self.tabs.currentIndex()).size().width()-10), self.tabs.count()
        self.tabs_widget.setStyleSheet(self.style_sheet +
                                       "QTabBar::tab { width:" + str(
                                        (self.tabs.widget(
                                            self.tabs.currentIndex()
                                            ).size().width()-26-self.tabs.count()*2)/self.tabs.count()
                                        ) + "px; }")

    def previous_tab(self):
        """Previous tab."""
        try:
            if self.tabs.currentIndex() > 0:
                self.tabs.setCurrentIndex(self.tabs.currentIndex()-1)
            else:
                self.tabs.setCurrentIndex(self.tabs.count()-1)

            self.change_tab()
        except Exception:
            pass

    def next_tab(self):
        """Next tab."""
        try:
            if self.tabs.currentIndex() < self.tabs.count()-1:
                self.tabs.setCurrentIndex(self.tabs.currentIndex()+1)
            else:
                self.tabs.setCurrentIndex(0)

            self.change_tab()
        except Exception: #, e
            pass

    def close_tab(self):
        """Close tab."""
        self.tabs.removeTab(self.tabs.currentIndex())

    def close(self):
        """Close app."""
        Qapplication.quit()

    def set_url(self):
        """Set url."""
        url = self.edit.text()
        # does the url start with http://?
        if "." not in url:
            url = "http://www.google.com/search?q="+url
        elif not url.startswith("http://"):
            url = "http://" + url
        qurl = QUrl(url)
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(qurl)
        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus()

    def load_start(self):
        """Update view values, called upon started page load."""
        self.rbutton.setText(u"╳")
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).stop)
        self.pbar.show()

    def load_finish(self):
        """Update view values, called upon finished page load."""
        if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoBack()):
            self.bbutton.setEnabled(True)
        else:
            self.bbutton.setEnabled(False)
        if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoForward()):
            self.fbutton.setEnabled(True)
        else:
            self.fbutton.setEnabled(False)

        self.rbutton.setText(u"↻")
        self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload)
        self.pbar.hide()

        global bookmarks
        if unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) in bookmarks:
            self.dbutton.setText(u"★")
        else:
            self.dbutton.setText(u"☆")

        if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden():
            self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).hide()
            self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).show()

    def bookmark(self):
        """Toggle bookmark."""
        global bookmarks
        if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded() in bookmarks:
            bookmarks.append(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())
            pickle.dump(bookmarks, open(bookFile, "wb"))
            link = QToolButton()
            link.setDefaultAction(QAction(unicode(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())), link))
            link.setObjectName(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()))
            link.setFont(QFont("Helvetica Neue", 11, QFont.Normal))
            link.clicked.connect(self.handleBookmarks)
            self.bookmarks_layout.addWidget(link)

            if self.bookmarks_widget.isHidden():
                self.bookmarks_widget.show()

            self.dbutton.setText(u"★")

        else:
            bookmarks.remove(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())
            pickle.dump(bookmarks, open(bookFile, "wb"))
            link = self.bookmarks_widget.findChild(QToolButton, unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()))
            self.bookmarks_layout.removeWidget(link)
            link.deleteLater()
            link = None

            if not bookmarks:
                self.bookmarks_widget.hide()

            self.dbutton.setText(u"☆")

    def handleBookmarks(self):

        self.gotoLink(self.sender().objectName())
        #self.gotoLink(unicode())

    def gotoLink(self, url):

        self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(QUrl(url))

    def styleSheet(self, style_sheet):
        """Load stylesheet."""
        try:
            with open(os.path.join
                      (basedir, 'assets', 'style.qss'), 'r') as file:
                return file.read()
        except Exception:
            # print e
            return ''

    def resizeEvent(self, evt=None):
        """Called on window resize."""
        self.change_tab()

    def myExitHandler(self):
        """Exiting."""
        pass
        global tabFile

    # {current_tab: 1, tabs:[0: {current_history:3, history:[{title, url}]]}
        pb = {'current_tab': self.tabs.currentIndex()}
        pb['tabs'] = list()
        for tab in range(self.tabs.count()):
            pb['tabs'].append(dict(current_history=self.tabs.widget(
                tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().currentItemIndex(), history=list(dict(
                    title=item.title(), url=item.url()
                    ) for item in self.tabs.widget(tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().items())))

        # print pb
        pickle.dump(pb, open(tabFile, "wb"))
Пример #60
0
class client(QMainWindow):   
    def __init__(self,parent= None):
#        QMainWindow.__init__(self)
        super(client, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.userModel = QStandardItemModel()
        self.itemHeadFriend=QStandardItem()
        self.itemHeadFriend.setData("linkMan",QtCore.Qt.DisplayRole)
        self.itemHeadStatis=QStandardItem()
        self.itemHeadStatis.setData("status",QtCore.Qt.DisplayRole)
        self.userModel.setHorizontalHeaderItem(0,self.itemHeadFriend)
        self.userModel.setHorizontalHeaderItem(1,self.itemHeadStatis)

                
        self.itemFriend=QStandardItem()
        self.itemFriend.setData("friend",QtCore.Qt.DisplayRole)
        self.userModel.insertRow(0,self.itemFriend)
        self.ui.linkManTreeView.setModel(self.userModel)

        self.connecting=None
        QtCore.QObject.connect(self.ui.linkManTreeView, QtCore.SIGNAL("clicked(QModelIndex)"), self,QtCore.SLOT("createMessageFrame(QModelIndex)"))
        self.messageFrame={}



    def addLinkMan(self,linkMan,status):
        '''添加联系人'''
        itemLinkMan=QStandardItem()
        itemLinkMan.setData(linkMan,QtCore.Qt.DisplayRole)
        itemLinkManStatus=QStandardItem()
        itemLinkManStatus.setData(status,QtCore.Qt.DisplayRole)

        self.itemFriend.appendRow([itemLinkMan,itemLinkManStatus])

    def createTempMessageFrame(self,user,friend):
        uiDebug(self.messageFrame)
        if self.messageFrame.has_key(friend):
            self.messageFrame[friend].show()
        else:    
            try:        
                frame = messageWin(self,user,friend)
                frame.setWindowTitle(friend)
                self.messageFrame[friend]=frame
                frame.show()
                #pylint: disable=W0702 
            except:
                pass
        
        uiDebug("mainPanelUi createMessageFrame()")
        
    
    def createMessageFrame(self,QModelIndex):
        '''创建对话窗口'''
        friend= self.userModel.data(QModelIndex)

        if self.userModel.indexFromItem(self.itemFriend) == QModelIndex:
            return
        
        if friend == "":
            return
        
        if friend == "inline":
            return
        
        uiDebug(self.messageFrame)
        if self.messageFrame.has_key(friend):
            self.messageFrame[friend].show()
        else:    
            try:        
                frame = messageWin(self,self.user,friend)
                frame.setWindowTitle(friend)
                self.messageFrame[friend]=frame
                frame.show()
                #pylint: disable=W0702 
            except:
                pass
        
        uiDebug("mainPanelUi createMessageFrame()")