예제 #1
0
 def init_notebooks(self):
     frame = QFrame()
     layout = QVBoxLayout()
     frame.setLayout(layout)
     self.ui.scrollArea.setWidget(frame)
     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)
         widget = QWidget()
         menu = QMenu(self)
         menu.addAction(self.tr('Change Name'), Slot()(partial(
             self.change_notebook, notebook=notebook,
         )))
         action = menu.addAction(self.tr('Remove Notebook'), Slot()(partial(
             self.remove_notebook, notebook=notebook,
         )))
         action.setEnabled(False)
         widget.ui = Ui_Notebook()
         widget.ui.setupUi(widget)
         widget.ui.name.setText(notebook.name)
         widget.ui.content.setText(self.tr('Containts %d notes') % count)
         widget.ui.actionBtn.setIcon(QIcon.fromTheme('gtk-properties'))
         widget.setFixedHeight(50)
         layout.addWidget(widget)
         widget.ui.actionBtn.clicked.connect(Slot()(partial(
             self.show_notebook_menu,
             menu=menu, widget=widget,
         )))
예제 #2
0
    def createDisplayFields(self):
        display_widget = QFrame()
        display_widget.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
        self.left_layout.addWidget(display_widget)
        self.display_layout = QHBoxLayout()

        # self.turn = self.transcript.current_turn()
        self.time_field = qHotField("time", str, "00:00:00", min_size=75, max_size=75, pos="top", handler=self.update_time)
        self.display_layout.addWidget(self.time_field)
        self.speaker_field = qHotField("speaker", str, " ", min_size=75, max_size=75, pos="top", handler=self.update_speaker)
        self.display_layout.addWidget(self.speaker_field)
        self.utt_field = qHotField("utterance", str, " ", min_size=350, max_size=500, pos="top", handler=self.update_utterance, multiline=True)
        self.utt_field.setStyleSheet("font: 14pt \"Courier\";")
        # self.utt_field.efield.setFont(QFont('SansSerif', 12))
        self.display_layout.addWidget(self.utt_field)

        display_widget.setLayout(self.display_layout)
        self.display_layout.setStretchFactor(self.speaker_field, 0)
        self.display_layout.setStretchFactor(self.utt_field, 1)

        self.transcript_slider = QSlider(QtCore.Qt.Horizontal, self)
        self.display_layout.addWidget(self.transcript_slider)
        self.transcript_slider.setMaximum(100)
        self.connect(self.transcript_slider,
                     QtCore.SIGNAL("sliderMoved(int)"), self.position_transcript)
        self.left_layout.addWidget(self.transcript_slider)
예제 #3
0
    def _init_load_options_tab(self, tab):

        # auto load libs

        auto_load_libs = QCheckBox(self)
        auto_load_libs.setText("Automatically load all libraries")
        auto_load_libs.setChecked(False)
        self.option_widgets['auto_load_libs'] = auto_load_libs

        # dependencies list

        dep_group = QGroupBox("Dependencies")
        dep_list = QListWidget(self)
        self.option_widgets['dep_list'] = dep_list

        sublayout = QVBoxLayout()
        sublayout.addWidget(dep_list)
        dep_group.setLayout(sublayout)

        layout = QVBoxLayout()
        layout.addWidget(auto_load_libs)
        layout.addWidget(dep_group)
        layout.addStretch(0)

        frame = QFrame(self)
        frame.setLayout(layout)
        tab.addTab(frame, "Loading Options")
예제 #4
0
 def BorderBox(self, layout):
     from PySide.QtGui import QFrame
     toto = QFrame()
     toto.setLayout(layout)
     toto.setFrameShape(QFrame.Box)
     toto.setFrameShadow(QFrame.Sunken)
     return toto        
예제 #5
0
 def __init__(self, sync_manager, network_access_manager, url=None, username=None, password=None, certificate=""):
     self.sync_manager = sync_manager
     self.nam = network_access_manager
     self.certificate = certificate
     self.replies = set()
     super(SettingsWindow, self).__init__()
     self.setWindowIcon(QIcon(os.path.join('icons', 'Logo_sync.png')))
     self.setGeometry(70, 60, 300, 250)
     self.setWindowTitle("c't SESAM Sync Settings")
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     layout.setContentsMargins(0, 0, 0, 0)
     # Header bar
     header_bar = QFrame()
     header_bar.setStyleSheet("QWidget { background: rgb(40, 40, 40); } " +
                              "QToolButton { background: rgb(40, 40, 40); }" +
                              "QToolTip { color: rgb(255, 255, 255); background-color: rgb(20, 20, 20); " +
                              "border: 1px solid white; }")
     header_bar.setAutoFillBackground(True)
     header_bar.setFixedHeight(45)
     header_bar_layout = QBoxLayout(QBoxLayout.RightToLeft)
     header_bar_layout.addStretch()
     header_bar.setLayout(header_bar_layout)
     layout.addWidget(header_bar)
     self.create_header_bar(header_bar_layout)
     self.certificate_loaded.connect(self.test_connection)
     # Main area
     main_area = QFrame()
     main_layout = QBoxLayout(QBoxLayout.TopToBottom)
     main_area.setLayout(main_layout)
     layout.addWidget(main_area)
     self.create_main_area(main_layout, url, username, password)
     # Show the window
     layout.addStretch()
     self.setLayout(layout)
     self.show()
    def _init_widgets(self):

        state = self._state

        if state is None:
            return

        if state.arch.name not in self.ARCH_REGISTERS:
            l.error(
                "Architecture %s is not listed in QRegisterViewer.ARCH_REGISTERS.",
                state.arch.name)
            return

        layout = QVBoxLayout()
        area = QScrollArea()
        area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        area.setWidgetResizable(True)

        regs = self.ARCH_REGISTERS[state.arch.name]

        # common ones
        common_regs = regs['common']

        for reg_name in common_regs:
            sublayout = QHBoxLayout()

            lbl_reg_name = QLabel(self)
            lbl_reg_name.setProperty('class', 'reg_viewer_label')
            lbl_reg_name.setText(reg_name)
            lbl_reg_name.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            sublayout.addWidget(lbl_reg_name)

            sublayout.addSpacing(10)
            reg_value = QASTViewer(None, parent=self)
            self._registers[reg_name] = reg_value
            sublayout.addWidget(reg_value)

            layout.addLayout(sublayout)

        layout.setSpacing(0)
        layout.addStretch(0)
        layout.setContentsMargins(2, 2, 2, 2)

        # the container
        container = QFrame()
        container.setAutoFillBackground(True)
        palette = container.palette()
        palette.setColor(container.backgroundRole(), Qt.white)
        container.setPalette(palette)
        container.setLayout(layout)

        area.setWidget(container)

        base_layout = QVBoxLayout()
        base_layout.addWidget(area)
        self.setLayout(base_layout)
예제 #7
0
    def _init_pathgroups_tab(self, tab):

        # pathgroups list

        pathgroups_label = QLabel(self)
        pathgroups_label.setText('PathGroup')

        pathgroups_list = QComboBox(self)
        self._pathgroups_list = pathgroups_list

        pg_layout = QHBoxLayout()
        pg_layout.addWidget(pathgroups_label)
        pg_layout.addWidget(pathgroups_list)

        # path group information
        viewer = QPathGroupViewer(None)
        self._pathgroup_viewer = viewer

        #
        # Buttons
        #

        # step button
        step_button = QPushButton()
        step_button.setText('Step Path Group')
        step_button.released.connect(self._on_step_clicked)

        # step until branch
        step_until_branch_button = QPushButton('Step Path Group until branch')
        step_until_branch_button.released.connect(
            self._on_step_until_branch_clicked)

        # explore button
        explore_button = QPushButton('Explore')
        explore_button.released.connect(self._on_explore_clicked)

        # buttons layout
        buttons_layout = QVBoxLayout()
        layout = QHBoxLayout()
        layout.addWidget(explore_button)
        buttons_layout.addLayout(layout)

        layout = QHBoxLayout()
        layout.addWidget(step_button)
        layout.addWidget(step_until_branch_button)
        buttons_layout.addLayout(layout)

        pathgroups_layout = QVBoxLayout()
        pathgroups_layout.addLayout(pg_layout)
        pathgroups_layout.addWidget(viewer)
        pathgroups_layout.addLayout(buttons_layout)

        frame = QFrame()
        frame.setLayout(pathgroups_layout)

        tab.addTab(frame, 'General')
예제 #8
0
    def _init_avoids_tab(self, tab):

        avoids_list = QListWidget()
        self._avoids_list = avoids_list

        layout = QVBoxLayout()
        layout.addWidget(avoids_list)

        frame = QFrame()
        frame.setLayout(layout)

        tab.addTab(frame, 'Avoids')
예제 #9
0
    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())
예제 #10
0
    def _init_settings_tab(self, tab):

        oneactive_checkbox = QCheckBox("Keep at most one active path")
        oneactive_checkbox.setChecked(False)
        self._oneactive_checkbox = oneactive_checkbox

        settings_layout = QVBoxLayout()
        settings_layout.addWidget(oneactive_checkbox)
        settings_layout.addStretch(0)

        frame = QFrame()
        frame.setLayout(settings_layout)

        tab.addTab(frame, 'Settings')
예제 #11
0
    def setupUI(self):

        paneLayout = QHBoxLayout()
        paneLayout.setContentsMargins(0, 0, 0, 0)

        leftPane = QFrame()
        leftPane.setObjectName("leftPane")

        leftPaneLayout = QVBoxLayout()
        leftPaneLayout.setContentsMargins(20, 20, 20, 10)
        heading = QLabel("Select Employee: ")
        heading.setObjectName("heading")
        leftPaneLayout.addWidget(heading)
        leftPaneLayout.addSpacing(10)

        form1 = QFormLayout()
        form1.addRow(QLabel("Name"), self.nameSearch)
        form1.addRow(QLabel("ID No."), self.id)
        leftPaneLayout.addLayout(form1)
        leftPaneLayout.addStretch()
        leftPane.setLayout(leftPaneLayout)

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)

        editGroup = QGroupBox("Edit below")
        form = QFormLayout()
        form.setContentsMargins(10, 10, 10, 30)
        form.setSpacing(20)
        form.addRow(QLabel("Name"), self.nameEdit)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)
        editGroup.setLayout(form)

        layout.addWidget(editGroup)
        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnSave)

        layout.addLayout(bttnLayout)

        paneLayout.addWidget(leftPane)
        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
예제 #12
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.nam = QNetworkAccessManager()
     self.setWindowIcon(QIcon(os.path.join('icons', 'Logo_rendered_edited.png')))
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     layout.setContentsMargins(0, 0, 0, 0)
     self.preference_manager = PreferenceManager()
     self.kgk_manager = KgkManager()
     self.kgk_manager.set_preference_manager(self.preference_manager)
     self.settings_manager = PasswordSettingsManager(self.preference_manager)
     self.setting_dirty = True
     # Header bar
     header_bar = QFrame()
     header_bar.setStyleSheet(
         "QWidget { background: rgb(40, 40, 40); } " +
         "QToolButton { background: rgb(40, 40, 40); }" +
         "QToolTip { color: rgb(255, 255, 255); background-color: rgb(20, 20, 20); " +
         "border: 1px solid white; }")
     header_bar.setAutoFillBackground(True)
     header_bar.setFixedHeight(45)
     header_bar_layout = QBoxLayout(QBoxLayout.LeftToRight)
     header_bar_layout.addStretch()
     header_bar.setLayout(header_bar_layout)
     layout.addWidget(header_bar)
     self.create_header_bar(header_bar_layout)
     # Widget area
     main_area = QFrame()
     main_layout = QBoxLayout(QBoxLayout.TopToBottom)
     main_area.setLayout(main_layout)
     layout.addWidget(main_area)
     self.create_main_area(main_layout)
     # Window layout
     layout.addStretch()
     main_layout.addStretch()
     self.setLayout(layout)
     settings = QSettings()
     size = settings.value("MainWindow/size")
     if not size:
         size = QSize(350, 450)
     self.resize(size)
     position = settings.value("MainWindow/pos")
     if not position:
         position = QPoint(0, 24)
     self.move(position)
     self.setWindowTitle("c't SESAM")
     self.master_password_edit.setFocus()
     self.show()
예제 #13
0
 def __init__(self, parent, app, widget, on_change):
     """Init and connect signals"""
     self.parent = parent
     self.app = app
     self.widget = widget
     self.note = None
     self.on_change = on_change
     self._resource_labels = {}
     self._resources = []
     self._res_hash = {}
     frame = QFrame()
     frame.setLayout(QVBoxLayout())
     frame.setFixedWidth(100)
     self.widget.setFixedWidth(100)
     self.widget.setWidget(frame)
     self.widget.hide()
     self.mime = magic.open(magic.MIME_TYPE)
     self.mime.load()
예제 #14
0
    def init_msh_ui(self):
        comps = QGroupBox('Components')

        mdlgr = QGroupBox('Models - {0}'.format(self.mdlmanager.count()))
        mdllay = QVBoxLayout()
        mdllay.addWidget(self.mdlmanager.get_frame())
        #mdllay.addStretch()
        mdlgr.setLayout(mdllay)
        matgr = QGroupBox('Materials - {0}'.format(self.matmanager.count()))
        matlay = QVBoxLayout()
        matlay.addWidget(self.matmanager.get_frame())
        #matlay.addStretch()
        matgr.setLayout(matlay)
        frame2lay = QHBoxLayout()
        frame2lay.addWidget(matgr)
        frame2lay.addWidget(mdlgr)
        comps.setLayout(frame2lay)

        # Misc stuff.
        self.setGeometry(200, 100, WIDTH_MSH, HEIGHT_MSH)
        frame = QFrame()
        framelay = QVBoxLayout()
        framelay.addWidget(self.infomanager.get_frame())
        framelay.addWidget(comps)
        #framelay.addStretch()

        load = QPushButton('Open')
        load.clicked.connect(self.load_msh)
        save = QPushButton('Save')
        save.clicked.connect(self.save)
        close = QPushButton('Close')
        close.clicked.connect(self.close)
        btnlay = QHBoxLayout()
        btnlay.addWidget(QLabel('<b>MSH Suite</b> Version {0}'.format(SUITE_VER)))
        btnlay.addStretch()
        btnlay.addWidget(load)
        btnlay.addWidget(save)
        btnlay.addWidget(close)

        framelay.addLayout(btnlay)
        frame.setLayout(framelay)

        self.setCentralWidget(frame)
        self.setWindowTitle('MSH Suite - {0}'.format(self.msh.info.name))
예제 #15
0
    def _init_cfg_options_tab(self, tab):
        resolve_indirect_jumps = QCheckBox(self)
        resolve_indirect_jumps.setText('Resolve indirect jumps')
        resolve_indirect_jumps.setChecked(True)
        self.option_widgets['resolve_indirect_jumps'] = resolve_indirect_jumps

        collect_data_refs = QCheckBox(self)
        collect_data_refs.setText(
            'Collect cross-references and infer data types')
        collect_data_refs.setChecked(True)
        self.option_widgets['collect_data_refs'] = collect_data_refs

        layout = QVBoxLayout()
        layout.addWidget(resolve_indirect_jumps)
        layout.addWidget(collect_data_refs)
        layout.addStretch(0)
        frame = QFrame(self)
        frame.setLayout(layout)
        tab.addTab(frame, 'CFG Options')
예제 #16
0
파일: view.py 프로젝트: summonersRift/rubik
def _view_server(kwargs, queue):
    from PySide.QtGui import QApplication, QMainWindow, QFrame, QGridLayout
    from RubikView import RubikView

    # Grab the partition to view from the queue.
    app = QApplication(sys.argv)

    frame = QFrame()
    layout = QGridLayout()
    frame.setLayout(layout)

    mainwindow = QMainWindow()
    mainwindow.setCentralWidget(frame)
    mainwindow.resize(1024, 768)
    mainwindow.move(30, 30)

    # Find next highest square number and fill within that shape
    partitions = queue.get()
    side = math.ceil(math.sqrt(len(partitions)))
    aspect = (side, side)

    views = []
    for i, partition in enumerate(partitions):
        rview = RubikView(mainwindow)
        if "renderer" in kwargs:
            rview.set_face_renderer(kwargs["renderer"])
        else:
            rview.set_face_renderer(colored_face_renderer(**kwargs))

        rview.set_partition(partition)

        r, c = np.unravel_index(i, aspect)
        layout.addWidget(rview, r, c)
        views.append(rview)

    mainwindow.show()
    mainwindow.raise_()

    rotation = kwargs.get("rotation", (45, 3, 3, 1))
    for rview in views:
        rview.set_rotation_quaternion(*rotation)

    app.exec_()
    def _load_tmps(self):

        state = self._state

        layout = QVBoxLayout()

        self._tmps.clear()
        if state is None:
            tmps = {}
        else:
            tmps = state.scratch.temps

        # tmps
        for tmp_id, tmp_value in tmps.iteritems():
            sublayout = QHBoxLayout()

            lbl_tmp_name = QLabel(self)
            lbl_tmp_name.setProperty('class', 'reg_viewer_label')
            lbl_tmp_name.setText("tmp_%d" % tmp_id)
            lbl_tmp_name.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            sublayout.addWidget(lbl_tmp_name)

            sublayout.addSpacing(10)

            tmp_viewer = QASTViewer(tmp_value, parent=self)
            self._tmps[tmp_id] = tmp_viewer
            sublayout.addWidget(tmp_viewer)

            layout.addLayout(sublayout)

        layout.setSpacing(0)
        layout.addStretch(0)
        layout.setContentsMargins(2, 2, 2, 2)

        # the container
        container = QFrame()
        container.setAutoFillBackground(True)
        palette = container.palette()
        palette.setColor(container.backgroundRole(), Qt.white)
        container.setPalette(palette)
        container.setLayout(layout)

        self._area.setWidget(container)
예제 #18
0
파일: view.py 프로젝트: IanLee1521/rubik
def _view_server(kwargs, queue):
    from PySide.QtGui import QApplication, QMainWindow, QFrame, QGridLayout
    from RubikView import RubikView

    # Grab the partition to view from the queue.
    app = QApplication(sys.argv)

    frame = QFrame()
    layout = QGridLayout()
    frame.setLayout(layout)

    mainwindow = QMainWindow()
    mainwindow.setCentralWidget(frame)
    mainwindow.resize(1024, 768)
    mainwindow.move(30, 30)

    # Find next highest square number and fill within that shape
    partitions = queue.get()
    side = math.ceil(math.sqrt(len(partitions)))
    aspect = (side, side)

    views = []
    for i, partition in enumerate(partitions):
        rview = RubikView(mainwindow)
        if "renderer" in kwargs:
            rview.set_face_renderer(kwargs["renderer"])
        else:
            rview.set_face_renderer(colored_face_renderer(**kwargs))

        rview.set_partition(partition)

        r, c = np.unravel_index(i, aspect)
        layout.addWidget(rview, r, c)
        views.append(rview)

    mainwindow.show()
    mainwindow.raise_()

    rotation = kwargs.get("rotation", (45, 3, 3, 1))
    for rview in views:
        rview.set_rotation_quaternion(*rotation)

    app.exec_()
예제 #19
0
 def __init__(self,
              sync_manager,
              network_access_manager,
              url=None,
              username=None,
              password=None,
              certificate=""):
     self.sync_manager = sync_manager
     self.nam = network_access_manager
     self.certificate = certificate
     self.replies = set()
     super(SettingsWindow, self).__init__()
     self.setWindowIcon(QIcon(os.path.join('icons', 'Logo_sync.png')))
     self.setGeometry(70, 60, 300, 250)
     self.setWindowTitle("c't SESAM Sync Settings")
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     layout.setContentsMargins(0, 0, 0, 0)
     # Header bar
     header_bar = QFrame()
     header_bar.setStyleSheet(
         "QWidget { background: rgb(40, 40, 40); } " +
         "QToolButton { background: rgb(40, 40, 40); }" +
         "QToolTip { color: rgb(255, 255, 255); background-color: rgb(20, 20, 20); "
         + "border: 1px solid white; }")
     header_bar.setAutoFillBackground(True)
     header_bar.setFixedHeight(45)
     header_bar_layout = QBoxLayout(QBoxLayout.RightToLeft)
     header_bar_layout.addStretch()
     header_bar.setLayout(header_bar_layout)
     layout.addWidget(header_bar)
     self.create_header_bar(header_bar_layout)
     self.certificate_loaded.connect(self.test_connection)
     # Main area
     main_area = QFrame()
     main_layout = QBoxLayout(QBoxLayout.TopToBottom)
     main_area.setLayout(main_layout)
     layout.addWidget(main_area)
     self.create_main_area(main_layout, url, username, password)
     # Show the window
     layout.addStretch()
     self.setLayout(layout)
     self.show()
예제 #20
0
    def _load_memory_widgets(self):

        state = self._state

        COLUMNS = 16
        ROWS = 10

        layout = QVBoxLayout()

        addr_base = self.addr

        for row in xrange(ROWS):

            row_layout = QHBoxLayout()

            col = 0

            addr = addr_base + row * COLUMNS
            addr_label = QLabel("%x" % addr)
            addr_label.setProperty("class", "memory_viewer_address")
            row_layout.addWidget(addr_label)

            while col < COLUMNS:
                addr = addr_base + row * COLUMNS + col
                data = state.memory.load(addr, 1)

                ast_viewer = QASTViewer(data,
                                        display_size=False,
                                        byte_format="%02x")

                row_layout.addWidget(ast_viewer)

                col += 1
            row_layout.addStretch(0)

            layout.addLayout(row_layout)

        container = QFrame()
        container.setLayout(layout)
        self._scrollarea.setWidget(container)
예제 #21
0
    def initUI(self):
        open_msh_btn = QPushButton('Open .MSH...')
        open_msh_btn.clicked.connect(self.load_msh)
        open_msh_btn.setToolTip('<b>Loads a .MSH file</b> for editing.')
        dump_msh_btn = QPushButton('Dump .MSH...')
        dump_msh_btn.clicked.connect(self.dump_msh)
        dump_msh_btn.setToolTip('<b>Dumps .MSH file information</b> into a text file.')
        munge_anim_btn = QPushButton('Munge Animation')
        munge_anim_btn.clicked.connect(self.munge_anim)
        munge_anim_btn.setToolTip('<b>Launches the AnimMunger.</b>')
        buttonslay = QGridLayout()
        buttonslay.addWidget(open_msh_btn, 1, 1)
        buttonslay.addWidget(dump_msh_btn, 1, 3)
        buttonslay.addWidget(munge_anim_btn, 3, 1)

        frame = QFrame()
        frame.setLayout(buttonslay)
        self.setCentralWidget(frame)

        self.setGeometry(200, 100, WIDTH_LAUNCH, HEIGHT_LAUNCH)
        self.setWindowTitle('MSH Suite')
        self.show()
예제 #22
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.clip_filename = None
     self.audio_filename = None
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     clip_row = QBoxLayout(QBoxLayout.LeftToRight)
     self.clip_button = QPushButton()
     self.clip_button.clicked.connect(self.open_clip)
     self.clip_button.setText(self.tr("Open clip"))
     clip_row.addWidget(self.clip_button)
     self.clip_view = QLabel()
     clip_row.addWidget(self.clip_view)
     clip_frame = QFrame()
     clip_frame.setLayout(clip_row)
     layout.addWidget(clip_frame)
     audio_row = QBoxLayout(QBoxLayout.LeftToRight)
     self.audio_button = QPushButton()
     self.audio_button.clicked.connect(self.open_audio)
     self.audio_button.setText(self.tr("Open audio"))
     audio_row.addWidget(self.audio_button)
     self.audio_view = QLabel()
     audio_row.addWidget(self.audio_view)
     audio_frame = QFrame()
     audio_frame.setLayout(audio_row)
     layout.addWidget(audio_frame)
     save_row = QBoxLayout(QBoxLayout.LeftToRight)
     self.save_button = QPushButton()
     self.save_button.clicked.connect(self.save)
     self.save_button.setText(self.tr("Save synced clip"))
     save_row.addWidget(self.save_button)
     save_frame = QFrame()
     save_frame.setLayout(save_row)
     layout.addWidget(save_frame)
     self.update_save_button()
     layout.addStretch()
     self.setLayout(layout)
     self.show()
예제 #23
0
파일: gui.py 프로젝트: pinae/Audiosyncer
 def __init__(self):
     super(MainWindow, self).__init__()
     self.clip_filename = None
     self.audio_filename = None
     layout = QBoxLayout(QBoxLayout.TopToBottom)
     clip_row = QBoxLayout(QBoxLayout.LeftToRight)
     self.clip_button = QPushButton()
     self.clip_button.clicked.connect(self.open_clip)
     self.clip_button.setText(self.tr("Open clip"))
     clip_row.addWidget(self.clip_button)
     self.clip_view = QLabel()
     clip_row.addWidget(self.clip_view)
     clip_frame = QFrame()
     clip_frame.setLayout(clip_row)
     layout.addWidget(clip_frame)
     audio_row = QBoxLayout(QBoxLayout.LeftToRight)
     self.audio_button = QPushButton()
     self.audio_button.clicked.connect(self.open_audio)
     self.audio_button.setText(self.tr("Open audio"))
     audio_row.addWidget(self.audio_button)
     self.audio_view = QLabel()
     audio_row.addWidget(self.audio_view)
     audio_frame = QFrame()
     audio_frame.setLayout(audio_row)
     layout.addWidget(audio_frame)
     save_row = QBoxLayout(QBoxLayout.LeftToRight)
     self.save_button = QPushButton()
     self.save_button.clicked.connect(self.save)
     self.save_button.setText(self.tr("Save synced clip"))
     save_row.addWidget(self.save_button)
     save_frame = QFrame()
     save_frame.setLayout(save_row)
     layout.addWidget(save_frame)
     self.update_save_button()
     layout.addStretch()
     self.setLayout(layout)
     self.show()
class SubtransactionForm:
    """ Represents the SubTransaction Form """
    
    def __init__(self, parent):
        """ Initialize the Subtransaction Form """
        self.parent = parent
        self.subtransactionTable = SubTransactionTableWidget(self.transaction, self)
        self.subtransactionLabels = []
    
    def setup(self):
        """ Setup the Subtransactions for the Transaction Details """
        self.subtransactionFrame = QFrame()
        
        self.verticalLayout = QVBoxLayout(self.subtransactionFrame)
        self.horizontalLayout = QHBoxLayout()
        
        label = QLabel("<b>Subtransactions</b>")
        self.horizontalLayout.addWidget(label)
        
        button = QPushButton("Add New Subtransaction")
        button.clicked.connect(self.addSubtransaction)
        self.horizontalLayout.addWidget(button)
        
        self.removeButton = QPushButton("Remove Subtransaction")
        self.removeButton.clicked.connect(self.removeSubtransaction)
        self.horizontalLayout.addWidget(self.removeButton)
        self.removeButton.setEnabled(False)
        
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addWidget(self.subtransactionTable)
        self.verticalLayout.addStretch()
        
        self.subtransactionFrame.setLayout(self.verticalLayout)
        self.layout.addWidget(self.subtransactionFrame)
        
    def addSubtransactionLabels(self):
        """ Add Subtransaction Labels """
        self.subtransactionLabels = []
        if self.transaction is not None and self.transaction.subtransaction_set is not None:
            for transaction in self.transaction.subtransaction_set.transactions:
                if transaction is not self.transaction:
                    label = QLabel("{0}".format(transaction.description))
                    self.subtransactionLabels.append(label)
                    self.formLayout.insertRow(1, label)
        
    def updateOnTransactionChange(self):
        """ Update on a Transaction Change """
        self.subtransactionTable.parent_transaction = self.transaction
        self.subtransactionTable.updateTransactions()
        
    def tabSelected(self):
        """ Do nothing when selected """
            
    def addSubtransaction(self, checked=False):
        """ Add the new Subtransaction """
        if self.transaction is not None:
            transaction = CreateSubtransactionFromRelative(self.transaction)
            
            TheBalanceHelper.setupBalancesForAccount(transaction.account)
            self.subtransactionTable.updateTransactions()
            if transaction.account is self.table.account:
                self.table.insertRow(transaction, selectRow=False)
                
    def removeSubtransaction(self, checked=False):
        """ Remove the current Subtransaction """
        subtransaction = self.subtransactionTable.currentSubtransaction
        if subtransaction is not None:
            subtransactionSet = subtransaction.subtransaction_set
            if len(subtransactionSet.transactions) == 2:
                SubtransactionSets.delete(subtransactionSet)
            else:
                subtransactionSet.transactions.remove(subtransaction)
                SubtransactionSets.save()
            
            row = self.subtransactionTable.currentRow()
            self.subtransactionTable.removeRow(row)
            
    def updateSubtransactionDetails(self):
        """ Update the Form's Subtransaction Details """
        subtransaction = self.subtransactionTable.currentSubtransaction
        self.removeButton.setEnabled(subtransaction is not None)
    
    @property
    def layout(self):
        return self.parent.layout
        
    @property
    def table(self):
        return self.parent.table
        
    @property
    def transaction(self):
        return self.parent.transaction
예제 #25
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"))
예제 #26
0
    def setupUI(self):
        """Arranges GUI elements inside the widget properly"""

        paneLayout = QHBoxLayout()
        paneLayout.setContentsMargins(0, 0, 0, 0)

        leftPane = QFrame()
        leftPane.setObjectName("leftPane")

        leftPaneLayout = QVBoxLayout()
        leftPaneLayout.setContentsMargins(20, 20, 20, 10)
        heading = QLabel("Select Employee: ")
        heading.setObjectName("heading")
        leftPaneLayout.addWidget(heading)
        leftPaneLayout.addSpacing(10)

        datelayout = QHBoxLayout()
        datelayout.addWidget(QLabel("Salary for month of "))
        datelayout.addWidget(self.month)
        datelayout.addWidget(self.year)
        datelayout.addStretch()
        leftPaneLayout.addLayout(datelayout)

        leftForm = QFormLayout()
        leftForm.setSpacing(10)
        leftForm.addRow(QLabel("Name"), self.name)
        leftForm.addRow(QLabel("ID No."), self.id)
        leftPaneLayout.addLayout(leftForm)

        leftPaneLayout.addStretch()
        leftPane.setLayout(leftPaneLayout)
        paneLayout.addWidget(leftPane)

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)
        form = QFormLayout()
        form.setSpacing(10)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)

        infoGroup = QGroupBox("Basic Info")
        infoGroup.setLayout(form)
        layout.addWidget(infoGroup)

        leftForm = QFormLayout()
        leftForm.addRow(QLabel("Dearness Allowance"), self.da_percent)
        leftForm.addRow(QLabel("Housing Rent Allowance"), self.hra_percent)
        leftForm.addRow(QLabel("Transport Allowance"), self.ta_percent)

        leftGroup = QGroupBox("Allowances")
        leftGroup.setLayout(leftForm)

        rightForm = QFormLayout()
        rightForm.addRow(QLabel("Income Tax"), self.it_percent)
        rightForm.addRow(QLabel("Profession Tax"), self.pt_percent)

        rightGroup = QGroupBox("Deductions")
        rightGroup.setLayout(rightForm)

        table = QHBoxLayout()
        table.addWidget(leftGroup)
        table.addWidget(rightGroup)

        layout.addLayout(table)

        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnCalculate)

        layout.addLayout(bttnLayout)

        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
예제 #27
0
class CommentsWidget(QWidget):
    def _append_comment(self, comment):
        l = QLabel(comment.text)
        l.setWordWrap(True)
        l.setStyleSheet("background-color: #ffffff;")
        # l.setTextInteractionFlags(Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard | Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard)

        self._comments_layout.addWidget(l)

        l = QLabel("Chuck Norris, 14/4/2016")
        l.setStyleSheet("color: #808080;")
        self._comments_layout.addWidget(l)
        self._comments_layout.setAlignment(l, Qt.AlignRight)
        self.comments_list_widget.setVisible(True)

    def show_comments(self, comments):

        self._comments = comments or []

        while self._comments_layout.count() > 0:
            self._comments_layout.removeItem(0)

        for comment in comments:
            self._append_comment(comment)

        self.comments_list_widget.setVisible(len(self._comments) > 0)

    @Slot()
    def submit_comment(self):
        comment = self.text_edit.toPlainText().strip()

        if comment:

            c = self._change_tracker.make_change_tracking_dto(Comment)
            c.text = comment
            self._append_comment(c)
            self.text_edit.setText("")

    def __init__(self, parent, change_tracker: ChangeTracker):
        super(CommentsWidget, self).__init__(parent)

        self._change_tracker = change_tracker
        #self.setObjectName("zwhite")
        layout = QVBoxLayout()

        self.comments_list_widget = QFrame(
            self
        )  # If you use QWidget, the background won't be set; don't know why :-(
        self.comments_list_widget.setStyleSheet("background: white;")
        self.comments_list_widget.setAutoFillBackground(True)
        #self.comments_list_widget.setObjectName("zwhite")

        self._comments_layout = QVBoxLayout()
        self.comments_list_widget.setLayout(self._comments_layout)

        self.comments_list_widget.hide()

        self.text_edit = QTextEdit(self)
        self.submit_button = QPushButton(("Add"), self)

        layout.addWidget(self.comments_list_widget)
        layout.addWidget(self.text_edit)
        hlayout = QHBoxLayout()

        hlayout.addStretch()
        hlayout.addWidget(self.submit_button)
        layout.addLayout(hlayout)
        self.setLayout(layout)

        self.submit_button.clicked.connect(self.submit_comment)
예제 #28
0
파일: gui05.py 프로젝트: yysynergy/pparser
class MainWindow(QMainWindow):
    def __init__(self, datta):
        QMainWindow.__init__(self)
        self.setWindowTitle('Project Parser')
        appIcon = QIcon('search.png')
        self.setWindowIcon(appIcon)
        self.viewPortBL = QDesktopWidget().availableGeometry().topLeft()
        self.viewPortTR = QDesktopWidget().availableGeometry().bottomRight()
        self.margin = int(QDesktopWidget().availableGeometry().width()*0.1/2)
        self.shirina = QDesktopWidget().availableGeometry().width() - self.margin*2
        self.visota = QDesktopWidget().availableGeometry().height() - self.margin*2
        self.setGeometry(self.viewPortBL.x() + self.margin, self.viewPortBL.y() + self.margin,
                         self.shirina, self.visota)
        # statusbar
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        
        #lower long layout
        self.lowerLong = QFrame()
        self.detailsLabel = QLabel()
        self.skillsLabel = QLabel()
        self.urlLabel = QLabel()
        self.locationLabel = QLabel()
        self.skillsLabel.setText('skills')
        self.detailsLabel.setWordWrap(True)
        self.la = QVBoxLayout()
        self.la.addWidget(self.detailsLabel)
        self.la.addWidget(self.skillsLabel)
        self.la.addWidget(self.urlLabel)
        self.la.addWidget(self.locationLabel)
        self.lowerLong.setLayout(self.la)

        # table
        self.source_model = MyTableModel(self, datta, ['Id', 'Date', 'Title'])
        self.proxy_model = myTableProxy(self)
        self.proxy_model.setSourceModel(self.source_model)
        self.proxy_model.setDynamicSortFilter(True)
        self.table_view = QTableView()
        self.table_view.setModel(self.proxy_model)
        self.table_view.setAlternatingRowColors(True)
        self.table_view.resizeColumnsToContents()
        self.table_view.resizeRowsToContents()
        self.table_view.horizontalHeader().setStretchLastSection(True)
        self.table_view.setSortingEnabled(True)
        self.table_view.sortByColumn(2, Qt.AscendingOrder)

        # events
        self.selection = self.table_view.selectionModel()
        self.selection.selectionChanged.connect(self.handleSelectionChanged)
        #DO NOT use CreateIndex() method, use index()
        index = self.proxy_model.index(0,0)
        self.selection.select(index, QItemSelectionModel.Select)
        
        self.upperLong = self.table_view  

        # right side widgets
        self.right = QFrame()
        self.la1 = QVBoxLayout()
        self.btnDownload = QPushButton('Download data')
        self.btnDownload.clicked.connect(self.download)
        self.myButton = QPushButton('Show Skillls')
        self.myButton.clicked.connect(self.showAllSkills)
        self.btnSearchByWord = QPushButton('Search by word(s)')
        self.btnSearchByWord.clicked.connect(self.onSearchByWord)
        self.btnResetFilter= QPushButton('Discard Filter')
        self.btnResetFilter.clicked.connect(self.discardFilter)
        self.btnCopyURL = QPushButton('URL to Clipboard')
        self.btnCopyURL.clicked.connect(self.copyToClipboard)
        self.btnExit = QPushButton('Exit')
        self.btnExit.clicked.connect(lambda: sys.exit())
        self.dateTimeStamp = QLabel()
        self.la1.addWidget(self.btnDownload)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.myButton)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnSearchByWord)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnResetFilter)
        self.la1.addSpacing(10)
        self.la1.addWidget(self.btnCopyURL)
        self.la1.addSpacing(70)
        self.la1.addWidget(self.btnExit)
        self.la1.addStretch(stretch=0)
        self.la1.addWidget(self.dateTimeStamp)
        self.right.setLayout(self.la1)
        self.right.setFrameShape(QFrame.StyledPanel)

        # splitters
        self.horiSplit = QSplitter(Qt.Vertical)
        self.horiSplit.addWidget(self.upperLong)
        self.horiSplit.addWidget(self.lowerLong)
        self.horiSplit.setSizes([self.visota/2, self.visota/2])
        self.vertiSplit = QSplitter(Qt.Horizontal)
        self.vertiSplit.addWidget(self.horiSplit)
        self.vertiSplit.addWidget(self.right)
        self.vertiSplit.setSizes([self.shirina*3/4, self.shirina*1/4])
        self.setCentralWidget(self.vertiSplit)
        
        self.settings = QSettings('elance.ini', QSettings.IniFormat)
        self.settings.beginGroup('DATE_STAMP')
        self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time'))
        self.settings.endGroup()
        self.statusText = ''

    def handleSelectionChanged(self, selected, deselected):
        for index in selected.first().indexes():
            #print('Row %d is selected' % index.row())
            ind = index.model().mapToSource(index)
            desc = ind.model().mylist[ind.row()]['Description']
            self.detailsLabel.setText(desc)
            skills = ', '.join(ind.model().mylist[ind.row()]['Skills']).strip()
            self.skillsLabel.setText(skills)
            url = ind.model().mylist[ind.row()]['URL']
            self.urlLabel.setText(url)
            location = ind.model().mylist[ind.row()]['Location']
            self.locationLabel.setText(location)
    
    def showAllSkills(self):
        listSkills = []
        for elem in self.source_model.mylist:
            listSkills += elem['Skills']
        allSkills = Counter(listSkills)
        tbl = MyTableModel(self, allSkills.items(), ['Skill', 'Freq'])
        win = skillsWindow(tbl, self.table_view)
        win.exec_()
    
    def discardFilter(self):
        self.table_view.model().emit(SIGNAL("modelAboutToBeReset()"))
        self.table_view.model().criteria = {}
        self.table_view.model().emit(SIGNAL("modelReset()"))
        self.table_view.resizeRowsToContents()
        
    def download(self):
        self.btnDownload.setDisabled(True)
        self.statusLabel = QLabel('Connecting')
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.myStatusBar.addWidget(self.statusLabel, 2)
        self.myStatusBar.addWidget(self.progressBar, 1)
        self.progressBar.setValue(1)
        self.settings.beginGroup('URLS')
        initialLink = self.settings.value('CategoriesDetailed/VahaSelected/InitialLink')
        pagingLink = self.settings.value('CategoriesDetailed/VahaSelected/PagingLink')
        self.settings.endGroup()
        downloader = Downloader(initialLink, pagingLink, 25, 5)
        downloader.messenger.downloadProgressChanged.connect(self.onDownloadProgressChanged)
        downloader.messenger.downloadComplete.connect(self.onDownloadComplete)
        downloader.download()
    
    def onDownloadComplete(self):
        #QMessageBox.information(self, 'Download complete', 'Download complete!', QMessageBox.Ok)
        self.table_view.model().emit(SIGNAL("modelAboutToBeReset()"))
        self.settings.beginGroup('DATE_STAMP')
        self.settings.setValue('date/time', time.strftime('%d-%b-%Y, %H:%M:%S'))
        self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time'))
        self.settings.endGroup()
        with open("elance.json") as json_file:
            jobDB = json.load(json_file)
        for elem in jobDB:
            words = nltk.tokenize.regexp_tokenize(elem['Title'].lower(), r'\w+')
            elem['Tokens'] = words
            elem['Skills'] = [t.strip() for t in elem['Skills'].split(',')]
        self.source_model.mylist = jobDB
        self.table_view.model().emit(SIGNAL("modelReset()"))
        self.btnDownload.setEnabled(True)
        self.myStatusBar.removeWidget(self.statusLabel)
        self.myStatusBar.removeWidget(self.progressBar)
        self.myStatusBar.showMessage(self.statusText, timeout = 5000)
                
    
    def onDownloadProgressChanged(self, stata):
        self.progressBar.setValue(stata[2])
        #text = 'Processed records{:5d} of{:5d}'.format(percentage[0], percentage[1])
        bajtikov = '{:,}'.format(stata[5])
        self.statusText = 'Processed page{:4d} of{:4d}. \
               Job entries{:5d} of{:5d}. \
               Downloaded{:>12s} Bytes'.format(stata[3], stata[4],
                                              stata[0], stata[1],
                                              bajtikov)
        self.statusLabel.setText(self.statusText)
        
    def copyToClipboard(self):
        clipboard = QApplication.clipboard()
        clipboard.setText(self.urlLabel.text())
        self.myStatusBar.showMessage(self.urlLabel.text(), timeout = 3000)
    
    def onSearchByWord(self):
        text, ok = QInputDialog.getText(self, 'Search the base by word(s)', 'Enter your keyword/phrase to search for:')
        if ok:
            words = [t.strip() for t in nltk.tokenize.regexp_tokenize(text.lower(), r'\w+')]
            self.table_view.model().emit(SIGNAL("modelAboutToBeReset()"))
            self.table_view.model().criteria = {'Description' : words}
            self.table_view.model().emit(SIGNAL("modelReset()"))
예제 #29
0
class QLogger(logging.Handler):
    '''Code from:
  https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt
  '''
    def __init__(self,
                 parent=None,
                 format=settings.log_fmt,
                 level=logging.INFO):
        logging.Handler.__init__(self)
        # Initialize a log handler as the super class
        self.setFormatter(logging.Formatter(format))
        # Set the formatter for the logger
        self.setLevel(level)
        # Set the logging level
        self.frame = QFrame(parent)
        # Initialize a QFrame to place other widgets in

        self.frame2 = QFrame(parent)
        # Initialize frame2 for the label and checkbox
        self.label = QLabel('Logs')
        # Define a label for the frame
        self.check = QCheckBox('Debugging')
        # Checkbox to enable debugging logging
        self.check.clicked.connect(self.__changeLevel)
        # Connect checkbox clicked to the __changeLevel method

        self.log_widget = QTextEdit()
        # Initialize a QPlainTextWidget to write logs to
        self.log_widget.verticalScrollBar().minimum()
        # Set a vertical scroll bar on the log widget
        self.log_widget.horizontalScrollBar().minimum()
        # Set a horizontal scroll bar on the log widget
        self.log_widget.setLineWrapMode(self.log_widget.NoWrap)
        # Set line wrap mode to no wrapping
        self.log_widget.setFont(QFont("Courier", 12))
        # Set the font to a monospaced font
        self.log_widget.setReadOnly(True)
        # Set log widget to read only

        layout = QHBoxLayout()
        # Initialize a horizontal layout scheme for the label and checkbox frame
        layout.addWidget(self.label)
        # Add the label to the layout scheme
        layout.addWidget(self.check)
        # Add the checkbox to the layout scheme
        self.frame2.setLayout(layout)
        # Set the layout for frame to the horizontal layout

        layout = QVBoxLayout()
        # Initialize a layout scheme for the widgets
        layout.addWidget(self.frame2)
        # Add the label/checkbox frame to the layout scheme
        layout.addWidget(self.log_widget)
        # Add the text widget to the layout scheme

        self.frame.setLayout(layout)
        # Set the layout of the fram to the layout scheme defined

    ##############################################################################
    def emit(self, record):
        '''
    Overload the emit method so that it prints to the text widget
    '''
        msg = self.format(record)
        # Format the message for logging
        if record.levelno >= logging.CRITICAL:  # If the log level is critical
            self.log_widget.setTextColor(Qt.red)
            # Set text color to red
        elif record.levelno >= logging.ERROR:  # Elif level is error
            self.log_widget.setTextColor(Qt.darkMagenta)
            # Set text color to darkMagenta
        elif record.levelno >= logging.WARNING:  # Elif level is warning
            self.log_widget.setTextColor(Qt.darkCyan)
            # Set text color to darkCyan
        else:  # Else
            self.log_widget.setTextColor(Qt.black)
            # Set text color to black
        self.log_widget.append(msg)
        # Add the log to the text widget

    ##############################################################################
    def write(self, m):
        '''
    Overload the write method so that it does nothing
    '''
        pass

    ##############################################################################
    def __changeLevel(self, *args):
        '''
    Private method to change logging level
    '''
        if self.check.isChecked():
            self.setLevel(logging.DEBUG)
            # Get the Meso1819 root logger and add the handler to it
        else:
            self.setLevel(logging.INFO)
예제 #30
0
    def _make_total_days_off_panel(self):

        widget = QFrame()
        widget.setObjectName('HorseRegularFrame')

        widget.setFrameShape(QFrame.Panel)
        widget.setFrameShadow(QFrame.Sunken)
        layout = QVBoxLayout()

        #layout.addWidget(QLabel(_("Days off to date")))
        self.day_off_total_duration_labels = dict()
        self.day_off_month_duration_labels = dict()
        self.day_off_labels = dict()

        self._day_off_table_model = QStandardItemModel(10, 3)
        self._day_off_table_model.setHorizontalHeaderLabels(
            [None, None, _("This\nmonth"),
             _("Before")])
        self.day_off_table_view = QTableView(None)
        self.day_off_table_view.setModel(self._day_off_table_model)

        # self.day_off_table_view.setHorizontalHeader(self.headers_view)
        self.day_off_table_view.verticalHeader().hide()
        self.day_off_table_view.setAlternatingRowColors(True)
        self.day_off_table_view.setEditTriggers(
            QAbstractItemView.NoEditTriggers)

        self.day_off_table_view.hide()

        row = 0
        for det in DayEventType.symbols():
            ndx = self._day_off_table_model.index(row, 0)
            self._day_off_table_model.setData(ndx, det.description,
                                              Qt.DisplayRole)

            ndx = self._day_off_table_model.index(row, 1)
            fg, bg = self.DAY_EVENT_PALETTE[det]
            self._day_off_table_model.setData(ndx, QBrush(bg),
                                              Qt.BackgroundRole)
            self._day_off_table_model.setData(ndx, QBrush(fg),
                                              Qt.TextColorRole)
            self._day_off_table_model.setData(ndx,
                                              DayEventType.short_code(det),
                                              Qt.DisplayRole)

            row += 1

        layout.addWidget(self.day_off_table_view)

        grid = QGridLayout()
        self.days_off_layout = grid
        grid.setColumnStretch(3, 1)
        row = 0

        grid.addWidget(QLabel(_('Year')), row, self.YEAR_EVENT_COLUMN)
        grid.addWidget(QLabel(_('Month')), row, self.MONTH_EVENT_COLUMN)
        row += 1

        for det in DayEventType.symbols():
            self.day_off_total_duration_labels[det] = QLabel("-")
            self.day_off_month_duration_labels[det] = QLabel("-")
            self.day_off_labels[det] = QLabel(det.description)

            hlayout = QHBoxLayout()

            sl = QLabel()
            fg, bg = self.DAY_EVENT_PALETTE[det]

            def to_html_rgb(color):
                i = color.red() * 256 * 256 + color.green() * 256 + color.blue(
                )
                return "#{:06X}".format(i)

            p = QPalette()
            p.setColor(QPalette.Window, QColor(bg))
            p.setColor(QPalette.WindowText, QColor(fg))
            sl.setPalette(p)
            sl.setAlignment(Qt.AlignCenter)
            sl.setStyleSheet("border: 2px solid black; background: {}".format(
                to_html_rgb(QColor(bg))))

            t = DayEventType.short_code(det)
            mainlog.debug(t)
            sl.setAutoFillBackground(True)
            sl.setText(t)

            grid.addWidget(sl, row, 0)
            grid.addWidget(self.day_off_labels[det], row, 1)
            grid.addWidget(self.day_off_total_duration_labels[det], row,
                           self.YEAR_EVENT_COLUMN)
            grid.addWidget(self.day_off_month_duration_labels[det], row,
                           self.MONTH_EVENT_COLUMN)

            hlayout.addStretch()

            row += 1

        layout.addLayout(grid)
        layout.addStretch()

        self.day_off_table_view.resizeColumnsToContents()
        # self.day_off_table_view.setMinimumWidth( self.day_off_table_view.width())
        # self.day_off_table_view.resize( self.day_off_table_view.minimumWidth(),
        #                                 self.day_off_table_view.minimumHeight(),)

        widget.setLayout(layout)
        return widget
    def __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(
                QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)
예제 #32
0
class ContactDataPlateWidget(QWidget):

    def _make_layout(self):
        self.customer_name_label = AutoHideLabel()
        self.customer_name_label.setObjectName("HorseCustomerPlateTitle")
        self.customer_address1_label = AutoHideLabel()
        self.customer_address2_label = AutoHideLabel()
        self.customer_phone_label = AutoHideLabel()
        self.customer_phone2_label = AutoHideLabel()
        self.customer_fax_label = AutoHideLabel()
        self.customer_notes_label = AutoHideLabel()


        contact_data_frame = QFrame()
        contact_data_layout = QVBoxLayout()
        # contact_data_layout.setContentsMargins(2,0,2,0)
        contact_data_layout.addWidget(self.customer_phone_label)
        contact_data_layout.addWidget(self.customer_phone2_label)
        contact_data_layout.addWidget(self.customer_fax_label)
        contact_data_layout.addStretch()
        contact_data_frame.setLayout(contact_data_layout)

        self.address_data_frame = QFrame()
        self.address_data_frame.setObjectName("leftBorderFrame")
        self.address_data_frame.setStyleSheet("#leftBorderFrame { border-left: 1px solid black; }")
        address_data_layout = QVBoxLayout()
        # address_data_layout.setContentsMargins(2,0,2,0)
        address_data_layout.addWidget(self.customer_address1_label)
        address_data_layout.addWidget(self.customer_address2_label)
        address_data_layout.addStretch()
        self.address_data_frame.setLayout(address_data_layout)

        self.note_frame = QFrame()
        self.note_frame.setObjectName("topBorderFrame")
        self.note_frame.setStyleSheet("#topBorderFrame { border-top: 1px solid black; }")
        layout = QVBoxLayout()
        # layout.setContentsMargins(2,0,2,0)
        self.customer_notes_label.setAlignment(Qt.AlignTop)
        layout.addWidget(self.customer_notes_label)
        layout.addStretch()
        self.note_frame.setLayout(layout)

        data1_layout = QHBoxLayout()
        data1_layout.addWidget(contact_data_frame)
        data1_layout.addWidget(self.address_data_frame)
        data1_layout.addStretch()

        data_layout = QVBoxLayout()
        data_layout.addWidget(self.customer_name_label)
        sep = QFrame()
        sep.setFrameStyle(QFrame.HLine)
        data_layout.addWidget(sep)
        data_layout.addLayout(data1_layout)
        data_layout.addWidget(self.note_frame)
        data_layout.setStretch(0,0)
        data_layout.setStretch(1,1)

        self.setLayout(data_layout)

        # top_frame = QFrame()
        # top_frame.setFrameShape(QFrame.NoFrame)
        # top_frame.setMinimumSize(300,100)
        # top_frame.setLayout(data_layout)

        # scroll_area = QScrollArea()
        # scroll_area.setWidget(top_frame)
        # scroll_area.setWidgetResizable(True)


        # self.setStyleSheet("background:white")
        # self.setFrameShape(QFrame.Panel)
        # self.setFrameShadow(QFrame.Sunken)

        self.setMinimumSize(300,80)
        self.setMaximumSize(600,400)
        self.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)


    def __init__(self,parent):
        super(ContactDataPlateWidget,self).__init__(parent)

        self._make_layout()
        self.customer_id = None


    def _clear_data(self):
        self.customer_name_label.setText("")
        self.customer_address1_label.setText("")
        self.customer_address2_label.setText("")
        self.customer_phone_label.setText("")
        self.customer_phone2_label.setText("")
        self.customer_fax_label.setText("")
        self.customer_notes_label.setText("")


    def _set_data(self,data):
        self.customer_name_label.setText(data.fullname)
        self.address_data_frame.setHidden(not data.address1 and not data.address2)

        self.customer_address1_label.setText(data.address1)
        self.customer_address2_label.setText(data.address2)

        if data.phone:
            self.customer_phone_label.setText(_("P: {}").format(data.phone))
        else:
            self.customer_phone_label.setText("")

        if data.phone2:
            self.customer_phone2_label.setText(_("P: {}").format(data.phone2))
        else:
            self.customer_phone2_label.setText("")

        if data.fax:
            self.customer_fax_label.setText(_("F: {}").format(data.fax))
        else:
            self.customer_fax_label.setText("")

        self.note_frame.setHidden(not data.notes)
        self.customer_notes_label.setText(data.notes)
예제 #33
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()
예제 #34
0
    def _make_layout(self):
        self.customer_name_label = AutoHideLabel()
        self.customer_name_label.setObjectName("HorseCustomerPlateTitle")
        self.customer_address1_label = AutoHideLabel()
        self.customer_address2_label = AutoHideLabel()
        self.customer_phone_label = AutoHideLabel()
        self.customer_phone2_label = AutoHideLabel()
        self.customer_fax_label = AutoHideLabel()
        self.customer_notes_label = AutoHideLabel()


        contact_data_frame = QFrame()
        contact_data_layout = QVBoxLayout()
        # contact_data_layout.setContentsMargins(2,0,2,0)
        contact_data_layout.addWidget(self.customer_phone_label)
        contact_data_layout.addWidget(self.customer_phone2_label)
        contact_data_layout.addWidget(self.customer_fax_label)
        contact_data_layout.addStretch()
        contact_data_frame.setLayout(contact_data_layout)

        self.address_data_frame = QFrame()
        self.address_data_frame.setObjectName("leftBorderFrame")
        self.address_data_frame.setStyleSheet("#leftBorderFrame { border-left: 1px solid black; }")
        address_data_layout = QVBoxLayout()
        # address_data_layout.setContentsMargins(2,0,2,0)
        address_data_layout.addWidget(self.customer_address1_label)
        address_data_layout.addWidget(self.customer_address2_label)
        address_data_layout.addStretch()
        self.address_data_frame.setLayout(address_data_layout)

        self.note_frame = QFrame()
        self.note_frame.setObjectName("topBorderFrame")
        self.note_frame.setStyleSheet("#topBorderFrame { border-top: 1px solid black; }")
        layout = QVBoxLayout()
        # layout.setContentsMargins(2,0,2,0)
        self.customer_notes_label.setAlignment(Qt.AlignTop)
        layout.addWidget(self.customer_notes_label)
        layout.addStretch()
        self.note_frame.setLayout(layout)

        data1_layout = QHBoxLayout()
        data1_layout.addWidget(contact_data_frame)
        data1_layout.addWidget(self.address_data_frame)
        data1_layout.addStretch()

        data_layout = QVBoxLayout()
        data_layout.addWidget(self.customer_name_label)
        sep = QFrame()
        sep.setFrameStyle(QFrame.HLine)
        data_layout.addWidget(sep)
        data_layout.addLayout(data1_layout)
        data_layout.addWidget(self.note_frame)
        data_layout.setStretch(0,0)
        data_layout.setStretch(1,1)

        self.setLayout(data_layout)

        # top_frame = QFrame()
        # top_frame.setFrameShape(QFrame.NoFrame)
        # top_frame.setMinimumSize(300,100)
        # top_frame.setLayout(data_layout)

        # scroll_area = QScrollArea()
        # scroll_area.setWidget(top_frame)
        # scroll_area.setWidgetResizable(True)


        # self.setStyleSheet("background:white")
        # self.setFrameShape(QFrame.Panel)
        # self.setFrameShadow(QFrame.Sunken)

        self.setMinimumSize(300,80)
        self.setMaximumSize(600,400)
        self.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)
예제 #35
0
class MainWindow(QMainWindow):
    start_acq = Signal(str)
    start_rec = Signal(str)
    collect_frame = Signal(object)
    collect_threshed = Signal(object)

    def __init__(self, parent=None):
        ''' sets up the whole main window '''

        #standard init
        super(MainWindow, self).__init__(parent)

        #set the window title
        self.setWindowTitle('Open Ephys Control GUI')

        self.window_height = 700
        self.window_width = 1100

        self.screen2 = QDesktopWidget().screenGeometry(0)
        self.move(
            self.screen2.left() +
            (self.screen2.width() - self.window_width) / 2.,
            self.screen2.top() +
            (self.screen2.height() - self.window_height) / 2.)

        self.get_info()
        self.noinfo = True

        while self.noinfo:
            loop = QEventLoop()
            QTimer.singleShot(500., loop.quit)
            loop.exec_()

        subprocess.Popen('start %s' % open_ephys_path, shell=True)

        self.collect_frame.connect(self.update_frame)
        self.collect_threshed.connect(self.update_threshed)
        self.acquiring = False
        self.recording = False

        self.video_height = self.window_height * .52
        self.video_width = self.window_width * .48

        self.resize(self.window_width, self.window_height)

        #create QTextEdit window 'terminal' for receiving stdout and stderr
        self.terminal = QTextEdit(self)
        #set the geometry
        self.terminal.setGeometry(
            QRect(self.window_width * .02,
                  self.window_height * .15 + self.video_height,
                  self.video_width * .96, 150))

        #make widgets
        self.setup_video_frames()
        self.setup_thresh_buttons()

        self.overlay = True

        #create thread and worker for video processing
        self.videoThread = QThread(self)
        self.videoThread.start()
        self.videoproc_worker = VideoWorker(self)
        self.videoproc_worker.moveToThread(self.videoThread)

        self.vt_file = None
        """""" """""" """""" """""" """""" """""" """""" """
        set up menus
        """ """""" """""" """""" """""" """""" """""" """"""

        #create a QMenuBar and set geometry
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(
            QRect(0, 0, self.window_width * .5, self.window_height * .03))
        #set the QMenuBar as menu bar for main window
        self.setMenuBar(self.menubar)

        #create a QStatusBar
        statusbar = QStatusBar(self)
        #set it as status bar for main window
        self.setStatusBar(statusbar)

        #create icon toolbar with default image
        iconToolBar = self.addToolBar("iconBar.png")

        #create a QAction for the acquire button
        self.action_Acq = QAction(self)
        #make it checkable
        self.action_Acq.setCheckable(True)
        #grab an icon for the button
        acq_icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        #set the icon for the action
        self.action_Acq.setIcon(acq_icon)
        #when the button is pressed, call the Acquire function
        self.action_Acq.triggered.connect(self.Acquire)

        #create a QAction for the record button
        self.action_Record = QAction(self)
        #make it checkable
        self.action_Record.setCheckable(True)
        #grab an icon for the button
        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)
        #when the button is pressed, call advanced_settings function
        self.action_Record.triggered.connect(self.Record)

        #create QAction for stop button
        action_Stop = QAction(self)
        #grab close icon
        stop_icon = self.style().standardIcon(QStyle.SP_MediaStop)
        #set icon for action
        action_Stop.setIcon(stop_icon)
        #when button pressed, close window
        action_Stop.triggered.connect(self.Stop)

        #show tips for each action in the status bar
        self.action_Acq.setStatusTip("Start acquiring")
        self.action_Record.setStatusTip("Start recording")
        action_Stop.setStatusTip("Stop acquiring/recording")

        #add actions to icon toolbar
        iconToolBar.addAction(self.action_Acq)
        iconToolBar.addAction(self.action_Record)
        iconToolBar.addAction(action_Stop)

        #        self.sort_button = QPushButton('Sort Now',self)
        #        self.sort_button.setGeometry(QRect(self.window_width*.85,0,self.window_width*.15,self.window_height*.05))
        #        self.sort_button.clicked.connect(self.sort_now)

        #show the window if minimized by windows
        self.showMinimized()
        self.showNormal()
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""
        """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" ""

    #this function acts as a slot to accept 'message' signal
    @Slot(str)
    def print_message(self, message):
        ''' print stdout and stderr to terminal window '''

        #move terminal cursor to end
        self.terminal.moveCursor(QTextCursor.End)
        #write message to terminal
        self.terminal.insertPlainText(message)

    def setup_thresh_buttons(self):
        ''' set up buttons for overlay/clearing thresh view '''

        self.button_frame = QFrame(self)
        self.button_frame.setGeometry(
            QRect(self.window_width * .52,
                  self.window_height * .13 + self.video_height,
                  self.video_width * .98, 50))
        button_layout = QHBoxLayout()
        self.button_frame.setLayout(button_layout)
        self.clear_button = QPushButton('Clear')
        self.overlay_button = QPushButton('Overlay')
        button_layout.addWidget(self.clear_button)
        button_layout.addWidget(self.overlay_button)

        self.clear_button.setEnabled(False)
        self.clear_button.clicked.connect(self.clear_threshed)
        self.overlay_button.setEnabled(False)
        self.overlay_button.clicked.connect(self.overlay_threshed)

    def setup_video_frames(self):
        ''' set up spots for playing video frames '''

        filler_frame = np.zeros((360, 540, 3))
        filler_frame = qimage2ndarray.array2qimage(filler_frame)

        self.raw_frame = QFrame(self)
        self.raw_label = QLabel()
        self.raw_label.setText('raw')
        self.raw_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .15,
                  self.video_width, self.video_height))
        self.raw_frame
        raw_layout = QVBoxLayout()
        self.raw_frame.setLayout(raw_layout)
        raw_layout.addWidget(self.raw_label)

        self.threshed_frame = QFrame(self)
        self.threshed_label = QLabel()
        self.threshed_label.setText('Threshed')
        self.threshed_frame.setGeometry(
            QRect(self.window_width * .51, self.window_height * .15,
                  self.video_width, self.video_height))
        threshed_layout = QVBoxLayout()
        self.threshed_frame.setLayout(threshed_layout)
        threshed_layout.addWidget(self.threshed_label)

        self.label_frame = QFrame(self)
        self.label_frame.setGeometry(
            QRect(self.window_width * .01, self.window_height * .11,
                  self.video_width * 2, 50))
        self.label_rawlabel = QLabel()
        self.label_rawlabel.setText('Raw Video')
        self.label_threshedlabel = QLabel()
        self.label_threshedlabel.setText('Threshold View')
        label_layout = QHBoxLayout()
        self.label_frame.setLayout(label_layout)
        label_layout.addWidget(self.label_rawlabel)
        label_layout.addWidget(self.label_threshedlabel)

        self.raw_label.setPixmap(QPixmap.fromImage(filler_frame))
        self.threshed_label.setPixmap(QPixmap.fromImage(filler_frame))

    def Acquire(self):

        if self.action_Acq.isChecked():

            self.vidbuffer = []

            if self.recording:

                while 1:
                    try:
                        self.sock.send('StopRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.recording = False

            else:
                #create and start a thread to transport a worker to later
                self.workerThread = QThread(self)
                self.workerThread.start()
                #create a worker object based on Worker class and move it to our
                #worker thread
                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_acq.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.acquiring = True
                self.start_acq.connect(self.worker.acquire)
                self.start_acq.emit('start!')

            self.action_Acq.setEnabled(False)
            self.action_Record.setChecked(False)
            self.action_Record.setEnabled(True)

            record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)

    def Record(self):

        if self.action_Record.isChecked():

            if not self.acquiring:
                self.workerThread = QThread(self)
                self.workerThread.start()

                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_rec.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.start_rec.connect(self.worker.acquire)
                self.recording = True
                self.start_rec.emit('start!')

            else:

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.recording = True

            record_icon = self.style().standardIcon(QStyle.SP_DialogNoButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)
            self.action_Record.setEnabled(False)

            self.action_Acq.setChecked(False)
            self.action_Acq.setEnabled(True)

    def Stop(self):

        self.acquiring = False
        self.recording = False

        while 1:
            try:
                self.sock.send('isRecording')
                rec = self.sock.recv()
            except:
                continue
            break

        if rec == '1':
            while 1:
                try:
                    self.sock.send('StopRecord')
                    self.sock.recv()
                except:
                    continue
                break

            self.action_Record.setEnabled(True)
            self.action_Record.setChecked(False)

        while 1:
            try:
                self.sock.send('isAcquiring')
                acq = self.sock.recv_string()
            except:
                continue
            break

        if acq == '1':
            while 1:
                try:
                    self.sock.send('StopAcquisition')
                    self.sock.recv()
                except:
                    continue
                break

        self.action_Acq.setEnabled(True)
        self.action_Acq.setChecked(False)

        try:
            #open a csv file for saving tracking data
            with open(self.vt_file, 'a') as csvfile:
                #create a writer
                vidwriter = csv.writer(csvfile, dialect='excel-tab')
                #check if it's an empty file
                for row in self.vidbuffer:
                    vidwriter.writerow(row)

        except:
            pass

        record_icon = self.style().standardIcon(QStyle.SP_DialogYesButton)
        #set the icon for the action
        self.action_Record.setIcon(record_icon)

    def update_frame(self, image):
        self.raw_label.setPixmap(QPixmap.fromImage(image))

    def update_threshed(self, threshed_image):
        self.threshed_label.setPixmap(QPixmap.fromImage(threshed_image))

    def clear_threshed(self):
        self.green_frame = np.zeros_like(self.green_frame)
        self.red_frame = np.zeros_like(self.red_frame)

    def overlay_threshed(self):
        if self.overlay:
            self.overlay = False
        elif not self.overlay:
            self.overlay = True


#    def sort_now(self):
#
#        if self.recdir is not None:
#            os.chdir('./kilosort_control')
#            #create and show the main window
#            self.sort_frame = kilosort_control.sort_gui.MainWindow()
#            self.sort_frame.show()
#
#            #set up stream for stdout and stderr based on outputStream class
#            self.outputStream = kilosort_control.sort_gui.outputStream()
#            #when outputStream sends messages, connect to appropriate function for
#            #writing to terminal window
#            self.outputStream.message.connect(self.sort_frame.print_message)
#
#            #connect stdout and stderr to outputStream
#            sys.stdout = self.outputStream
#            sys.stderr = self.outputStream
#
#            self.sort_frame.run_now(self.recdir)
#
#            self.close()

    def get_info(self):

        self.info_window = QWidget()
        self.info_window.resize(400, 350)
        #set title
        self.info_window.setWindowTitle('Session Info')
        #give layout
        info_layout = QVBoxLayout(self.info_window)

        with open('info_fields.pickle', 'rb') as f:
            default_fields = pickle.load(f)
            f.close()

        #set label for pic_resolution setting
        experimenter_label = QLabel('Experimenter:')
        #make a QLineEdit box for displaying/editing settings
        experimenter = QComboBox(self.info_window)
        experimenter.setEditable(True)
        experimenter.addItems(default_fields['experimenter'])
        #add label and box to current window
        info_layout.addWidget(experimenter_label)
        info_layout.addWidget(experimenter)

        #set label for pic_resolution setting
        whose_animal_label = QLabel('Whose animal?')
        #make a QLineEdit box for displaying/editing settings
        whose_animal = QComboBox(self.info_window)
        whose_animal.setEditable(True)
        whose_animal.addItems(default_fields['whose_animal'])
        #add label and box to current window
        info_layout.addWidget(whose_animal_label)
        info_layout.addWidget(whose_animal)

        animal_number_label = QLabel('Animal number:')
        animal_number = QComboBox(self.info_window)
        animal_number.setEditable(True)
        animal_number.addItems(default_fields['animal_number'])
        info_layout.addWidget(animal_number_label)
        info_layout.addWidget(animal_number)

        session_number_label = QLabel('Session number:')
        session_number = QTextEdit(self.info_window)
        session_number.setText('1')
        info_layout.addWidget(session_number_label)
        info_layout.addWidget(session_number)

        session_type_label = QLabel('Session type:')
        session_type = QComboBox(self.info_window)
        session_type.setEditable(True)
        session_type.addItems(default_fields['session_type'])
        info_layout.addWidget(session_type_label)
        info_layout.addWidget(session_type)

        def save_info(self):

            info_fields = {}
            info_fields['experimenter'] = [
                experimenter.itemText(i) for i in range(experimenter.count())
            ]
            info_fields['whose_animal'] = [
                whose_animal.itemText(i) for i in range(whose_animal.count())
            ]
            info_fields['animal_number'] = [
                animal_number.itemText(i) for i in range(animal_number.count())
            ]
            info_fields['session_type'] = [
                session_type.itemText(i) for i in range(session_type.count())
            ]

            with open('info_fields.pickle', 'wb') as f:
                pickle.dump(info_fields, f, protocol=2)
                f.close()

            current_experimenter = str(experimenter.currentText())
            current_whose_animal = str(whose_animal.currentText())
            current_animal_number = str(animal_number.currentText())
            current_session_number = str(session_number.toPlainText())
            current_session_type = str(session_type.currentText())

            recdir = data_save_dir + current_whose_animal + '/' + current_animal_number

            if not os.path.exists(recdir):
                os.makedirs(recdir)

            self.experiment_info = '###### Experiment Info ######\r\n'
            self.experiment_info += 'Experimenter: %s\r\n' % current_experimenter
            self.experiment_info += 'Whose animal? %s\r\n' % current_whose_animal
            self.experiment_info += 'Animal number: %s\r\n' % current_animal_number
            self.experiment_info += 'Session number: %s\r\n' % current_session_number
            self.experiment_info += 'Session type: %s\r\n' % current_session_type

            self.experiment_info = self.experiment_info.encode()

            config_file = config_path + '/' + current_animal_number + '.xml'

            if not os.path.exists(config_file):
                shutil.copy(default_config, config_file)

            tree = et.parse(config_file)
            root = tree.getroot()
            for child in root:
                if child.tag == 'CONTROLPANEL':
                    child.attrib['recordPath'] = recdir.replace('/', '\\')
            tree.write(config_file)
            tree.write(default_config)

            self.info_window.close()
            self.noinfo = False

        ready_button = QPushButton('Ready!')
        ready_button.clicked.connect(lambda: save_info(self))
        info_layout.addWidget(ready_button)

        self.info_window.show()
    def __create_ui(self):
        """ Create main UI """
        self.setWindowTitle(CREATE_NODE_TITLE)

        # remove window decoration if path and type is set
        if self.defined_path and self.defined_type:
            self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)

        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(1)
        main_layout.setContentsMargins(2, 2, 2, 2)

        # content layout
        content_layout = QVBoxLayout()
        self.files_model = QFileSystemModel()
        self.files_model.setNameFilterDisables(False)
        self.files_list = MTTFileList()
        self.files_list.setAlternatingRowColors(True)
        self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.files_list.selectionValidated.connect(self.do_validate_selection)
        self.files_list.goToParentDirectory.connect(self.on_go_up_parent)
        self.files_list.doubleClicked.connect(self.on_double_click)
        self.files_list.setModel(self.files_model)

        buttons_layout = QHBoxLayout()

        content_layout.addLayout(self.__create_filter_ui())
        content_layout.addWidget(self.files_list)
        content_layout.addLayout(buttons_layout)
        self.files_list.filter_line = self.filter_line

        if not self.defined_path:
            # path line
            path_layout = QHBoxLayout()
            # bookmark button
            bookmark_btn = QPushButton('')
            bookmark_btn.setFlat(True)
            bookmark_btn.setIcon(QIcon(':/addBookmark.png'))
            bookmark_btn.setToolTip('Bookmark this Folder')
            bookmark_btn.setStatusTip('Bookmark this Folder')
            bookmark_btn.clicked.connect(self.on_add_bookmark)
            # path line edit
            self.path_edit = QLineEdit()
            self.path_edit.editingFinished.connect(self.on_enter_path)
            # parent folder button
            self.parent_folder_btn = QPushButton('')
            self.parent_folder_btn.setFlat(True)
            self.parent_folder_btn.setIcon(QIcon(':/SP_FileDialogToParent.png'))
            self.parent_folder_btn.setToolTip('Parent Directory')
            self.parent_folder_btn.setStatusTip('Parent Directory')
            self.parent_folder_btn.clicked.connect(self.on_go_up_parent)
            # browse button
            browse_btn = QPushButton('')
            browse_btn.setFlat(True)
            browse_btn.setIcon(QIcon(':/navButtonBrowse.png'))
            browse_btn.setToolTip('Browse Directory')
            browse_btn.setStatusTip('Browse Directory')
            browse_btn.clicked.connect(self.on_browse)
            # parent widget and layout
            path_layout.addWidget(bookmark_btn)
            path_layout.addWidget(self.path_edit)
            path_layout.addWidget(self.parent_folder_btn)
            path_layout.addWidget(browse_btn)
            main_layout.addLayout(path_layout)

            # bookmark list
            bookmark_parent_layout = QHBoxLayout()
            bookmark_frame = QFrame()
            bookmark_frame.setFixedWidth(120)
            bookmark_layout = QVBoxLayout()
            bookmark_layout.setSpacing(1)
            bookmark_layout.setContentsMargins(2, 2, 2, 2)
            bookmark_frame.setLayout(bookmark_layout)
            bookmark_frame.setFrameStyle(QFrame.Sunken)
            bookmark_frame.setFrameShape(QFrame.StyledPanel)
            self.bookmark_list = MTTBookmarkList()
            self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark)
            self.bookmark_list.setAlternatingRowColors(True)
            self.bookmark_list.dragEnabled()
            self.bookmark_list.setAcceptDrops(True)
            self.bookmark_list.setDropIndicatorShown(True)
            self.bookmark_list.setDragDropMode(QListView.InternalMove)
            self.bookmark_list_sel_model = self.bookmark_list.selectionModel()
            self.bookmark_list_sel_model.selectionChanged.connect(
                self.on_select_bookmark)

            bookmark_layout.addWidget(self.bookmark_list)
            bookmark_parent_layout.addWidget(bookmark_frame)
            bookmark_parent_layout.addLayout(content_layout)
            main_layout.addLayout(bookmark_parent_layout)

            self.do_populate_bookmarks()

        else:
            main_layout.addLayout(content_layout)

        if not self.defined_type:
            # type layout
            self.types = QComboBox()
            self.types.addItems(self.supported_node_type)
            self.types.currentIndexChanged.connect(self.on_node_type_changed)
            if cmds.optionVar(exists='MTT_lastNodeType'):
                last = cmds.optionVar(query='MTT_lastNodeType')
                if last in self.supported_node_type:
                    self.types.setCurrentIndex(
                        self.supported_node_type.index(last))
            buttons_layout.addWidget(self.types)

        if not self.defined_path or not self.defined_type:
            create_btn = QPushButton('C&reate')
            create_btn.clicked.connect(self.accept)
            cancel_btn = QPushButton('&Cancel')
            cancel_btn.clicked.connect(self.reject)

            buttons_layout.addStretch()
            buttons_layout.addWidget(create_btn)
            buttons_layout.addWidget(cancel_btn)