コード例 #1
2
ファイル: widget.py プロジェクト: kissofblood/neuron
class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.uiTeachingWidget = teachingwidget.Widget()
        self.uiExperimentWidget = experimentwidget.Widget()

        self.uiStackedWidget = QStackedWidget()
        self.uiStackedWidget.addWidget(self.uiTeachingWidget)
        self.uiStackedWidget.addWidget(self.uiExperimentWidget)
        self.uiButtonNext = QPushButton('Next')
        self.uiButtonBack = QPushButton('Back')
        self.uiButtonBack.setEnabled(False)
        hboxLayout = QHBoxLayout()
        hboxLayout.addStretch(1)
        hboxLayout.addWidget(self.uiButtonBack)
        hboxLayout.addWidget(self.uiButtonNext)

        vboxLayout = QVBoxLayout()
        vboxLayout.addWidget(self.uiStackedWidget)
        vboxLayout.addLayout(hboxLayout)
        self.setLayout(vboxLayout)
        self.setWindowTitle('Teaching one linear neuron (example 3)')
        self.connect(self.uiButtonNext, SIGNAL('clicked()'), self.nextWidget)
        self.connect(self.uiButtonBack, SIGNAL('clicked()'), self.backWidget)

    def nextWidget(self):
        self.uiButtonNext.setEnabled(False)
        self.uiButtonBack.setEnabled(True)
        self.uiStackedWidget.setCurrentIndex(1)

    def backWidget(self):
        self.uiButtonNext.setEnabled(True)
        self.uiButtonBack.setEnabled(False)
        self.uiStackedWidget.setCurrentIndex(0)
コード例 #2
1
ファイル: table_widget.py プロジェクト: intermezzo-fr/pireal
class TableWidget(QWidget):

    def __init__(self):
        super(TableWidget, self).__init__()

        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)

        self.relations = {}

        ## Splitter
        #self._splitter = QSplitter()

        ## List of names of tables/relations
        #self._list_tables = QListWidget()
        #self._splitter.addWidget(self._list_tables)
        ## Stack
        self.stacked = QStackedWidget()
        vbox.addWidget(self.stacked)

        #vbox.addWidget(self._splitter)

        #self.connect(self._list_tables, SIGNAL("currentRowChanged(int)"),
                     #self.__change_table)

    #def __change_table(self, index):
        #self.stacked.setCurrentIndex(index)

    def count(self):
        return self.stacked.count()

    def add_table(self, rows, columns, name, data):
        table = QTableWidget()
        table.setRowCount(rows)
        table.setColumnCount(columns)

        for k, v in list(data.items()):
            item = QTableWidgetItem()
            item.setText(v)
            if k[0] == 0:
                table.setHorizontalHeaderItem(k[1], item)
            else:
                table.setItem(k[0] - 1, k[1], item)
        #ntuples = " [ " + str(rows) + " ]"
        #item_list = QListWidgetItem(name + ntuples)
        #item_list.setTextAlignment(Qt.AlignHCenter)
        #self._list_tables.addItem(item_list)
        self.stacked.addWidget(table)
        self.stacked.setCurrentIndex(self.stacked.count() - 1)

    def add_new_table(self, rel, name):
        import itertools

        table = QTableWidget()
        table.setRowCount(0)
        table.setColumnCount(0)

        data = itertools.chain([rel.fields], rel.content)

        for row_data in data:
            row = table.rowCount()
            table.setColumnCount(len(row_data))
            for col, text in enumerate(row_data):
                item = QTableWidgetItem()
                item.setText(text)
                if row == 0:
                    table.setHorizontalHeaderItem(col, item)
                else:
                    table.setItem(row - 1, col, item)
            table.insertRow(row)
        table.removeRow(table.rowCount() - 1)
        self.stacked.addWidget(table)
        self.stacked.setCurrentIndex(self.stacked.count() - 1)
        lateral = Pireal.get_service("lateral")
        lateral.add_item_list([name])

    def remove_table(self, index):
        table = self.stacked.widget(index)
        self.stacked.removeWidget(table)

    def add_table_from_file(self):
        pass
コード例 #3
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setGeometry(geom['win']['g']['x'], geom['win']['g']['y'], geom['win']['g']['w'], geom['win']['g']['h'])
        self.setStyleSheet(BG_STYLE)
        self.cw = QStackedWidget()
        self.setCentralWidget(self.cw)
        stopby = Stopat(IMAGES, self, options = VLC_OPTIONS)
        self.cw.insertWidget(STOPAT_NDX, stopby)
        self.cw.setCurrentIndex(STOPAT_NDX)
    def getstack(self):
        return self.cw
コード例 #4
0
class FormTabWidget(QWidget):
    def __init__(self, datalist, comment="", parent=None):
        QWidget.__init__(self, parent)
        layout = QHBoxLayout()
        self.contentsWidget = QListWidget()
        self.contentsWidget.setViewMode(QListView.ListMode)
        self.contentsWidget.setMovement(QListView.Static)
        self.contentsWidget.setMaximumWidth(128)

        self.pagesWidget = QStackedWidget()
        layout.addWidget(self.contentsWidget)
        layout.addWidget(self.pagesWidget)
        self.setLayout(layout)
        self.widgetlist = []

        for elem in datalist:
            if len(elem) == 4:
                data, title, comment, icon = elem
            else:
                data, title, comment = elem
                icon = None

            if len(data[0]) == 3:
                widget = FormComboWidget(data, comment=comment, parent=self)
            else:
                widget = FormWidget(data, comment=comment, parent=self)
            #index = self.tabwidget.addTab(widget, title)
            #self.tabwidget.setTabToolTip(index, comment)
            self.pagesWidget.addWidget(widget)
            contentItem = QListWidgetItem(self.contentsWidget)
            if icon:
                contentItem.setIcon(icon)
            contentItem.setText(title)
            contentItem.setToolTip(comment)
            contentItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            self.contentsWidget.addItem(contentItem)
            self.widgetlist.append(widget)

        self.contentsWidget.currentRowChanged.connect(self.changePage)

    def changePage(self, current):
        if current != -1:
            self.pagesWidget.setCurrentIndex(current)

    def setup(self):
        for widget in self.widgetlist:
            widget.setup()

    def get(self):
        return [ widget.get() for widget in self.widgetlist]
コード例 #5
0
ファイル: main_window.py プロジェクト: pombredanne/happyboom
class MainWindow(QMainWindow):
    def __init__(self, app):
        QMainWindow.__init__(self)
        self.options = self.parseOptions()

        if self.options.debug:
            level = DEBUG
        elif self.options.verbose:
            level = INFO
        else:
            level = ERROR
        setupStdoutLog(level)

        self.app = app
        self.async_response = AsyncReponse()
        self.pages = []
        self.client = QtClient(self)
        self.setup()
        self.createWidgets()

    def _addPage(self, page):
        page.page_index = len(self.pages)
        self.pages.append(page)
        self.stacked.addWidget(page.widget)

    def createWidgets(self):
        self.stacked = QStackedWidget(self)

        self.game_list = GameList(self)
        self.create_game = CreateGame(self)
        self.setup_game = SetupGame(self)
        self.awale = Awale(self)
        self.mille_bornes = MilleBornes(self)

        self._addPage(self.game_list)
        self._addPage(self.create_game)
        self._addPage(self.setup_game)
        self._addPage(self.awale)
        self._addPage(self.mille_bornes)

        self.setCentralWidget(self.stacked)

    def parseOptions(self):
        parser = OptionParser(usage="%prog [options]")
        parser.add_option("--name",
            help='Player name (default: %s)' % DEFAULT_PLAYER_NAME,
            type="str", default=DEFAULT_PLAYER_NAME)
        parser.add_option("--host",
            help='Host name or IP (default: %s)' % DEFAULT_HOST,
            type="str", default=DEFAULT_HOST)
        parser.add_option("--port",
            help='Server TCP port (default: %s)' % DEFAULT_PORT,
            type="int", default=DEFAULT_PORT)
        parser.add_option("-v", "--verbose",
            help="Verbose mode",
            action="store_true", default=False)
        parser.add_option("--debug",
            help="Debug mode (don't call any service at startup)",
            action="store_true", default=False)
        parser.add_option("--create", metavar="GAME_TYPE",
            help="Create directly a game of type GAME_TYPE",
            type="str")
        parser.add_option("--join", metavar="GAME_ID",
            help="Join directly the game GAME_ID",
            type="int")
        options, arguments = parser.parse_args()
        if options.debug:
            options.verbose = True
        if arguments:
            parser.print_help()
            exit(1)
        return options

    def connectClient(self):
        self.client.connect(self.options.host, self.options.port)
        name = unicode(self.options.name)
        self.client.createPlayer(name)
        self.gotoGameListPage()

    def setup(self):
        self.app.setQuitOnLastWindowClosed(True)
        self.setWindowTitle(tr('Player %s') % self.options.name)

    def setActivePage(self, new_page):
        old_index = self.stacked.currentIndex()
        old_page = self.pages[old_index]
        old_page.exitPage()
        self.stacked.setCurrentIndex(new_page.page_index)
        new_page.enterPage()

    def gotoGameListPage(self):
        self.game_list.refresh()
        self.setActivePage(self.game_list)

    def gotoCreateGamePage(self):
        self.setActivePage(self.create_game)

    def gotoSetupGamePage(self, game):
        self.setup_game.init(game['id'], game['type'])
        self.setActivePage(self.setup_game)

    def gotoAwalePage(self, game_id):
        self.awale.init(game_id)
        self.setActivePage(self.awale)

    def gotoMilleBornesPage(self, game_id):
        self.mille_bornes.init(game_id)
        self.setActivePage(self.mille_bornes)

    def closeEvent(self, event):
        self.quit()

    def quit(self):
        self.client.quit()

    def infoPopup(self, text, title=None):
        if not title:
            title = tr("Information")
        QMessageBox.information(self, title, text)

    def errorPopup(self, text, title=None):
        if not title:
            title = tr("Error")
        QMessageBox.warning(self, title, text)

    def exception(self, err, title=None):
        text = exceptionAsUnicode(err)
        self.errorPopup(text, title)

    def main(self):
        create = self.options.create
        game_id = self.options.join
        if create:
            game = self.client.command(u'game_create',
                self.client.player_id, unicode(create), u'create')
            self.gotoSetupGamePage(game)
        elif game_id:
            game = self.client.command(u'game_info', [game_id])[0]
            self.client.command(u'game_join',
                game_id, self.client.player_id)
            self.gotoSetupGamePage(game)
        self.show()
コード例 #6
0
class NewSimulationWindow(QDialog):

    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.core = NewSimulationCore(self)
        self.create_widgets(parent)
        
        self.environments = []
        self.env_wid = {}  # Environment Name to Environment Widget
        self.env_obj = {}  # Environment Name to Environment Objects
        
        self.exec()
        
    def create_widgets(self, parent):
        
        # Layout
        GBuilder().set_props(self, min_sz_x=900, min_sz_y=700)
        self.setWindowTitle("Simulation Configuration")
        self.setFixedHeight(700)
        self.setFixedWidth(1350)
        main_lo = QVBoxLayout()
        self.setLayout(main_lo)

        # Label
        self.desc_label = GBuilder().label(self, "Create a new simulation. Create one or more environments and"\
                                           " fill them with components. Then connect the components.", None, None)
        self.desc_label.setFixedHeight(20)
        main_lo.addWidget(self.desc_label)
        
        # Horizontal Layout
        hl_1 = QHBoxLayout()
        main_lo.addLayout(hl_1)
        
        # Groupboxes
        self.components_gb = GBuilder().hand_groupbox(self, "Components", None, None)
        self.components_gb.setFixedWidth(300)
        self.environment_gb = GBuilder().groupbox(self, "Environments", None, None)
        hl_1.addWidget(self.components_gb)
        hl_1.addWidget(self.environment_gb)
        
        # Components Boxes
        self.comps_layout = QVBoxLayout()
        self.components_gb.setLayout(self.comps_layout)
        self._add_component_boxes()
               
        # Buttons
        main_lo.addWidget(GBuilder().hor_line(self))
        hl = QHBoxLayout()
        hl.addWidget(GBuilder().label(self, ""))
        ok_but = GBuilder().pushbutton(self, "OK", self._ok_hit)
        ok_but.setFixedWidth(150)
        ok_but.setFixedHeight(25)
        cancel_but = GBuilder().pushbutton(self, "Cancel", self._ok_hit)
        cancel_but.setFixedWidth(150)
        cancel_but.setFixedHeight(25)
        hl.addWidget(ok_but)
        hl.addWidget(cancel_but)
        main_lo.addLayout(hl)
        
        # Fill Components Boxes
        self._fill_ecu_boxes()
        self._fill_bus_boxes()
        self._fill_others_boxes()
        
        # Fill environment
        self._fill_environment_box()
        
        # Style 
        self._set_stle()
 
    def _add_component_boxes(self):
        
        # ECU Box
        self.ecu_box_wid = QScrollArea()
        wid = QWidget()
        self.ecu_box_wid.setWidget(wid)        
        self.ecu_box_wid.setWidgetResizable(True)               
        self.ecu_box = QGridLayout()
        wid.setLayout(self.ecu_box)   
        self.ecu_box_wid_wid = wid     
        self.comps_layout.addWidget(self.ecu_box_wid)

        # Bus Box
        self.bus_box_wid = QScrollArea()
        wid = QWidget()
        self.bus_box_wid.setWidget(wid)        
        self.bus_box_wid.setWidgetResizable(True)             
        self.bus_box = QGridLayout()
        wid.setLayout(self.bus_box)    
        self.bus_box_wid_wid = wid      
        self.comps_layout.addWidget(self.bus_box_wid)

        # Others Box
        self.others_box_wid = QScrollArea()
        wid = QWidget()
        self.others_box_wid.setWidget(wid)        
        self.others_box_wid.setWidgetResizable(True)       
        self.others_box = QGridLayout()
        wid.setLayout(self.others_box)
        self.others_box_wid_wid = wid  
        self.comps_layout.addWidget(self.others_box_wid)

    def _fill_ecu_boxes(self):
        
        # Creatable Objects
        kys = ECUFactory().createable_objects()   
        row = 0
        col = 0
        
        for ky in list(kys):                
            
            # Information gathering
            name = self._load_gui_name(ky, ECUFactory())  
            ico = self._load_gui_icon(ky, ECUFactory())                     
            
            # New Element per Object
            gb = GBuilder().groupbox(self, name, None, None)
            gb.setFont(QtGui.QFont('SansSerif', 7))
            gb.setFixedHeight(70)
            gb.setFixedWidth(70)            
            db = GBuilder().dragbutton(gb, '', self._add_component_boxes, ico, icon_x=45, icon_y=45, size_x=60, size_y=50, pos_x=5, pos_y=15)
            db.set_drop_func(self.core.add_ecu_box_to_env)
            db.set_move_icon_context_acts(self.core.load_context_menu_actions(ky))
            db.ecu_key = ky
            db.setCheckable(True)                
            db.setStyleSheet('QPushButton {background-color: #F2F2F2; color: red;border: 0px solid gray;border-radius: 12px;}')
            
            # Add to Layout
            self.ecu_box.addWidget(gb, row, col, Qt.AlignTop)            
            col += 1
            if col == 3:
                row += 1
                col = 0
                
        # Add Widget        
        self.ecu_box.addWidget(QWidget())
        
    def _fill_bus_boxes(self):
        
        kys = BusFactory().createable_objects()          
        
        row = 0
        col = 0
        
        for ky in list(kys):
            
            # Information gathering
            name = self._load_gui_name(ky, BusFactory())  
            ico = self._load_gui_icon(ky, BusFactory())                        
            
            # New Element per Object
            gb = GBuilder().groupbox(self, name, None, None)
            gb.setFont(QtGui.QFont('SansSerif', 7))
            gb.setFixedHeight(70)
            gb.setFixedWidth(70)            
            db = GBuilder().dragbutton(gb, '', self._add_component_boxes, ico, icon_x=45, icon_y=45, size_x=60, size_y=50, pos_x=5, pos_y=15)
            db.set_drop_func(self.core.add_bus_box_to_env)
            db.set_move_icon_context_acts(self.core.load_context_menu_actions(ky))
            db.ecu_key = ky
            db.setCheckable(True)
            db.setStyleSheet('QPushButton {background-color: #F2F2F2; color: red;border: 0px solid gray;border-radius: 12px;}')
            
            # Add to Layout
            self.bus_box.addWidget(gb, row, col, Qt.AlignTop)            
            col += 1
            if col == 3:
                row += 1
                col = 0
                
        # Add Widget        
        self.bus_box.addWidget(QWidget())
        
    def _fill_others_boxes(self):
        kys = ECUFactory().createable_objects()          
        
        row = 0
        col = 0

    def _fill_environment_box(self):
        
        # Main Layout
        main_lo = QVBoxLayout()        
        self.environment_gb.setLayout(main_lo)
                
        # Combobox
        lo, self.env_select_cb, lab = GBuilder().label_combobox(self, "Current Environment:", [], self._env_select_changed)
        hl = QHBoxLayout()
        hl.addLayout(lo)
        but = GBuilder().pushbutton(self, "New", self._new_env_hit)
        but.setFixedWidth(40)
        hl.addWidget(but)        
        lab.setFixedWidth(140)
        self.env_select_cb.setFixedHeight(22)  
        self.env_select_cb.setFixedWidth(350)      
        main_lo.addLayout(hl)
        
        # Groupbox (to make it look nicer)
        self.content_gb = EnvironmentView(self.environment_gb)    
        main_lo.addWidget(self.content_gb)
        self.content_gb.setFixedHeight(550)  
        self.content_gb.setFixedWidth(1000)  
        self.content_gb.setLayout(lo)
        
        # QStackedWidget with environments
        self.stacked_env = QStackedWidget()
        lo.addWidget(self.stacked_env)
       

    def _set_stle(self):
        
        self.content_gb.setStyleSheet('QGroupBox {background-color: #F2F2F2; color: red; border: 2px solid gray;border-radius: 12px;} EnvironmentView {background-color: #F2F2F2; color: red; border: 2px solid gray;border-radius: 12px;}')

        self.ecu_box_wid_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}')
        self.ecu_box_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}')
         
        self.bus_box_wid_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}')
        self.bus_box_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}')
         
        self.others_box_wid_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}')
        self.others_box_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}')
        
    def _ok_hit(self):
        
        # 1. Create environments using defined processing methods
        environments_list = NewSimulationCore().run_processes()        
        
        # 2. Save environments via API / Load them via API as well

        self.close()
        
    def _cancel_hit(self):
        print("Cancel")
        self.close()
        
    def _new_env_hit(self):
        
        # Add to list
        nr = len(self.environments)
        self.environments.append("Environment %s" % nr)        
        self.env_select_cb.addItem(self.environments[-1])
        self.env_select_cb.setCurrentIndex(nr)
        
        # Create new Stacked widget entry
        wid = QWidget()
        self.stacked_env.addWidget(wid)
        self.env_wid["Environment %s" % nr] = wid
        
        lo = QVBoxLayout()

        wid.setLayout(lo)
        self.stacked_env.setCurrentIndex(nr)

    def _env_select_changed(self):
        idx = self.env_select_cb.currentIndex()        
        self.stacked_env.setCurrentIndex(idx)        
        NewSimulationCore().selected_env = self.env_select_cb.currentText()
        self.content_gb.selected_env = self.env_select_cb.currentText()
        
        self._show_env(NewSimulationCore().selected_env, NewSimulationCore().env_map)
        
    def _get_env_elem_by_icon(self, env_elems, move_icon):        
        for elem in env_elems:            
            if str(elem.move_icon) == str(move_icon):
                return elem
        return None 
        
    def _load_gui_name(self, ky, factory):
        try:                                 
            cls = factory.get_class(ky)
            name = cls.GUI_NAME
        except:
            name = ky
        return name
    
    def _load_gui_icon(self, ky, factory):
        try:                                 
            cls = factory.get_class(ky)
            name = cls.GUI_ICON
        except:
            name = os.getcwd() + r'/icons/standard_ecu.png'
        return name

    def _show_env(self, selected_env, env_map):
        
        GBuilder().update_connected(self.content_gb, self.environment_gb.pos(), self.content_gb.pos(), self.content_gb.selected_env)
        
        # Mainwindow
        for chil in self.children():
            if isinstance(chil, DragLabel):
                try:
                    a = self._get_env_elem_by_icon(env_map[selected_env], chil)   
                    
                    if a == None:
                        chil.hide()
                    else:
                        chil.show()
                except:
                    chil.hide()
コード例 #7
0
class clockWidget(QWidget):
    """The widget that displays the quote and author"""
    def __init__(self, parent=None, fixedTime=''):
        self.fixedTime = fixedTime
        self.default_quote_font_size = 40
        self.default_author_font_size = 37
        self.min_font_size = 10

        QWidget.__init__(self)
        #set up the main quote area
        self.stackIndex = 0
        self.setObjectName("clockWidget")
        self.setStyleSheet(myStyleSheet)
        vlayout = QVBoxLayout()
        self.font = QFont()
        self.font.setFamily("Times")
        self.font.setPointSize(self.default_quote_font_size)
        self.font.setBold(False)
        self.font.setWeight(50)
        self.timeLabel = QTextEdit()
        self.timeLabel.setFixedSize(750, 340)  # 400)
        self.timeLabel.setFont(self.font)
        self.timeLabel.setObjectName("timeLabel")
        self.timeLabel.setText("Some great quote goes here!")
        self.timeLabel.setReadOnly(True)
        self.timeLabel.mousePressEvent = self.toggleStack
        self.timeLabel.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #we make this a stack widget so we can display the quit button and quote, dialog boxes are ugly with full screen apps
        self.stack = QStackedWidget()
        self.stack.addWidget(self.timeLabel)
        self.quitWidget = quitW()
        self.stack.addWidget(self.quitWidget)
        self.stack.setCurrentIndex(self.stackIndex)
        vlayout.addWidget(self.stack)
        #set up the author area
        self.authLabel = QTextEdit()
        self.authLabel.setFixedSize(680, 81)
        self.fonta = QFont()
        self.fonta.setFamily("Times")
        self.fonta.setPointSize(self.default_author_font_size)
        self.authLabel.setFont(self.fonta)
        self.authLabel.setObjectName("authorLabel")
        self.authLabel.setText("Title, Author")
        self.authLabel.setAlignment(Qt.AlignRight)
        self.authLabel.setReadOnly(True)
        self.authLabel.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        vlayout.addWidget(self.authLabel)
        #add the layouts to the widget
        mainLayout = QGridLayout()
        mainLayout.addLayout(vlayout, 0, 1)
        self.setLayout(mainLayout)
        self.loadData()
        #set up the timer to run every second
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.Time)
        self.currentMin = 61  #to ensure it triggers time diff check at start up
        self.Time()
        self.timer.start(1000)

    def closeEvent(self, event):
        log.debug("Form close event")
        self.timer.stop()
        event.accept()

    @pyqtSlot()
    def toggleStack(self, event):
        #print('toggle')
        self.stack.setCurrentIndex(1)
        QTimer.singleShot(3000, self.toggleStackOff)

    def toggleStackOff(self):
        self.stack.setCurrentIndex(0)

    def Time(self):
        #check to see if the minute has updated from last time, if so run setTime()
        if datetime.now().minute != self.currentMin:
            self.currentMin = datetime.now().minute
            self.setTime(datetime.now().strftime('%H:%M'))
            log.debug('Update min {}'.format(self.currentMin))

    def loadData(self):
        #load the data from the json files into a dict. It would have been easier if it was one big file, but its a file per minute
        self.quote_data = dict()

        for hours in range(24):
            for mins in range(60):
                time = "{:02d}:{:02d}".format(hours, mins)
                filename = "docs/times/{:s}.json".format(time)
                try:
                    with open(filename, 'r') as jfile:
                        self.quote_data[time] = json.load(jfile)
                except Exception:
                    log.error('Cannot load {}'.format(filename))

    def _getQuote(self, time_str):
        #get a select a quote for the time, some times have multiple quotes so pick one at random
        return random.choice(self.quote_data[time_str])

    def setTime(self, time_str):
        #set default font sizes - might get reduced later
        self.font.setPointSize(self.default_quote_font_size)
        self.timeLabel.setFont(self.font)

        self.fonta.setPointSize(self.default_author_font_size)
        self.authLabel.setFont(self.fonta)
        #fixTime is set from the command line as is for debug
        if not self.fixedTime:
            qt = self._getQuote(time_str)
        else:
            qt = self._getQuote(self.fixedTime)
            log.debug('fixed time')
        #set up the html for the quotes and authors
        qstr = u"{:s} <b><em><font color =\"white\">{:s}</font></em></b> {:s}".format(
            qt['quote_first'], qt['quote_time_case'], qt['quote_last'])
        log.info(qstr)
        self.timeLabel.setHtml(qstr)
        authStr = u"- {:s}, <em><font color =\"white\">{:s}</font></em>".format(
            qt['title'], qt['author'])
        self.authLabel.setHtml(authStr)
        self.authLabel.setAlignment(Qt.AlignRight)
        log.info(authStr)
        #now the tricky bit, resize the fonts for the quote and author text to ensure it fits into the text boxes
        fs = self.default_quote_font_size
        log.debug('quote')
        while True:
            h = self.timeLabel.document().size().height()
            met = QFontMetrics(self.font)
            bb = met.boundingRect(self.timeLabel.geometry(), Qt.TextWordWrap,
                                  qstr)
            h = bb.height()

            if h > self.timeLabel.size().height():
                fs = fs - 1
                if fs <= self.min_font_size:
                    log.debug('Min font size reached')
                    break
                self.font.setPointSize(fs)
                self.timeLabel.setFont(self.font)
            else:
                break
        log.debug('author')
        fs = self.default_author_font_size
        while True:
            h = self.authLabel.document().size().height()
            met = QFontMetrics(self.fonta)
            bb = met.boundingRect(self.authLabel.geometry(), Qt.TextWordWrap,
                                  authStr)
            h = bb.height()

            if h > self.authLabel.size().height():

                fs = fs - 1
                if fs <= self.min_font_size:
                    log.debug('Min font size reached')
                    break
                self.fonta.setPointSize(fs)
                self.authLabel.setFont(self.fonta)
            else:  #make the font a bit smaller still if possible
                if fs > self.min_font_size + 4:
                    fs = fs - 4
                    self.fonta.setPointSize(fs)
                    self.authLabel.setFont(self.fonta)
                break
コード例 #8
0
class MixerPanel(QtGui.QFrame):
    '''A color mixer to hook up to an image.
    You pass the image you the panel to operate on
    and it operates on that image in place. You also
    pass a callback to be called to trigger a refresh.
    This callback is called every time the mixer modifies
    your image.'''
    def __init__(self, img):
        QtGui.QFrame.__init__(self)
        #self.setFrameStyle(QtGui.QFrame.Box|QtGui.QFrame.Sunken)

        self.img = img
        self.mixer = ColorMixer(self.img)
        self.callback = None

        #---------------------------------------------------------------
        # ComboBox
        #---------------------------------------------------------------

        self.combo_box_entries = ['RGB Color', 'HSV Color',
                                  'Brightness/Contrast',
                                  'Gamma',
                                  'Gamma (Sigmoidal)']
        self.combo_box = QtGui.QComboBox()
        for entry in self.combo_box_entries:
            self.combo_box.addItem(entry)
        self.combo_box.currentIndexChanged.connect(self.combo_box_changed)

        #---------------------------------------------------------------
        # RGB color sliders
        #---------------------------------------------------------------

        # radio buttons
        self.rgb_add = QtGui.QRadioButton('Additive')
        self.rgb_mul = QtGui.QRadioButton('Multiplicative')
        self.rgb_mul.toggled.connect(self.rgb_radio_changed)
        self.rgb_add.toggled.connect(self.rgb_radio_changed)

        # sliders
        rs = IntelligentSlider('R', 0.51, -255, self.rgb_changed)
        gs = IntelligentSlider('G', 0.51, -255, self.rgb_changed)
        bs = IntelligentSlider('B', 0.51, -255, self.rgb_changed)
        self.rs = rs
        self.gs = gs
        self.bs = bs

        self.rgb_widget = QWidget()
        self.rgb_widget.layout = QGridLayout(self.rgb_widget)
        self.rgb_widget.layout.addWidget(self.rgb_add, 0, 0, 1, 3)
        self.rgb_widget.layout.addWidget(self.rgb_mul, 1, 0, 1, 3)
        self.rgb_widget.layout.addWidget(self.rs, 2, 0)
        self.rgb_widget.layout.addWidget(self.gs, 2, 1)
        self.rgb_widget.layout.addWidget(self.bs, 2, 2)


        #---------------------------------------------------------------
        # HSV sliders
        #---------------------------------------------------------------

        # radio buttons
        self.hsv_add = QtGui.QRadioButton('Additive')
        self.hsv_mul = QtGui.QRadioButton('Multiplicative')
        self.hsv_mul.toggled.connect(self.hsv_radio_changed)
        self.hsv_mul.toggled.connect(self.hsv_radio_changed)

        # sliders
        hs = IntelligentSlider('H', 0.36, -180, self.hsv_changed)
        ss = IntelligentSlider('S', 0.002, 0, self.hsv_changed)
        vs = IntelligentSlider('V', 0.002, 0, self.hsv_changed)
        self.hs = hs
        self.ss = ss
        self.vs = vs

        self.hsv_widget = QWidget()
        self.hsv_widget.layout = QGridLayout(self.hsv_widget)
        self.hsv_widget.layout.addWidget(self.hsv_add, 0, 0, 1, 3)
        self.hsv_widget.layout.addWidget(self.hsv_mul, 1, 0, 1, 3)
        self.hsv_widget.layout.addWidget(self.hs, 2, 0)
        self.hsv_widget.layout.addWidget(self.ss, 2, 1)
        self.hsv_widget.layout.addWidget(self.vs, 2, 2)


        #---------------------------------------------------------------
        # Brightness/Contrast sliders
        #---------------------------------------------------------------

        # sliders
        cont = IntelligentSlider('x', 0.002, 0, self.bright_changed)
        bright = IntelligentSlider('+', 0.51, -255, self.bright_changed)
        self.cont = cont
        self.bright = bright

        # layout
        self.bright_widget = QWidget()
        self.bright_widget.layout = QtGui.QGridLayout(self.bright_widget)
        self.bright_widget.layout.addWidget(self.cont, 0, 0)
        self.bright_widget.layout.addWidget(self.bright, 0, 1)


        #-----------------------------------------------------------------------
        # Gamma Slider
        #-----------------------------------------------------------------------
        gamma = IntelligentSlider('gamma', 0.005, 0, self.gamma_changed)
        self.gamma = gamma

        # layout
        self.gamma_widget = QWidget()
        self.gamma_widget.layout = QtGui.QGridLayout(self.gamma_widget)
        self.gamma_widget.layout.addWidget(self.gamma, 0, 0)


        #---------------------------------------------------------------
        # Sigmoid Gamma sliders
        #---------------------------------------------------------------

        # sliders
        alpha = IntelligentSlider('alpha', 0.011, 1, self.sig_gamma_changed)
        beta = IntelligentSlider('beta', 0.012, 0, self.sig_gamma_changed)
        self.a_gamma = alpha
        self.b_gamma = beta

        # layout
        self.sig_gamma_widget = QWidget()
        self.sig_gamma_widget.layout = QtGui.QGridLayout(self.sig_gamma_widget)
        self.sig_gamma_widget.layout.addWidget(self.a_gamma, 0, 0)
        self.sig_gamma_widget.layout.addWidget(self.b_gamma, 0, 1)

        #---------------------------------------------------------------
        # Buttons
        #---------------------------------------------------------------
        self.commit_button = QtGui.QPushButton('Commit')
        self.commit_button.clicked.connect(self.commit_changes)
        self.revert_button = QtGui.QPushButton('Revert')
        self.revert_button.clicked.connect(self.revert_changes)

        #---------------------------------------------------------------
        # Mixer Layout
        #---------------------------------------------------------------
        self.sliders = QStackedWidget()
        self.sliders.addWidget(self.rgb_widget)
        self.sliders.addWidget(self.hsv_widget)
        self.sliders.addWidget(self.bright_widget)
        self.sliders.addWidget(self.gamma_widget)
        self.sliders.addWidget(self.sig_gamma_widget)

        self.layout = QtGui.QGridLayout(self)
        self.layout.addWidget(self.combo_box, 0, 0)
        self.layout.addWidget(self.sliders, 1, 0)
        self.layout.addWidget(self.commit_button, 2, 0)
        self.layout.addWidget(self.revert_button, 3, 0)

        #---------------------------------------------------------------
        # State Initialization
        #---------------------------------------------------------------

        self.combo_box.setCurrentIndex(0)
        self.rgb_mul.setChecked(True)
        self.hsv_mul.setChecked(True)


    def set_callback(self, callback):
        self.callback = callback

    def combo_box_changed(self, index):
        self.sliders.setCurrentIndex(index)
        self.reset()

    def rgb_radio_changed(self):
        self.reset()

    def hsv_radio_changed(self):
        self.reset()

    def reset(self):
        self.reset_sliders()
        self.mixer.set_to_stateimg()
        if self.callback:
            self.callback()

    def reset_sliders(self):
        # handle changing the conversion factors necessary
        if self.rgb_add.isChecked():
            self.rs.set_conv_fac(0.51, -255)
            self.rs.set_value(0)
            self.gs.set_conv_fac(0.51, -255)
            self.gs.set_value(0)
            self.bs.set_conv_fac(0.51, -255)
            self.bs.set_value(0)
        else:
            self.rs.set_conv_fac(0.002, 0)
            self.rs.set_value(1.)
            self.gs.set_conv_fac(0.002, 0)
            self.gs.set_value(1.)
            self.bs.set_conv_fac(0.002, 0)
            self.bs.set_value(1.)

        self.hs.set_value(0)
        if self.hsv_add.isChecked():
            self.ss.set_conv_fac(0.002, -1)
            self.ss.set_value(0)
            self.vs.set_conv_fac(0.002, -1)
            self.vs.set_value(0)
        else:
            self.ss.set_conv_fac(0.002, 0)
            self.ss.set_value(1.)
            self.vs.set_conv_fac(0.002, 0)
            self.vs.set_value(1.)

        self.bright.set_value(0)
        self.cont.set_value(1.)

        self.gamma.set_value(1)
        self.a_gamma.set_value(1)
        self.b_gamma.set_value(0.5)


    def rgb_changed(self, name, val):
        if name == 'R':
            channel = self.mixer.RED
        elif name == 'G':
            channel = self.mixer.GREEN
        else:
            channel = self.mixer.BLUE

        if self.rgb_mul.isChecked():
            self.mixer.multiply(channel, val)
        elif self.rgb_add.isChecked():
            self.mixer.add(channel, val)
        else:
            pass

        if self.callback:
            self.callback()

    def hsv_changed(self, name, val):
        h = self.hs.val()
        s = self.ss.val()
        v = self.vs.val()

        if self.hsv_mul.isChecked():
            self.mixer.hsv_multiply(h, s, v)
        elif self.hsv_add.isChecked():
            self.mixer.hsv_add(h, s, v)
        else:
            pass

        if self.callback:
            self.callback()

    def bright_changed(self, name, val):
        b = self.bright.val()
        c = self.cont.val()
        self.mixer.brightness(c, b)

        if self.callback:
            self.callback()

    def gamma_changed(self, name, val):
        self.mixer.gamma(val)

        if self.callback:
            self.callback()

    def sig_gamma_changed(self, name, val):
        ag = self.a_gamma.val()
        bg = self.b_gamma.val()
        self.mixer.sigmoid_gamma(ag, bg)

        if self.callback:
            self.callback()

    def commit_changes(self):
        self.mixer.commit_changes()
        self.reset_sliders()

    def revert_changes(self):
        self.mixer.revert()
        self.reset_sliders()

        if self.callback:
            self.callback()
コード例 #9
0
ファイル: preferences.py プロジェクト: Garjy/edis
class Preferences(QDialog):

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Configuraciones - Edis"))
        self.__sections = []
        # Opacity effect
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        self.animation = QPropertyAnimation(self.effect, "opacity")

        Edis.load_component("preferences", self)
        # Install sections
        #lint:disable
        from src.ui.dialogs.preferences import (
            environment_configuration,
            editor_configuration,
            compiler_configuration
            )
        #lint:enable
        self.load_ui()
        key_escape = QShortcut(QKeySequence(Qt.Key_Escape), self)
        self.connect(key_escape, SIGNAL("activated()"), self.close)
        self.connect(self.btn_cancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btn_guardar, SIGNAL("clicked()"), self._save)

    def install_section(self, obj):
        self.__sections.append(obj)

    def load_ui(self):
        container = QVBoxLayout(self)

        box = QHBoxLayout()
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)
        toolbar = QToolBar()
        toolbar.setToolButtonStyle(3)
        toolbar.setOrientation(Qt.Vertical)
        toolbar.setIconSize(QSize(30, 30))
        toolbar.setObjectName("preferencias")

        environment_section = toolbar.addAction(
            QIcon(":image/general-pref"), "Entorno")
        editor_section = toolbar.addAction(
            QIcon(":image/editor-pref"), "Editor")
        compiler_section = toolbar.addAction(
            QIcon(":image/compiler-pref"), "Compilador")
        self.connect(environment_section, SIGNAL("triggered()"),
                     lambda: self.change_widget(0))
        self.connect(editor_section, SIGNAL("triggered()"),
                     lambda: self.change_widget(1))
        self.connect(compiler_section, SIGNAL("triggered()"),
                     lambda: self.change_widget(2))

        # Set size
        for action in toolbar.actions():
            widget = toolbar.widgetForAction(action)
            widget.setFixedSize(80, 50)

        box.addWidget(toolbar)

        self.stack = QStackedWidget()
        box.addWidget(self.stack)

        # Load sections and subsections
        for section in self.__sections:
            for name, obj in list(section.get_tabs().items()):
                section.install_tab(obj, name)
            self.stack.addWidget(section)

        box_buttons = QHBoxLayout()
        box_buttons.setMargin(10)
        box_buttons.setSpacing(10)
        box_buttons.addStretch(1)
        self.btn_cancel = QPushButton(self.tr("Cancelar"))
        self.btn_guardar = QPushButton(self.tr("Guardar"))
        box_buttons.addWidget(self.btn_cancel)
        box_buttons.addWidget(self.btn_guardar)
        container.addLayout(box)
        container.addLayout(box_buttons)

    def change_widget(self, index):
        if not self.isVisible():
            self.show()
        self.stack.setCurrentIndex(index)

    def _save(self):
        for index in range(self.stack.count()):
            self.stack.widget(index).save()
        self.close()

    def close(self):
        super(Preferences, self).close()
        self.emit(SIGNAL("configurationsClose(PyQt_PyObject)"), self)

    def showEvent(self, event):
        super(Preferences, self).showEvent(event)
        self.animation.setDuration(400)
        self.animation.setStartValue(0)
        self.animation.setEndValue(1)
        self.animation.start()
コード例 #10
0
ファイル: Gui.py プロジェクト: hackerj/Treasure-Hunting-Game
class Gui(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        #Set size of window and make it non-resizeable
        MainWindow.resize(818, 665)
        MainWindow.setFixedHeight(665)
        MainWindow.setFixedWidth(818)
        
        MainWindow.setWindowTitle("Map Master: Search for the Lost City")
        MainWindow.setWindowIcon(QIcon("icon_medium.ico"))

        #Set window backgrounds
        self.background = QLabel(MainWindow)
        
        
        self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png"))
        self.backgroundPixmapSettings = QPixmap(normpath(
                                            "images/gameMenuSettings2.png"))
        self.background.setPixmap(self.backgroundPixmapMenu)       
        
        self.background.setGeometry(QtCore.QRect(0, 0, 818, 665))
        
        self.popupPixmap = QPixmap(normpath("images/popupBG.png"))
        
        font = QFont()
        if "linux" in platform:
            font.setFamily("Century Schoolbook L")
        else:
            font.setFamily("Century Schoolbook")
        
        
        #Stylesheet settings for labels and buttons
        self.fg = "QLabel {color:black}"
        self.fgb = "QPushButton {color:black}"

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        #Main Menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        
        self.startButton = QPushButton(self.menuPage)
        self.startButton.setStyleSheet(self.fgb)
        self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60))
        self.startButton.setText(QApplication.translate("MainWindow", 
                                 "Start Game", None, QApplication.UnicodeUTF8))
        self.startButton.setObjectName("startButton")
        font.setPointSize(15)
        
        self.startButton.setFont(font)
        self.loadButton = QPushButton(self.menuPage)
        self.loadButton.setStyleSheet(self.fgb)
        self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60))
        self.loadButton.setText(QApplication.translate("MainWindow", 
                                "Load Game", None, QApplication.UnicodeUTF8))
        self.loadButton.setObjectName("loadButton")
        self.loadButton.setFont(font)
        
        self.settingsButton = QPushButton(self.menuPage)
        self.settingsButton.setStyleSheet(self.fgb)
        self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60))
        self.settingsButton.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.settingsButton.setObjectName("settingsButton")
        self.settingsButton.setFont(font)
        
        self.quitButton = QPushButton(self.menuPage)
        self.quitButton.setStyleSheet(self.fgb)
        self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60))
        self.quitButton.setText(QApplication.translate("MainWindow", 
                                "Quit", None, QApplication.UnicodeUTF8))
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setFont(font)
        
        self.instrButton = QPushButton(self.menuPage)
        self.instrButton.setStyleSheet(self.fgb)
        self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60))
        self.instrButton.setText(QApplication.translate("MainWindow", 
                               "Instructions", None, QApplication.UnicodeUTF8))
        self.instrButton.setObjectName("instrButton")
        self.instrButton.setFont(font)
        self.stackedWidget.addWidget(self.menuPage)
        
        #Settings page
        self.settingsPage = QWidget()
        self.settingsPage.setObjectName("settingsPage")
        self.volumeSlider = QSlider(self.settingsPage)
        self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30))
        self.volumeSlider.setProperty("value", 50)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.soundLabel = QLabel(self.settingsPage)
        self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30))
        font.setPointSize(20)
        self.soundLabel.setFont(font)
        self.soundLabel.setStyleSheet(self.fg)
        self.soundLabel.setText(QApplication.translate("MainWindow", 
                                "Volume", None, QApplication.UnicodeUTF8))
        self.soundLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.soundLabel.setObjectName("soundLabel")
        
        #Quiet Sound Graphic
        self.quietGraphic = QLabel(self.settingsPage)
        self.quietGraphic.setPixmap(QPixmap(normpath(
                                    "images/speakerQuiet.png")))
        self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80))
        self.quietGraphic.setObjectName("quietGraphic")
        
        #Loud Sound Graphic
        self.loudGraphic = QLabel(self.settingsPage)
        self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png")))
        self.loudGraphic.setEnabled(True)
        self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80))
        self.loudGraphic.setObjectName("loudGraphic")
        
        self.settingsLabel = QLabel(self.settingsPage)
        self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.settingsLabel.setFont(font)
        self.settingsLabel.setStyleSheet(self.fg)
        self.settingsLabel.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.settingsLabel.setObjectName("settingsLabel")
        self.doneButton = QPushButton(self.settingsPage)
        self.doneButton.setStyleSheet(self.fgb)
        self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton.setText(QApplication.translate("MainWindow", 
                                "Done", None, QApplication.UnicodeUTF8))
        self.doneButton.setObjectName("doneButton")
        font.setPointSize(15)
        self.doneButton.setFont(font)
        self.stackedWidget.addWidget(self.settingsPage)
        
        self.soundManager = Sounds(self.volumeSlider.sliderPosition())
        
        #Main Game page
        self.mainPage = QWidget()
        self.mainPage.setObjectName("mainPage")
        
        #Person View
        self.personView = ViewGraphics(self.mainPage)
        self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500))
        self.personView.setObjectName("personView")
        
        #Map View
        self.mapView = ViewGraphics(self.mainPage)
        self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500))
        self.mapView.setObjectName("mapView")
        
        #ClueView
        self.clueView = QLabel(self.mainPage)
        self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91))
        self.clueView.setObjectName("clueView")
        font.setPointSize(20)
        self.clueView.setFont(font)
        self.clueView.setStyleSheet(self.fg)
        
        #Map Toggles
        self.latLongCheck = QCheckBox(self.mainPage)
        self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 103, 41))
        self.latLongCheck.setText(QApplication.translate("MainWindow", 
                                  "Latitude/ \n"
                                  "Longitude", None, QApplication.UnicodeUTF8))
        self.latLongCheck.setObjectName("latLongCheck")
        font.setPointSize(12)
        self.latLongCheck.setFont(font)
        self.latLongCheck.setFocusPolicy(QtCore.Qt.NoFocus)

        self.colorCheck = QCheckBox(self.mainPage)
        self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41))
        self.colorCheck.setText(QApplication.translate("MainWindow", 
                                "Color\n"
                                "Coding", None, QApplication.UnicodeUTF8))
        self.colorCheck.setObjectName("colorCheck")
        self.colorCheck.setFont(font)
        self.colorCheck.setFocusPolicy(QtCore.Qt.NoFocus)
        
        self.legendCheck = QCheckBox(self.mainPage)
        self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22))
        self.legendCheck.setText(QApplication.translate("MainWindow", 
                                 "Legend", None, QApplication.UnicodeUTF8))
        self.legendCheck.setObjectName("legendCheck")
        self.legendCheck.setFocusPolicy(QtCore.Qt.NoFocus)
        
        font.setPointSize(12)
        self.legendCheck.setFont(font)
        self.searchButton = QPushButton(self.mainPage)
        self.searchButton.setStyleSheet(self.fgb)
        self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 55))
        self.searchButton.setText(QApplication.translate("MainWindow", 
                                  "Search", None, QApplication.UnicodeUTF8))
        self.searchButton.setObjectName("searchButton")
        font.setPointSize(15)
        self.searchButton.setFont(font)
        self.searchButton.setFocusPolicy(QtCore.Qt.NoFocus)
        
        #Score pieces
        self.scoreBox = QLabel(self.mainPage)
        self.scoreBox.setStyleSheet(self.fg)
        self.scoreBox.setGeometry(QtCore.QRect(720, 570, 71, 41))
        self.scoreBox.setObjectName("scoreBox")
        self.scoreBox.setText(QApplication.translate("MainWindow", 
                              "0", None, QApplication.UnicodeUTF8))
        self.scoreBox.setFont(font)
        self.scoreLabel = QLabel(self.mainPage)
        self.scoreLabel.setStyleSheet(self.fg)
        self.scoreLabel.setGeometry(QtCore.QRect(650, 580, 70, 17))
        self.scoreLabel.setText(QApplication.translate("MainWindow", 
                                "Score:", None, QApplication.UnicodeUTF8))
        self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreLabel.setObjectName("scoreLabel")
        self.scoreLabel.setFont(font)
        
        self.popup = ViewGraphics(self.mainPage)
        self.popup.setStyleSheet(
                "QGraphicsView {background:transparent;border-style:none}")
        self.popupImage = self.popup.scene.addPixmap(self.popupPixmap)
        self.popup.setGeometry(QtCore.QRect(25, 25, 750, 450))
        self.popup.setObjectName("popupLabel")
        font.setPointSize(25)
        self.popupText = self.popup.scene.addText("", font)
        self.textColor = QColor('black')
        self.popupText.setDefaultTextColor(self.textColor)
        self.popupText.setX(350)
        self.popupText.setY(225)
        self.popupImage.setOpacity(0)
        self.popupText.setOpacity(0)
        self.stackedWidget.addWidget(self.mainPage)
        
        #Help page
        self.helpPage = QWidget()
        self.helpPage.setObjectName("helpPage")
        self.HelpLabel = QLabel(self.helpPage)
        self.HelpLabel.setStyleSheet(self.fg)
        self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.HelpLabel.setFont(font)
        self.HelpLabel.setText(QApplication.translate("MainWindow", 
                               "Instructions", None, QApplication.UnicodeUTF8))
        self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.HelpLabel.setObjectName("HelpLabel")
        self.wInstr = QLabel(self.helpPage)
        self.wInstr.setStyleSheet(self.fg)
        self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30))
        font.setPointSize(20)
        self.wInstr.setFont(font)
        self.wInstr.setText(QApplication.translate("MainWindow", 
                            "W", None, QApplication.UnicodeUTF8))
        self.wInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr.setObjectName("wInstr")
        self.sInstr = QLabel(self.helpPage)
        self.sInstr.setStyleSheet(self.fg)
        self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30))
        self.sInstr.setFont(font)
        self.sInstr.setText(QApplication.translate("MainWindow", 
                            "S", None, QApplication.UnicodeUTF8))
        self.sInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr.setObjectName("sInstr")
        self.aInstr = QLabel(self.helpPage)
        self.aInstr.setStyleSheet(self.fg)
        self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30))
        self.aInstr.setFont(font)
        self.aInstr.setText(QApplication.translate("MainWindow", 
                            "A", None, QApplication.UnicodeUTF8))
        self.aInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr.setObjectName("aInstr")
        self.dInstr = QLabel(self.helpPage)
        self.dInstr.setStyleSheet(self.fg)
        self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30))
        self.dInstr.setFont(font)
        self.dInstr.setText(QApplication.translate("MainWindow", 
                            "D", None, QApplication.UnicodeUTF8))
        self.dInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr.setObjectName("dInstr")
        self.wInstr2 = QLabel(self.helpPage)
        self.wInstr2.setStyleSheet(self.fg)
        self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30))
        self.wInstr2.setFont(font)
        self.wInstr2.setText(QApplication.translate("MainWindow", 
                            "Move North", None, QApplication.UnicodeUTF8))
        self.wInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr2.setObjectName("wInstr2")
        self.sInstr2 = QLabel(self.helpPage)
        self.sInstr2.setStyleSheet(self.fg)
        self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30))
        self.sInstr2.setFont(font)
        self.sInstr2.setText(QApplication.translate("MainWindow", 
                            "Move South", None, QApplication.UnicodeUTF8))
        self.sInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr2.setObjectName("sInstr2")
        self.aInstr2 = QLabel(self.helpPage)
        self.aInstr2.setStyleSheet(self.fg)
        self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30))
        self.aInstr2.setFont(font)
        self.aInstr2.setText(QApplication.translate("MainWindow", 
                            "Move West", None, QApplication.UnicodeUTF8))
        self.aInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr2.setObjectName("aInstr2")
        self.dInstr2 = QLabel(self.helpPage)
        self.dInstr2.setStyleSheet(self.fg)
        self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30))
        self.dInstr2.setFont(font)
        self.dInstr2.setText(QApplication.translate("MainWindow", 
                            "Move East", None, QApplication.UnicodeUTF8))
        self.dInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2.setObjectName("dInstr2")
        self.searchInstr = QPushButton(self.helpPage)
        self.searchInstr.setStyleSheet(self.fgb)
        self.searchInstr.setEnabled(True)
        self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30))
        self.searchInstr.setText(QApplication.translate("MainWindow", 
                                "Search", None, QApplication.UnicodeUTF8))
        self.searchInstr.setAutoDefault(False)
        self.searchInstr.setDefault(False)
        self.searchInstr.setFlat(False)
        self.searchInstr.setObjectName("searchInstr")
        font.setPointSize(15)
        self.searchInstr.setFont(font)
        self.dInstr2_2 = QLabel(self.helpPage)
        self.dInstr2_2.setStyleSheet(self.fg)
        self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30))
        font.setPointSize(20)
        self.dInstr2_2.setFont(font)
        self.dInstr2_2.setText(QApplication.translate("MainWindow", 
                           "Search for clues", None, QApplication.UnicodeUTF8))
        self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2_2.setObjectName("dInstr2_2")
        self.doneButton2 = QPushButton(self.helpPage)
        self.doneButton2.setStyleSheet(self.fgb)
        self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton2.setText(QApplication.translate("MainWindow", 
                                 "Done", None, QApplication.UnicodeUTF8))
        self.doneButton2.setObjectName("doneButton2")
        font.setPointSize(15)
        self.doneButton2.setFont(font)
        self.stackedWidget.addWidget(self.helpPage)
        
        #Credits page
        self.creditsPage = QWidget()
        self.creditsPage.setObjectName("creditsPage")
        self.creditsLabel = QLabel(self.creditsPage)
        self.creditsLabel.setStyleSheet(self.fg)
        self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.creditsLabel.setFont(font)
        self.creditsLabel.setText(QApplication.translate("MainWindow", 
                                  "Credits", None, QApplication.UnicodeUTF8))
        self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.creditsLabel.setObjectName("creditsLabel")
        self.credits = QLabel(self.creditsPage)
        self.credits.setStyleSheet(self.fg)
        self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400))
        font.setPointSize(20)
        self.credits.setFont(font)
        self.credits.setText(QApplication.translate("MainWindow", 
        "Gary Lent\n"
        "Grant Stafford\n"
        "Jessie Liu\n"
        "Peter Andrien\n"
        "Nokia (Qt4 framework)\n"
        "Riverbank Computing Ltd (PyQt)\n"
        "Celestial Aeon Project", None, QApplication.UnicodeUTF8))
        self.credits.setAlignment(
                QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.credits.setObjectName("credits")
        self.doneButton3 = QPushButton(self.creditsPage)
        self.doneButton3.setStyleSheet(self.fgb)
        self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton3.setText(QApplication.translate("MainWindow", 
                                "Done", None, QApplication.UnicodeUTF8))
        self.doneButton3.setObjectName("doneButton3")
        font.setPointSize(15)
        self.doneButton3.setFont(font)
        self.stackedWidget.addWidget(self.creditsPage)
        
        #Story page
        self.storyPage = QWidget()
        self.storyPage.setObjectName("storyPage")
        self.storyLabel = QLabel(self.storyPage)
        self.storyLabel.setStyleSheet(self.fg)
        self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400))
        font.setPointSize(25)
        self.storyLabel.setFont(font)
        self.storyLabel.setText(QApplication.translate("MainWindow", 
        "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently"
        " lost my job, but stumbled\n on a clue that may change my life"
        " \nforever. I've set off on a quest - a quest\n to find a lost city. "
        "I've found a clue,\n and believe there may be more.\n Help me find "
        "the lost city.  ", None, QApplication.UnicodeUTF8))
        self.storyLabel.setAlignment(
                QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.storyLabel.setObjectName("storyLabel")
        self.nextButton = QPushButton(self.storyPage)
        self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.nextButton.setText(QApplication.translate("MainWindow", 
                                "Next", None, QApplication.UnicodeUTF8))
        self.nextButton.setObjectName("nextButton")
        self.nextButton.setStyleSheet(self.fgb)
        font.setPointSize(15)
        self.nextButton.setFont(font)
        self.stackedWidget.addWidget(self.storyPage)
        
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #Menu bar
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QMenu(self.menubar)
        self.menuMenu.setTitle(QApplication.translate("MainWindow", 
                               "Menu", None, QApplication.UnicodeUTF8))
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.actionSave_Game = QAction(MainWindow)
        self.actionSave_Game.setText(QApplication.translate("MainWindow", 
                                  "Save Game", None, QApplication.UnicodeUTF8))
        self.actionSave_Game.setObjectName("actionSave_Game")
        self.actionCredits = QAction(MainWindow)
        self.actionCredits.setText(QApplication.translate("MainWindow", 
                                   "Credits", None, QApplication.UnicodeUTF8))
        self.actionCredits.setObjectName("actionCredits")
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setText(QApplication.translate("MainWindow", 
                                "Quit", None, QApplication.UnicodeUTF8))
        self.actionQuit.setObjectName("actionQuit")
        self.actionSettings = QAction(MainWindow)
        self.actionSettings.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setObjectName("actionSettings")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setText(QApplication.translate("MainWindow", 
                                "Help", None, QApplication.UnicodeUTF8))
        self.actionHelp.setObjectName("actionHelp")
        self.actionMain_Menu = QAction(MainWindow)
        self.actionMain_Menu.setText(QApplication.translate("MainWindow", 
                                "Main Menu", None, QApplication.UnicodeUTF8))
        self.actionMain_Menu.setObjectName("actionMain_Menu")
        self.menuMenu.addAction(self.actionSettings)
        self.menuMenu.addAction(self.actionHelp)
        self.menuMenu.addAction(self.actionSave_Game)
        self.menuMenu.addAction(self.actionCredits)
        self.menuMenu.addAction(self.actionMain_Menu)
        self.menuMenu.addAction(self.actionQuit)
        self.menubar.addAction(self.menuMenu.menuAction())
        

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)

        self.stackIndex = 0

    def retranslateUi(self, MainWindow):
        pass
コード例 #11
0
class LunchMenuWidget(QWidget):
    textViewIndex = 0
    textViewAdditivesMap = {}
    
    def __init__(self, parent):
        super(LunchMenuWidget, self).__init__(parent)
        
        box = QVBoxLayout(self)
        box.addWidget(QLabel(u"Initializing...", self))
    
    def initializeLayout(self):
        layout = self.layout()
        
        child = layout.takeAt(0)
        while child != None:
            child.widget().deleteLater()
            child = layout.takeAt(0)
        
        self.messages = LunchMenu.messages()
        self.toggleMessages = LunchMenu.toggleMessages()
        
        self.additives = LunchMenu.additives()
        self.toggleAdditives = LunchMenu.toggleAdditives()
        
        buttonBar = self.createButtonBar(self)
        
        layout.addLayout(buttonBar)
        
        self.menuNotebook = QStackedWidget(self)
        self.createNotebook()
        layout.addWidget(self.menuNotebook)
        
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
    
    def create_arrow_button(self, parent, arrow_type):
        button = QToolButton(parent)
        button.setArrowType(arrow_type)
        return button
    
    def goLeft(self):
        curIndex = self.combobox.currentIndex()
        if curIndex > 0:
            self.combobox.setCurrentIndex(curIndex - 1)
    
    def goRight(self):
        curIndex = self.combobox.currentIndex()
        if curIndex < 4:
            self.combobox.setCurrentIndex(curIndex + 1)
    
    def goToday(self):
        now = LunchMenu.today()
        
        minDelta = sys.maxint
        minDeltaI = 0
        i = 0
        for aLunchMenu in LunchMenu.allLunchMenus():
            if aLunchMenu == None or isinstance(aLunchMenu, Exception):
                # parse error, use current day of week
                if now.weekday() < 5:
                    minDeltaI = now.weekday()
                else:
                    minDeltaI = 4
                break
            td = now - aLunchMenu.lunchDate
            delta = abs((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)
            if delta < minDelta:
                minDelta = delta
                minDeltaI = i
            i = i + 1
                
        self.combobox.setCurrentIndex(minDeltaI)
            
    def goTodayClicked(self):
        self.goToday()
        
    def isToggled(self):
        index = self.menuNotebook.currentIndex()
        return (index >= 5)
        
    def changed_combo(self,index):
        if self.isToggled():
            self.menuNotebook.setCurrentIndex(index + 5)
        else:
            self.menuNotebook.setCurrentIndex(index)
        self.leftButton.setEnabled(index != 0)
        self.rightButton.setEnabled(index != 4)
   
    def toggleLanguage(self):
        index = self.menuNotebook.currentIndex()
        isToggle = (index >= 5)
        if isToggle:
            self.switchLanguageButton.setText(self.messages["toggleLanguage"])
            index = index - 5
        else:
            self.switchLanguageButton.setText(self.messages["toggleLanguage2"])
            index = index + 5
        self.menuNotebook.setCurrentIndex(index)
   
    def createButtonBar(self, parent):
        self.combobox = QComboBox(parent)
        self.combobox.addItem(self.messages['monday'])
        self.combobox.addItem(self.messages['tuesday'])
        self.combobox.addItem(self.messages['wednesday'])
        self.combobox.addItem(self.messages['thursday'])
        self.combobox.addItem(self.messages['friday'])
        self.combobox.currentIndexChanged.connect(self.changed_combo)
        comboBoxHeight = self.combobox.sizeHint().height()
        
        self.leftButton = self.create_arrow_button(parent, Qt.LeftArrow)
        self.leftButton.clicked.connect(self.goLeft)
        self.leftButton.setMinimumSize(comboBoxHeight, comboBoxHeight)
        
        self.rightButton = self.create_arrow_button(parent, Qt.RightArrow)
        self.rightButton.clicked.connect(self.goRight)
        self.rightButton.setMinimumSize(comboBoxHeight, comboBoxHeight)
        
        
        navButtons = QHBoxLayout()
        navButtons.addWidget(self.leftButton, 0, Qt.AlignRight)
        navButtons.addWidget(self.combobox, 0, Qt.AlignCenter)
        navButtons.addWidget(self.rightButton, 0, Qt.AlignLeft)
        
        buttonBar = QHBoxLayout()
        todayButton = QPushButton(self.messages['today'], parent)
        todayButton.clicked.connect(self.goTodayClicked)
        todayButton.setMinimumHeight(comboBoxHeight)
        buttonBar.addWidget(todayButton)
        
        buttonBar.addWidget(QWidget(parent), 1)
        buttonBar.addLayout(navButtons, 1)
        buttonBar.addWidget(QWidget(parent), 1)
        
        self.switchLanguageButton = QPushButton(self.messages["toggleLanguage"], parent)
        self.switchLanguageButton.clicked.connect(self.toggleLanguage)
        self.switchLanguageButton.setMinimumHeight(comboBoxHeight)
        buttonBar.addWidget(self.switchLanguageButton, 0, Qt.AlignRight)
                
        return buttonBar
    
    def addMenuLine(self, parent, text, box, header = False):
        aLabel = QLabel(text, parent)
        if header:
            aLabel.setAlignment(Qt.AlignCenter)
            oldFont = aLabel.font()
            aLabel.setFont(QFont(oldFont.family(), 13, QFont.Bold))
        box.addWidget(aLabel, 0, Qt.AlignBottom)
        
    def addLocaleErrorPage(self, parent, box, toggle):
        aLabel = QLabel(self.messages['parseLocaleError'], parent)
        aLabel.setWordWrap(True)
        box.addWidget(aLabel)
        
        aButton = QPushButton(self.messages['installLocaleButton'], parent)
        if toggle:
            aButton.clicked.connect(self.installLanguageSupportToggle)
        else:
            aButton.clicked.connect(self.installLanguageSupport)
        box.addWidget(aButton)
        
    def addExceptionPage(self, parent, box, error, _toggle):
        aLabel = QLabel(self.messages['otherException'] + u" " + unicode(error), parent)
        aLabel.setWordWrap(True)
        box.addWidget(aLabel)
        
    def installLanguageSupportForLocale(self, locale):
        locale = locale.partition("_")[0]
        if subprocess.call(['gksu', "apt-get -q -y install language-pack-%s" % locale])!=0:
            QMessageBox().critical(self.menuNotebook, "Installation Error", self.messages['installLocaleError'], buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok)
        else:
            QMessageBox().information(self.menuNotebook, "Success", self.messages['installLocaleSuccess'], buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok)
    
    def installLanguageSupport(self):
        self.installLanguageSupportForLocale(self.defaultLocaleString)
    def installLanguageSupportToggle(self):
        self.installLanguageSupportForLocale(self.messages['toggleLocale'])

    def formatTitleAndDescription(self, title, description, keyInfo):
        if title and description:
            result = "%s, %s" % (title, description)
        elif title:
            result = title
        else:
            result = description
        
        if keyInfo:
            return "%s: %s" % (keyInfo.title(), result)
        return result

    def addMenuContent(self, parent, desc, menuContents, box, messages, additivesDict):
        self.addMenuLine(parent, desc, box)
        if desc in menuContents:
            contentList = menuContents[desc]
        else:
            contentList = [(messages[u'noContents'], None, [], None)]
            log_debug("lunch menu does not contain key '%s'" % desc)
        
        textview = GrowingTextEdit(parent, messages, additivesDict)
        textview.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        textview.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        textview.setLineWrapMode(QTextEdit.WidgetWidth)
        textview.setReadOnly(True)
        textview.document().setIndentWidth(10)
        
        if len(contentList) == 1:
            title, description, additives, keyInfo = contentList[0]
            textview.append(self.formatTitleAndDescription(title, description, keyInfo), additives)
        elif len(contentList) > 1:
            cursor = textview.textCursor()
            listFormat = QTextListFormat()
            listFormat.setStyle(QTextListFormat.ListDisc)
            listFormat.setIndent(1)
            cursor.createList(listFormat)
            for title, description, additives, keyInfo in contentList:
                textview.append(self.formatTitleAndDescription(title, description, keyInfo), additives)
        
        box.addWidget(textview, 0)
    
    def createNotebook(self):
        self.combobox.setCurrentIndex(0)
        for _ in range(self.menuNotebook.count()):
            self.menuNotebook.removeWidget(self.menuNotebook.widget(0))
        curMessages = self.messages
        curAdditives = self.additives
        for index in range(10):
            if index == 5:
                try:
                    if getPlatform() != PLATFORM_WINDOWS:
                        locale.setlocale(locale.LC_TIME, (self.messages["toggleLocale"],"UTF-8"))
                except:
                    log_exception("error setting locale")
                curMessages = self.toggleMessages
                curAdditives = self.toggleAdditives
            pageWidget = QWidget(self.menuNotebook)
            page = QVBoxLayout(pageWidget)
            thisLunchMenu = LunchMenu.allLunchMenus()[index]
            if thisLunchMenu != None and type(thisLunchMenu) == LunchMenu:
                title = curMessages['lunchMenuFor'] + u" " + thisLunchMenu.lunchDate.strftime(curMessages['dateFormatDisplayed']).decode("utf-8")
                self.addMenuLine(pageWidget, title, page, True)
                if thisLunchMenu.isValid():
                    self.addMenuContent(pageWidget, curMessages['soupDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives)
                    self.addMenuContent(pageWidget, curMessages['mainDishesDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives)
                    self.addMenuContent(pageWidget, curMessages['supplementsDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives)
                    self.addMenuContent(pageWidget, curMessages['dessertsDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives)
                else:
                    self.addMenuLine(pageWidget, curMessages['noLunchToday'], page)
            elif type(thisLunchMenu) == locale.Error:
                self.addLocaleErrorPage(pageWidget, page, index >= 5)
                pass
            elif isinstance(thisLunchMenu, Exception):
                self.addExceptionPage(pageWidget, page, thisLunchMenu, index >= 5)
            
            self.menuNotebook.addWidget(pageWidget)
        try:
            if getPlatform() != PLATFORM_WINDOWS:
                locale.setlocale(locale.LC_TIME, (LunchMenu.defaultLocaleString,"UTF-8"))
        except:
            log_exception("error setting locale")
        
        self.goToday()
コード例 #12
0
class LeapFlow (QMainWindow):

	def __init__ (self):
		QMainWindow.__init__ (self)

		self.controller = Controller ()
		self.listener = LeapListener (self)
		self.controller.add_listener (self.listener)

		self.mode = "gallery"
		self.scroll = False
		self.direction = ""
		self.direction_x = 0
		self.scroll_velocity = 0
		self.current_index = 0

		# List containing images for the gallery
		self.list_view = QListWidget ()
		self.list_view.setFlow (0)
		self.list_view.setHorizontalScrollMode (1)
		self.list_view.setMouseTracking (True)
		self.list_view.itemClicked.connect (self.show_image)

		# Setting the style of the ListView, background, item selected, etc
		self.list_view.setStyleSheet ("""
				QListWidget::item:hover {background: transparent;}
				QListWidget::item:disabled:hover {background: transparent;}
				QListWidget::item:hover:!active {background: transparent;}
				QListWidget::item:selected:active {background: transparent;}
	            QListWidget::item:selected:!active {background: transparent;}
	            QListWidget::item:selected:disabled {background: transparent;}
	            QListWidget::item:selected:!disabled {background: transparent;}
	            QListWidget {background: #2C3539}
			""")

		# Image viewer
		self.scene = QGraphicsScene ()
		self.viewer = QGraphicsView (self.scene)

		self.stackedWidget = QStackedWidget ()
		self.stackedWidget.addWidget (self.list_view)
		self.stackedWidget.addWidget (self.viewer)

		self.setCentralWidget (self.stackedWidget)
		self.resize (500, 400)
		self.showMaximized ()

		scan = ScanLibrary ("/home/chris/Example")
		threads.append (scan)
		self.connect (scan, SIGNAL (scan.signal), self.add_images_to_list)
		scan.start ()

		self.connect (self, SIGNAL ("scrollChanged(bool)"), self.scroll_view)

	def setScroll (self, scroll):
		"""Emit signal to scroll the view"""
		if (self.scroll != scroll):
			self.scroll = scroll
			self.emit (SIGNAL("scrollChanged(bool)"), scroll)

	def scroll_view (self):
		"""Scroll the view based on scroll velocity and direction"""

		x = self.direction_x * self.scroll_velocity / 100
		bar_x = self.list_view.horizontalScrollBar ().value ()
		self.list_view.horizontalScrollBar ().setValue (bar_x + x)

	def add_images_to_list (self):
		"""To add a widget to the listview you must add a QListWidgetItem
		and replace with your widget"""

		for image in library:
			item = QListWidgetItem ()
			pixmap = QPixmap.fromImage (QImage (library[image]))
			label = QLabel ()
			label.setPixmap (pixmap.scaled (600, 400))
			item.setSizeHint (label.sizeHint ())
			item.setData (0, library[image])
			self.list_view.addItem (item)
			self.list_view.setItemWidget (item, label)

	def show_image (self, item):
		""""Display the selected image"""

		self.current_index = self.list_view.indexFromItem (item).row ()
		self.scene.addPixmap ((QPixmap.fromImage (QImage (item.text()))).scaled (self.viewer.size()))

		self.stackedWidget.setCurrentIndex (1)
		self.mode = "viewer"

	def previous_image (self):
		"""Load previous image"""

		if self.current_index - 1 >= 0:
			self.current_index -= 1
			self.load_image ()

	def next_image (self):
		"""Load next image"""

		if self.current_index + 1 <= len(library.keys ()) - 1:
			self.current_index += 1
			self.load_image ()

	def load_image (self):
		"""Load the image in self.current_index"""

		self.scene.addPixmap (QPixmap.fromImage (QImage (library[library.keys()[self.current_index]])))
コード例 #13
0
class SideBar(QWidget):
    """ Sidebar with a widget area which is hidden or shown.
        On by clicking any tab, off by clicking the current tab.
    """

    North = 0
    East = 1
    South = 2
    West = 3

    def __init__(self, orientation=2, parent=None):
        QWidget.__init__(self, parent)

        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase(True)
        self.__tabBar.setShape(QTabBar.RoundedNorth)
        self.__tabBar.setFocusPolicy(Qt.NoFocus)
        self.__tabBar.setUsesScrollButtons(True)
        self.__tabBar.setElideMode(1)
        self.__stackedWidget = QStackedWidget(self)
        self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setMargin(0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setMargin(0)
        self.layout.setSpacing(0)
        self.barLayout.addWidget(self.__tabBar)
        self.layout.addLayout(self.barLayout)
        self.layout.addWidget(self.__stackedWidget)
        self.setLayout(self.layout)

        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()

        self.splitter = None

        self.__tabBar.installEventFilter(self)

        self.__orientation = orientation
        self.setOrientation(orientation)

        self.__tabBar.currentChanged.connect(
            self.__stackedWidget.setCurrentIndex)
        return

    def setSplitter(self, splitter):
        """ Set the splitter managing the sidebar """
        self.splitter = splitter
        return

    def __getIndex(self):
        " Provides the widget index in splitters "
        if self.__orientation == SideBar.West:
            return 0
        if self.__orientation == SideBar.East:
            return 2
        if self.__orientation == SideBar.South:
            return 1
        return 0

    def __getWidget(self):
        " Provides a reference to the widget "
        return self.splitter.widget(self.__getIndex())

    def shrink(self):
        """ Shrink the sidebar """
        if self.__minimized:
            return

        self.__minimized = True
        self.__bigSize = self.size()
        if self.__orientation in [SideBar.North, SideBar.South]:
            self.__minSize = self.minimumHeight()
            self.__maxSize = self.maximumHeight()
        else:
            self.__minSize = self.minimumWidth()
            self.__maxSize = self.maximumWidth()

        self.__stackedWidget.hide()

        sizes = self.splitter.sizes()
        selfIndex = self.__getIndex()

        if self.__orientation in [SideBar.North, SideBar.South]:
            newHeight = self.__tabBar.minimumSizeHint().height()
            self.setFixedHeight(newHeight)

            diff = sizes[selfIndex] - newHeight
            sizes[selfIndex] = newHeight
        else:
            newWidth = self.__tabBar.minimumSizeHint().width()
            self.setFixedWidth(newWidth)

            diff = sizes[selfIndex] - newWidth
            sizes[selfIndex] = newWidth

        if selfIndex == 0:
            sizes[1] += diff
        else:
            sizes[selfIndex - 1] += diff

        self.splitter.setSizes(sizes)
        return

    def expand(self):
        """ Expand the sidebar """
        if not self.__minimized:
            return

        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)

        sizes = self.splitter.sizes()
        selfIndex = self.__getIndex()

        if self.__orientation in [SideBar.North, SideBar.South]:
            self.setMinimumHeight(self.__minSize)
            self.setMaximumHeight(self.__maxSize)

            diff = self.__bigSize.height() - sizes[selfIndex]
            sizes[selfIndex] = self.__bigSize.height()
        else:
            self.setMinimumWidth(self.__minSize)
            self.setMaximumWidth(self.__maxSize)

            diff = self.__bigSize.width() - sizes[selfIndex]
            sizes[selfIndex] = self.__bigSize.width()

        if selfIndex == 0:
            sizes[1] -= diff
        else:
            sizes[selfIndex - 1] -= diff

        self.splitter.setSizes(sizes)
        return

    def isMinimized(self):
        """ Provides the minimized state """
        return self.__minimized

    def eventFilter(self, obj, evt):
        """ Handle click events for the tabbar """

        if obj == self.__tabBar:
            if evt.type() == QEvent.MouseButtonPress:
                pos = evt.pos()

                index = self.__tabBar.count() - 1
                while index >= 0:
                    if self.__tabBar.tabRect(index).contains(pos):
                        break
                    index -= 1

                if index == self.__tabBar.currentIndex():
                    if self.isMinimized():
                        self.expand()
                    else:
                        self.shrink()
                    return True

                elif self.isMinimized():
                    if self.isTabEnabled(index):
                        self.expand()

        return QWidget.eventFilter(self, obj, evt)

    def addTab(self, widget, iconOrLabel, label=None):
        """ Add a tab to the sidebar """

        if label:
            self.__tabBar.addTab(iconOrLabel, label)
        else:
            self.__tabBar.addTab(iconOrLabel)
        self.__stackedWidget.addWidget(widget)
        return

    def insertTab(self, index, widget, iconOrLabel, label=None):
        """ Insert a tab into the sidebar """

        if label:
            self.__tabBar.insertTab(index, iconOrLabel, label)
        else:
            self.__tabBar.insertTab(index, iconOrLabel)
        self.__stackedWidget.insertWidget(index, widget)
        return

    def removeTab(self, index):
        """ Remove a tab """

        self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index))
        self.__tabBar.removeTab(index)
        return

    def clear(self):
        """ Remove all tabs """

        while self.count() > 0:
            self.removeTab(0)
        return

    def prevTab(self):
        """ Show the previous tab """

        index = self.currentIndex() - 1
        if index < 0:
            index = self.count() - 1

        self.setCurrentIndex(index)
        self.currentWidget().setFocus()
        return

    def nextTab(self):
        """ Show the next tab """

        index = self.currentIndex() + 1
        if index >= self.count():
            index = 0

        self.setCurrentIndex(index)
        self.currentWidget().setFocus()
        return

    def count(self):
        """ Provides the number of tabs """

        return self.__tabBar.count()

    def currentIndex(self):
        """ Provides the index of the current tab """

        return self.__stackedWidget.currentIndex()

    def setCurrentIndex(self, index):
        """ Switch to the certain tab """

        if index >= self.currentIndex():
            return

        self.__tabBar.setCurrentIndex(index)
        self.__stackedWidget.setCurrentIndex(index)
        if self.isMinimized():
            self.expand()
        return

    def currentWidget(self):
        """ Provide a reference to the current widget """

        return self.__stackedWidget.currentWidget()

    def setCurrentWidget(self, widget):
        """ Set the current widget """

        self.__stackedWidget.setCurrentWidget(widget)
        self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex())
        if self.isMinimized():
            self.expand()
        return

    def indexOf(self, widget):
        """ Provides the index of the given widget """

        return self.__stackedWidget.indexOf(widget)

    def isTabEnabled(self, index):
        """ Check if the tab is enabled """

        return self.__tabBar.isTabEnabled(index)

    def setTabEnabled(self, index, enabled):
        """ Set the enabled state of the tab """

        self.__tabBar.setTabEnabled(index, enabled)
        return

    def orientation(self):
        """ Provides the orientation of the sidebar """

        return self.__orientation

    def setOrientation(self, orient):
        """ Set the orientation of the sidebar """

        if orient == SideBar.North:
            self.__tabBar.setShape(QTabBar.RoundedNorth)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == SideBar.East:
            self.__tabBar.setShape(QTabBar.RoundedEast)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.RightToLeft)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        elif orient == SideBar.South:
            self.__tabBar.setShape(QTabBar.RoundedSouth)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.BottomToTop)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        else:
            # default
            orient = SideBar.West
            self.__tabBar.setShape(QTabBar.RoundedWest)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        self.__orientation = orient
        return

    def tabIcon(self, index):
        """ Provide the icon of the tab """

        return self.__tabBar.tabIcon(index)

    def setTabIcon(self, index, icon):
        """ Set the icon of the tab """

        self.__tabBar.setTabIcon(index, icon)
        return

    def tabText(self, index):
        """ Provide the text of the tab """

        return self.__tabBar.tabText(index)

    def setTabText(self, index, text):
        """ Set the text of the tab """

        self.__tabBar.setTabText(index, text)
        return

    def tabToolTip(self, index):
        """ Provide the tooltip text of the tab """

        return self.__tabBar.tabToolTip(index)

    def setTabToolTip(self, index, tip):
        """ Set the tooltip text of the tab """

        self.__tabBar.setTabToolTip(index, tip)
        return

    def tabWhatsThis(self, index):
        """ Provide the WhatsThis text of the tab """

        return self.__tabBar.tabWhatsThis(index)

    def setTabWhatsThis(self, index, text):
        """ Set the WhatsThis text for the tab """

        self.__tabBar.setTabWhatsThis(index, text)
        return

    def widget(self, index):
        """ Provides the reference to the widget (QWidget) """

        return self.__stackedWidget.widget(index)
コード例 #14
0
class StudentProfile(QDialog):
    def __init__(self, sids, es, parent=None):
        super(StudentProfile, self).__init__(parent)

        red = 50 + es
        reds = 50 + es

        self.setGeometry(red, reds, 700, 700)
        self.textStyle = "background-color: white; color:black; border: 3px ridge #ccc"
        self.minW = 670
        self.maxW = 700

        self.sid = sids
        self.student = sids
        cn = Db()
        self.myterms = cn.getTermClass(self.sid)
        menu = self.menuUi()
        data = self.pullStudents(self.sid)

        fullnamex = data['surname'] + ' ' + data['firstname'] + ' ' + data[
            'othername']
        self.fullname = fullnamex.title()
        self.schno = str(data['schno']).upper()

        if data['gender'] == 0:
            self.gender = 'Male'
        elif data['gender'] == 1:
            self.gender = 'Female'
        else:
            self.gender = 'None Stated'

        now = datetime.datetime.today()

        dob = data['dob']
        dt = datetime.datetime.strptime(dob, '%d/%m/%Y').date()
        dt1 = now.date()
        diff = (dt1 - dt).days
        age1 = int(diff) / 365.25
        agey = round(int(diff) / 365.25, 0)
        agem = age1 - agey
        months = round(agem * 12)
        self.dob = "{:%d, %b %Y}".format(dt)
        self.age = str(math.floor(agey)) + ' yrs ' + str(
            math.floor(months)) + ' months '

        admit = data['admit']
        dt2 = datetime.datetime.strptime(admit, '%d/%m/%Y').date()
        dt3 = now.date()
        diff1 = (dt3 - dt2).days
        admit1 = int(diff1) / 365.25
        admity = round(int(diff1) / 365.25, 0)
        admitm = admit1 - admity
        amonths = round(admitm * 12)
        self.admit = "{:%d, %b %Y}".format(dt2)
        self.admit_dur = str(math.floor(admity)) + ' yrs ' + str(
            math.floor(amonths)) + ' months '

        self.data = data

        self.h1_box = QVBoxLayout()
        self.h2_box = QVBoxLayout()
        self.h3_box = QVBoxLayout()
        self.h4_box = QVBoxLayout()
        self.h5_box = QVBoxLayout()

        self.profileStack = QStackedWidget()

        bioText = QTextEdit(self)
        bioText.setMinimumWidth(self.minW)
        bioText.setMinimumHeight(self.maxW)
        bioText.setMaximumHeight(self.maxW)
        btext = self.buildBio()
        bioText.insertHtml(btext)
        bioText.setStyleSheet(self.textStyle)
        self.profileStack.setCurrentIndex(0)
        self.h1_box.addWidget(bioText)
        self.h1_box.setSizeConstraint(QLayout.SetFixedSize)
        self.doc1 = bioText

        self.academicText = QTextEdit()
        self.academicText.setMinimumWidth(self.minW)
        self.academicText.setMinimumHeight(self.maxW)
        self.academicText.setMaximumHeight(self.maxW)
        actext = self.buildBio()
        self.academicText.insertHtml(actext)
        self.academicText.setStyleSheet(self.textStyle)
        self.h2_box.addWidget(self.academicText)
        self.h2_box.setSizeConstraint(QLayout.SetFixedSize)
        self.doc2 = self.academicText

        self.affectiveText = QTextEdit()
        self.affectiveText.setMinimumWidth(self.minW)
        self.affectiveText.setMinimumHeight(self.maxW)
        self.affectiveText.setMaximumHeight(self.maxW)
        aftext = self.buildBio()
        self.affectiveText.insertHtml(aftext)
        self.affectiveText.setStyleSheet(self.textStyle)
        self.h3_box.addWidget(self.affectiveText)
        self.h3_box.setSizeConstraint(QLayout.SetFixedSize)
        self.doc3 = self.affectiveText

        self.psychomotorText = QTextEdit()
        self.psychomotorText.setMinimumWidth(self.minW)
        self.psychomotorText.setMinimumHeight(self.maxW)
        self.psychomotorText.setMaximumHeight(self.maxW)
        pstext = self.buildBio()
        self.psychomotorText.insertHtml(pstext)
        self.psychomotorText.setStyleSheet(self.textStyle)
        self.h4_box.addWidget(self.psychomotorText)
        self.h4_box.setSizeConstraint(QLayout.SetFixedSize)
        self.doc4 = self.psychomotorText

        self.feeText = QTextEdit()
        self.feeText.setMinimumWidth(self.minW)
        self.feeText.setMinimumHeight(self.maxW)
        self.feeText.setMaximumHeight(self.maxW)
        fetext = self.buildBio()
        self.feeText.insertHtml(fetext)
        self.feeText.setStyleSheet(self.textStyle)
        self.h5_box.addWidget(self.feeText)
        self.h5_box.setSizeConstraint(QLayout.SetFixedSize)
        self.doc5 = self.feeText

        scrollArea = QScrollArea(self)
        scrollArea.setWidgetResizable(True)
        scrollArea.setFixedHeight(700)
        scrollArea.setFixedWidth(700)

        bioProfileWidget = QWidget()
        academicProfileWidget = QWidget()
        affectiveProfileWidget = QWidget()
        psychomotorProfileWidget = QWidget()
        feeProfileWidget = QWidget()

        self.profileStack.addWidget(bioProfileWidget)
        self.profileStack.addWidget(academicProfileWidget)
        self.profileStack.addWidget(affectiveProfileWidget)
        self.profileStack.addWidget(psychomotorProfileWidget)
        self.profileStack.addWidget(feeProfileWidget)

        bioProfileWidget.setLayout(self.h1_box)
        academicProfileWidget.setLayout(self.h2_box)
        affectiveProfileWidget.setLayout(self.h3_box)
        psychomotorProfileWidget.setLayout(self.h4_box)
        feeProfileWidget.setLayout(self.h5_box)
        #Main layout
        Hbox = QVBoxLayout()
        Hbox.addWidget(menu)
        Hbox.addStretch()
        Hbox.addWidget(self.profileStack)
        Hbox.setContentsMargins(0, 0, 0, 0)

        #Create central widget, add layout and set
        central_widget = QWidget(scrollArea)
        scrollArea.setWidget(central_widget)
        central_widget.setContentsMargins(0, 0, 0, 0)
        central_widget.setGeometry(0, 0, 650, 700)
        central_widget.setStyleSheet("background-color: #ccc; color:#000")
        central_widget.setLayout(Hbox)

        self.setWindowTitle(fullnamex.title())
        self.show()

    def getFile(self, a):
        fname = QFileDialog.getOpenFileName(self, 'Open', 'c:\\',
                                            "Image File (*.jpg *.png)")
        if a == 1:
            self.pic1.setPixmap(QPixmap(fname))
        elif a == 2:
            self.pic2.setPixmap(QPixmap(fname))
        elif a == 2:
            self.pic3.setPixmap(QPixmap(fname))

    def getFilez(self):
        fname = QFileDialog.getOpenFileName(self, 'Open', 'c:\\',
                                            "Image File (*.jpg *.png)")
        self.pic1.setPixmap(QPixmap(fname))

    def button_click1(self, a):
        # shost is a QString object
        s1 = self.le.text()
        s2 = self.le2.text()
        self.a = a
        g = Db()
        if (len(s1) > 0):
            y = {'name': s1, 'subID': self.a, 'abbrv': s2}
            j = g.insert('datas', y)
            return j

    def pullClass(self, a):
        self.a = a
        cn = Db()
        students = cn.select('datas', '', '', {'subID': self.a})
        arr = {}

        for j in students:
            arr[j[0]] = j[2]
        return arr

    def pullResults(self, term):
        cn = Db()
        students = cn.selectn('datas', '', '', {'subID': term, 'pubID': 'rep'})
        return students

    def pullResult(self, row):
        cn = Db()
        students = cn.selectn('datas', '', 1, {'id': row})
        return students

    def pullStudents(self, a):
        self.a = a
        cn = Db()
        students = cn.selectn('students', '', 1, {'id': self.a})
        return students

    def lunchUnitForm(self, a):
        self.a = a

    def lunchPrintForm(self, a):
        self.item = a
        self.lunchPrintPreview()
        #form.exec_()

    def handlePaintRequest(self, printer):
        _item = self.item
        if _item == 1:
            document = self.doc1
        elif _item == 2:
            document = self.doc1
        elif _item == 3:
            document = self.doc1
        elif _item == 4:
            document = self.doc1
        else:
            document = None

        if document != None:
            document.print_(printer)

    def lunchReport(self, a, b, c=None):
        _item = a
        if _item == 1:
            self.profileStack.setCurrentIndex(0)
            self.bioText = QTextEdit()
            self.bioText.setMinimumWidth(self.minW)
            self.bioText.setMinimumHeight(self.maxW)
            self.bioText.setMaximumHeight(self.maxW)
            btext = self.buildBio()
            self.bioText.insertHtml(btext)
            self.bioText.setStyleSheet(self.textStyle)
        elif _item == 2:
            self.profileStack.setCurrentIndex(1)
            self.academicText.close()
            self.academicText = QTextEdit()
            self.academicText.setMinimumWidth(self.minW)
            self.academicText.setMinimumHeight(self.maxW)
            self.academicText.setMaximumHeight(self.maxW)
            actext = self.buildAca(b, c)
            self.academicText.insertHtml(actext)
            self.academicText.setStyleSheet(self.textStyle)
            self.h2_box.addWidget(self.academicText)
            self.academicText.show()
        elif _item == 3:
            self.profileStack.setCurrentIndex(2)
            self.affectiveText.close()
            self.affectiveText = QTextEdit()
            self.affectiveText.setMinimumWidth(self.minW)
            self.affectiveText.setMinimumHeight(self.maxW)
            self.affectiveText.setMaximumHeight(self.maxW)
            aftext = self.buildAff(b)
            self.affectiveText.insertHtml(aftext)
            self.affectiveText.setStyleSheet(self.textStyle)
        elif _item == 4:
            self.profileStack.setCurrentIndex(3)
            self.psychomotorText.close()
            self.psychomotorText = QTextEdit()
            self.psychomotorText.setMinimumWidth(self.minW)
            self.psychomotorText.setMinimumHeight(self.maxW)
            self.psychomotorText.setMaximumHeight(self.maxW)
            pstext = self.buildPsy(b)
            self.psychomotorText.insertHtml(pstext)
            self.psychomotorText.setStyleSheet(self.textStyle)
        elif _item == 5:
            self.profileStack.setCurrentIndex(4)
            self.feeText.close()
            self.feeText = QTextEdit()
            self.feeText.setMinimumWidth(self.minW)
            self.feeText.setMinimumHeight(self.maxW)
            self.feeText.setMaximumHeight(self.maxW)
            fetext = self.buildFee(b)
            self.feeText.insertHtml(fetext)
            self.feeText.setStyleSheet(self.textStyle)
        else:
            self.profileStack.setCurrentIndex(0)

    def lunchPrintPreview(self):
        dialog = QPrintPreviewDialog()
        dialog.paintRequested.connect(self.handlePaintRequest)
        dialog.exec_()

    def menuUi(self):
        extractQuit = QAction(self)
        extractQuit.setStatusTip('File')

        mainMenu = QMenuBar()

        fileMenu = mainMenu.addMenu('&File')
        exitMenu = QAction('&Exit', self)
        exitMenu.setShortcut('CTRL+Q')
        exitMenu.setStatusTip('Close Dialog')
        exitMenu.triggered.connect(self.lunchUnitForm)
        fileMenu.addAction(exitMenu)

        #settings menu
        ViewMenu = mainMenu.addMenu('&Veiws')
        ## student menu static items
        bioMenu = QAction('Biodata', self)
        bioMenu.setStatusTip('Bio and Contact data')
        bioMenu.triggered.connect(
            lambda state, x=1, y='k': self.lunchReport(x, y))
        ViewMenu.addAction(bioMenu)

        academicMenu = ViewMenu.addMenu('Academic')
        dumpClass1 = {}
        for k in self.myterms:
            act = str(list(self.myterms[k])[0])
            getResult = self.pullResults(k)
            studs = academicMenu.addMenu(act)
            for w in getResult:
                getRes = w['name'].split(',')
                getDat = w['description'].split(':::')
                if list(self.myterms[k])[1] in getRes:
                    stud = QAction(getDat[0], studs)
                    dumpClass1[k] = stud
                    stud.triggered.connect(lambda state, x=2, term=k, rep=w[
                        'id']: self.lunchReport(x, term, rep))
                    studs.addAction(stud)

        affectiveMenu = ViewMenu.addMenu('Affective')
        dumpClass2 = {}
        for k in self.myterms:
            act = str(self.myterms[k])
            stud = QAction(act, self)
            dumpClass2[k] = stud
            stud.triggered.connect(
                lambda state, x=3, y=k: self.lunchReport(x, y))
            affectiveMenu.addAction(stud)

        psychomotorMenu = ViewMenu.addMenu('Psychomotor')
        dumpClass3 = {}
        for k in self.myterms:
            act = str(self.myterms[k])
            stud = QAction(act, self)
            dumpClass3[k] = stud
            stud.triggered.connect(
                lambda state, x=4, y=k: self.lunchReport(x, y))
            psychomotorMenu.addAction(stud)

        feeMenu = ViewMenu.addMenu('Fees')
        dumpClass4 = {}
        for k in self.myterms:
            act = str(self.myterms[k])
            stud = QAction(act, self)
            dumpClass4[k] = stud
            stud.triggered.connect(
                lambda state, x=5, y=k: self.lunchReport(x, y))
            feeMenu.addAction(stud)

        printMenu = mainMenu.addMenu('&Print')
        exitMenu1 = QAction('&Exit', self)
        exitMenu1.setShortcut('CTRL+Q')
        exitMenu1.setStatusTip('Close Dialog')
        exitMenu1.triggered.connect(lambda state, x=1: self.lunchPrintForm(x))
        printMenu.addAction(exitMenu1)
        #printMenu.triggered.connect(lambda state, x = 1:self.lunchPrintForm(x))

        return mainMenu

    def buildBio(self):
        table = '''<html><head>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/invoice-print.css'/>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/theme.css'/>
        </head>
        <style>
        body{
            font: "Century Gothic";
        }
        table
        {
        
        }
        tbody, th, td{
        padding:2px;
         
        }
        td{ align:left}
        .tch{
                align: left !important;
                background-color:teal; 
                color:white;
                text-transform: uppercase;
                font-family: "Century Gothic";
        }
        .tch1{
                color:black;
                text-transform: uppercase;
                font-family: "Century Gothic";
                font-weight:bold;
                width: 300px;
        }
        .item-tab{
                display:inline-block;
        }
        td img{
        max-width: 100px;
        height:150px;
        }
        </style>
        <body>
            <div width='100%'>
                <div width="100%" style="background-color:teal; color:white; text-transform:uppercase; text-align:center">
                    <h3>Bio-Data and Contact Information</h3>
                </div>
                <div style='display:flex'>
                    <div class="item-tab" width='600px' >
                    <table width="500px " cellspacing="0" cellpadding="2px"  style="border-width:1px; border-color: teal; padding:2px" >
                        <tbody>
                            <tr><th class="tch" style="align:right">SCHOOL NUMBER</th><td class="tch1" width="40%">{{dat.schno}}</td>
                            <td rowspan="13" width="40%" style="background-color:green"><img src="img/studentz.png" width="250" height="340" /></td></tr>
                            <tr><th class="tch" style="align:right">SURNAME</th><td class="tch1" width="40%">{{dat.surname | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">FIRSTNAME</th><td class="tch1" width="40%">{{dat.firstname | upper}}</td></tr>
                            <tr><th class="tch" style="align:right" >MIDDLENAME</th><td class="tch1" width="40%">{{dat.othername | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">SEX</th><td class="tch1" width="40%">{{gender}}</td></tr>
                            <tr><th class="tch" style="align:right">DATE OF BIRTH</th><td class="tch1" width="40%">{{dob }}</td></tr>
                            <tr><th class="tch" style="align:right">AGE</th><td class="tch1" width="40%">{{age}}</td></tr>
                            <tr><th class="tch" style="align:right">LGA/District</th><td class="tch1" width="40%">{{dat.lga | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">State/Region</th><td class="tch1" width="40%">{{dat.soo | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">Nationality</th><td class="tch1" width="40%">{{dat.nation | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">Date Started</th><td class="tch1" width="40%">{{admit}}  ( {{admit_dur}})</td></tr>
                            <tr><th class="tch" style="align:right">Status</th><td class="tch1" width="40%">{{dat.schno}}<.td></tr>
                            <tr><th class="tch" style="align:right">Address</th><td class="tch1" width="40%" style="word-wrap:break-word;overflow:none">{{dat.addr}}</td></tr>
                        </tbody>
                    </table>
                </div>
                </div>
                <div width="100%" style="background-color:teal; color:white; text-transform:uppercase; align:center">
                    <h3>Guradians/Primary Care Giver</h3>
                </div>
                <div>
                <table width="100% " cellspacing="0" cellpadding="2px"  style="border-width:1px; border-color: teal; padding:2px" >
                <tbody style='align:left'>
                    <tr><td class="tch1" width="100%"><ul><li>{{dat.g1 | upper}}({{dat.g1rel | upper}}) </li><li> {{dat.g1p1}} | {{dat.g1p2}} </li><li> {{dat.g1addr | upper}} </li> <li>{{dat.g1email}}</li></ul></td></tr>
                    <tr><td class="tch1" width="100%"><ul><li>{{dat.g2 | upper}}({{dat.g2rel | upper}}) </li><li> {{dat.g2p1}} | {{dat.g2p2}} </li><li> {{dat.g2addr | upper}} </li> <li>{{dat.g2email}}</li></ul></td></tr>
                </tbody>
                </table>
                
                </div></body></html>'''

        h = Template(table).render(gender=self.gender,
                                   dob=self.dob,
                                   age=self.age,
                                   admit=self.admit,
                                   admit_dur=self.admit_dur,
                                   dat=self.data)
        return h

    def buildAff(self, a):
        table = '''<html><head>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/invoice-print.css'/>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/theme.css'/>
        </head>
        <style>
        body{
            font: "Century Gothic";
        }
        table
        {
        
        }
        tbody, th, td{
        padding:2px;
         
        }
        td{ align:left}
        .tch{
                align: left !important;
                background-color:teal; 
                color:white;
                text-transform: uppercase;
                font-family: "Century Gothic";
        }
        .tch1{
                color:black;
                text-transform: uppercase;
                font-family: "Century Gothic";
                font-weight:bold;
                width: 300px;
        }
        .item-tab{
                display:inline-block;
        }
        td img{
        max-width: 100px;
        height:150px;
        }
        </style>
        <body>
            <div width='100%'>
                <div width="100%" style="background-color:teal; color:white; text-transform:uppercase; text-align:center">
                    <h3>Bio-Data and Contact Information</h3>
                </div>
                <div style='display:flex'>
                    <div class="item-tab" width='600px' >
                    <table width="100% " cellspacing="0" cellpadding="2px"  style="border-width:1px; border-color: teal; padding:2px" >
                        <tbody>
                        '''

        table = ''' </tbody>
                    </table>
                </div>
                </div>
               </body></html>'''

        h = Template(table).render(gender=self.gender,
                                   dob=self.dob,
                                   age=self.age,
                                   admit=self.admit,
                                   admit_dur=self.admit_dur,
                                   dat=self.data)
        return h

    def buildAca(self, term, report):
        con = Con()
        result = self.pullResult(report)
        f_all = result['description']
        d = f_all.split(':::')
        _title = d[0]
        _theme = d[1]
        _font = d[2]
        _ass = d[3]
        _gra = d[4]
        _set = d[5]

        _ass_list = _ass.split('::')
        _ass_list = [int(x) for x in _ass_list]
        _gra_list = _gra.split('::')
        grade = con.pullGrade(_gra_list[0])
        _set_list = _set.split('::')

        _data = con.academicReportData(term, self.sid, _ass_list)
        _d = _data[0]
        _c = _data[1]
        _s = _data[2]

        subjects = {}
        for s in _s:
            ss = _s[s][0]
            subjects[s] = ss.upper()

        cas = {}
        for c in _c:
            cc = _c[c][1]
            cas[c] = cc.upper()

        std = Con()
        avgs = std.subjectAverage(term, self.student, cas.keys(),
                                  subjects.keys())
        pos = std.studentAverage(term, self.student, cas.keys(),
                                 subjects.keys())
        posUnit = std.studentAverageUnit(term, self.student, cas.keys(),
                                         subjects.keys())
        t = self.buildWriter(subjects, cas, _d, avgs, _set_list, grade)

        table = '''<html><head>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/invoice-print.css'/>
       
        </head>
        <style>
        body{
            font: "Century Gothic";
        }
        @font-face
        {
               
        }
        h1{
                font-family: "Poiret One";
                font-size:30px;
        }
        h2{
                font-family: "Sarala";
                font-size:20px;
        }
        h3{
                font-family: "Sarala";
                font-size:20px;
               
        }
        tbody, th, td{
        padding:2px;
         
        }
        td{ align:center}
        .tch{
                align: left !important;
                background-color:teal; 
                color:white;
                text-transform: uppercase;
                font-family: "Century Gothic";
        }
        .tch1{
                color:black;
                text-transform: uppercase;
                font-family: "Century Gothic";
                font-weight:bold;
                width: 300px;
        }
        .item-tab{
                display:inline-block;
        }
        td img{
        max-width: 100px;
        height:150px;
        }
        .xtable{ display:block;}
        .xrow{ display:block;}
        .xcell{ display:inline-block;}
        
        .xtable{ display:table;}
        .xrow{ display:table-row;}
        .xcell{ display:table-cell;}
        .xcell-10{ width:100px !important;}
        </style>
        <body>
            <div>
            
            <div width='100%' style="background-color:teal; color:white; padding:4px; display:block">
            <h1>{{name}}</h1>
            </div>
            <tr>
            <td width='20%'>
              <img src="img/studentz.png" width="80" height="80" />  
            </td>
            <td>
            <table class="xtable" width='100%' style="font-weight:bold">
                <tr class="xrow">
                    <td class="xcell xcell-10">SCHOOL NUMBER</td>
                    <td class="xcell">{{schno}}</td>
                    <td class="xcell"></td>
                    <td class="xcell"></td>
                </tr>
                <tr class="xrow">
                    <td class="xcell xcell-10">POSITION IN CLASS</td>
                    <td class="xcell">{{pos[2]}} of {{pos[1]}}</td>
                    <td class="xcell">CLASS AVERAGE</td>
                    <td class="xcell">{{pos[0]}}</td>
                </tr>
                 <tr class="xrow">
                    <td class="xcell xcell-10">POSITION IN CLASS UNIT</td>
                    <td class="xcell">{{posUnit[2]}} of {{posUnit[1]}}</td>
                    <td class="xcell">CLASS UNIT AVERAGE</td>
                    <td class="xcell">{{posUnit[0]}}</td>
                </tr>
                <tr class="xrow">
                    <td class="xcell xcell-10">ATTENDANCE</td>
                    <td class="xcell">234.300</td>
                    <td class="xcell">80%</td>
                    <td class="xcell"></td>
                </tr>
                <tr class="xrow">
                    <td class="xcell xcell-10">FEES</td>
                    <td class="xcell">PREV. DEBT:</td>
                    <td class="xcell">NEXT FEE: </td>
                    <td class="xcell">Total: </td>
                </tr>
            </table>
            </td>
            </tr>
            </table>
            </div>
            <div width='100%'>
                <div width='100%' style="background-color:teal; color:white; padding:4px;display:block">
                    
                        <h1>{{title}}</h1>
                    
                </div>
                <div style='display:flex'>
                    <div class="item-tab" width='600px' >
                    
                        {{text}}
                    
                </div>
                </div>
        </body>
        </html>'''

        h = Template(table).render(text=t,
                                   title=_title,
                                   name=self.fullname,
                                   schno=self.schno,
                                   pos=pos,
                                   posUnit=posUnit)
        return h

    def buildWriter(self, subjects, cas, data, avgs, sets, grade):
        subject = subjects.keys()
        cal = cas.keys()
        cal.sort()
        table = '<table  width="100%" cellspacing="0" cellpadding="2px"  style="border-width:1px; border-color: teal; padding:2px; color:black; font-family: Century Gothic">'
        table += "<thead>"
        table += "<tr style='background-color:teal; color:white'>"
        table += "<th>"
        table += "SUBJECTS"
        table += "</th>"
        arr = {}
        arrca = {}
        summed_arr = []
        aummed_arr = []

        for ca in cal:
            arrca[ca] = []
            if str(16) in sets:
                table += "<th>"
                table += str(cas[ca])
                table += "</th>"
        if str(5) in sets:
            #total
            table += "<th>"
            table += "TOTAL<BR>"
            table += "</th>"
        if str(4) in sets:
            #total 100%
            table += "<th>"
            table += "TOTAL<BR>100%"
            table += "</th>"
        if str(6) in sets:
            #total 100%
            table += "<th>"
            table += "GRADE"
            table += "</th>"
        if str(7) in sets:
            #subject Average
            table += "<th width='80px'>"
            table += "SUBJECT<BR>AVERAGE"
            table += "</th>"
        if str(8) in sets:
            #ranking only
            table += "<th width='80px'>"
            table += "CLASS<BR>RANKING"
            table += "</th>"
        if str(9) in sets:
            #ranking and population
            table += "<th width='80px'>"
            table += "CLASS<BR>RANKING"
            table += "</th>"
        table += "</tr>"
        table += "</thead>"
        table += "<tbody>"
        for sub in subject:
            arr[sub] = []
            table += "<tr>"
            table += "<td >"
            table += str(subjects[sub])
            table += "</td>"
            for ca in cal:
                nm = 'AB' + str(sub) + 'CD' + str(ca)
                if nm in data:
                    arr[sub].append(data[nm])
                    arrca[ca].append(data[nm])
                    tdd = str(data[nm])
                else:
                    tdd = str('-.-')
                if str(16) in sets:
                    table += "<td align='center'>"
                    table += tdd
                    table += "</td>"
            summed = sum(arr[sub])
            summed_arr.append(summed)
            if str(5) in sets:
                table += "<td align='center'>"
                table += str(round(summed, 1))
                table += "</td>"
            if str(4) in sets:
                table += "<td align='center'>"
                table += str(round(summed, 1))
                table += "</td>"

            aummed_arr.append(avgs[sub][0])
            if str(6) in sets:
                table += "<td align='center' style='width:80px'>"
                table += str(avgs[sub][0])
                table += "</td>"
            if str(7) in sets:
                table += "<td align='center' style='width:80px'>"
                table += 'Excellent'
                table += "</td>"
            if str(8) in sets:
                table += "<td align='center'style='width:80px'>"
                table += str(avgs[sub][2])
                table += "</td>"
            if str(9) in sets:
                table += "<td align='center'style='width:80px'>"
                table += str(avgs[sub][2]) + ' of ' + str(avgs[sub][1])
                table += "</td>"
        table += "</tr>"
        table += "</tbody>"
        table += "<tfoot>"
        table += "<tr style='background-color:teal; color:white'>"
        table += "<th>"
        table += "SUBJECTS"
        table += "</th>"
        for ca in cal:
            if len(arrca[ca]) > 0:
                cammed = sum(arrca[ca]) / float(len(arrca[ca]))
                cammed = str(round(cammed, 1))
            else:
                cammed = '-.-'
            if str(16) in sets:
                table += "<th>"
                table += cammed
                table += "</th>"
        if str(5) in sets:
            table += "<th>"
            if len(summed_arr) > 0:
                total = sum(summed_arr) / float(len(summed_arr))
            else:
                total = '-.-'
                table += str(round(total, 1))
            table += "</th>"
        if str(4) in sets:
            table += "<th>"
            if len(summed_arr) > 0:
                total = sum(summed_arr) / float(len(summed_arr))
            else:
                total = '-.-'
                table += str(round(total, 1))
            table += "</th>"
        if str(6) in sets:
            table += "<th>"
            #Grading
            table += "</th>"
        if str(7) in sets:
            table += "<th>"
            if len(aummed_arr) > 0:
                totals = sum(aummed_arr) / float(len(aummed_arr))
            else:
                totals = '-.-'
            table += str(round(totals, 1))
            table += "</th>"
        if str(8) in sets:
            table += "<th>"
            #table += str(subjects[sub])
            table += "</th>"
        if str(9) in sets:
            table += "<th>"
            #table += str(subjects[sub])
            table += "</th>"
        table += "</tr>"
        table += "</tfoot>"
        table += "<table>"
        return table

    def buildFee(self, a):
        table = '''<html><head>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/invoice-print.css'/>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/theme.css'/>
        </head>
        <style>
        body{
            font: "Century Gothic";
        }
        table
        {
        
        }
        tbody, th, td{
        padding:2px;
         
        }
        td{ align:left}
        .tch{
                align: left !important;
                background-color:teal; 
                color:white;
                text-transform: uppercase;
                font-family: "Century Gothic";
        }
        .tch1{
                color:black;
                text-transform: uppercase;
                font-family: "Century Gothic";
                font-weight:bold;
                width: 300px;
        }
        .item-tab{
                display:inline-block;
        }
        td img{
        max-width: 100px;
        height:150px;
        }
        </style>
        <body>
            <div width='100%'>
                <div width="100%" style="background-color:teal; color:white; text-transform:uppercase; text-align:center">
                    <h3>Bio-Data and Contact Information</h3>
                </div>
                <div style='display:flex'>
                    <div class="item-tab" width='600px' >
                    <table width="500px " cellspacing="0" cellpadding="2px"  style="border-width:1px; border-color: teal; padding:2px" >
                        <tbody>
                            <tr><th class="tch" style="align:right">SCHOOL NUMBER</th><td class="tch1" width="40%">{{dat.schno}}</td>
                            <td rowspan="13" width="40%" style="background-color:green"><img src="img/studentz.png" width="250" height="340" /></td></tr>
                            <tr><th class="tch" style="align:right">SURNAME</th><td class="tch1" width="40%">{{dat.surname | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">FIRSTNAME</th><td class="tch1" width="40%">{{dat.firstname | upper}}</td></tr>
                            <tr><th class="tch" style="align:right" >MIDDLENAME</th><td class="tch1" width="40%">{{dat.othername | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">SEX</th><td class="tch1" width="40%">{{gender}}</td></tr>
                            <tr><th class="tch" style="align:right">DATE OF BIRTH</th><td class="tch1" width="40%">{{dob }}</td></tr>
                            <tr><th class="tch" style="align:right">AGE</th><td class="tch1" width="40%">{{age}}</td></tr>
                            <tr><th class="tch" style="align:right">LGA/District</th><td class="tch1" width="40%">{{dat.lga | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">State/Region</th><td class="tch1" width="40%">{{dat.soo | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">Nationality</th><td class="tch1" width="40%">{{dat.nation | upper}}</td></tr>
                            <tr><th class="tch" style="align:right">Date Started</th><td class="tch1" width="40%">{{admit}}  ( {{admit_dur}})</td></tr>
                            <tr><th class="tch" style="align:right">Status</th><td class="tch1" width="40%">{{dat.schno}}<.td></tr>
                            <tr><th class="tch" style="align:right">Address</th><td class="tch1" width="40%" style="word-wrap:break-word;overflow:none">{{dat.addr}}</td></tr>
                        </tbody>
                    </table>
                </div>
                </div>
                <div width="100%" style="background-color:teal; color:white; text-transform:uppercase; align:center">
                    <h3>Guradians/Primary Care Giver</h3>
                </div>
                <div>
                <table width="100% " cellspacing="0" cellpadding="2px"  style="border-width:1px; border-color: teal; padding:2px" >
                <tbody style='align:left'>
                    <tr><td class="tch1" width="100%"><ul><li>{{dat.g1 | upper}}({{dat.g1rel | upper}}) </li><li> {{dat.g1p1}} | {{dat.g1p2}} </li><li> {{dat.g1addr | upper}} </li> <li>{{dat.g1email}}</li></ul></td></tr>
                    <tr><td class="tch1" width="100%"><ul><li>{{dat.g2 | upper}}({{dat.g2rel | upper}}) </li><li> {{dat.g2p1}} | {{dat.g2p2}} </li><li> {{dat.g2addr | upper}} </li> <li>{{dat.g2email}}</li></ul></td></tr>
                </tbody>
                </table>
                
                </div></body></html>'''

        h = Template(table).render(gender=self.gender,
                                   dob=self.dob,
                                   age=self.age,
                                   admit=self.admit,
                                   admit_dur=self.admit_dur,
                                   dat=self.data)
        return h

    def buildPsy(self, a):
        table = '''<html><head>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/invoice-print.css'/>
        <link rel ='stylesheet' type="text/css" href='static/stylesheets/theme.css'/>
        </head>
        <style>
        body{
            font: "Century Gothic";
        }
        table
        {
        
        }
        tbody, th, td{
        padding:2px;
         
        }
        td{ align:left}
        .tch{
                align: left !important;
                background-color:teal; 
                color:white;
                text-transform: uppercase;
                font-family: "Century Gothic";
        }
        .tch1{
                color:black;
                text-transform: uppercase;
                font-family: "Century Gothic";
                font-weight:bold;
                width: 300px;
        }
        .item-tab{
                display:inline-block;
        }
        td img{
        max-width: 100px;
        height:150px;
        }
        </style>
        <body>
            </body></html>'''

        h = Template(table).render(gender=self.gender,
                                   dob=self.dob,
                                   age=self.age,
                                   admit=self.admit,
                                   admit_dur=self.admit_dur,
                                   dat=self.data)
        return h
コード例 #15
0
ファイル: browsers.py プロジェクト: wioota/ftools-qgis
class LayerImportBrowser(QDialog):

    class VectorPage(QWidget):
        def __init__(self, parent=None, filters="", encodings=[]):
            QWidget.__init__(self, parent)
            self.filters = filters
            self.layerLineEdit = QLineEdit()
            self.browseToolButton = QToolButton()
            self.browseToolButton.setAutoRaise(True)
            self.browseToolButton.setIcon(QIcon(":document-open"))
            layerLabel = QLabel("&Dataset:")
            layerLabel.setBuddy(self.layerLineEdit)

            self.encodingComboBox = QComboBox()
            self.encodingComboBox.addItems(encodings)
            encodingLabel = QLabel("&Encoding:")
            encodingLabel.setBuddy(self.encodingComboBox)

            hbox = QHBoxLayout()
            hbox.addWidget(layerLabel)
            hbox.addWidget(self.layerLineEdit)
            hbox.addWidget(self.browseToolButton)
            vbox = QVBoxLayout()
            vbox.addLayout(hbox)
            hbox = QHBoxLayout()
            hbox.addWidget(encodingLabel)
            hbox.addWidget(self.encodingComboBox)
            vbox.addLayout(hbox)
            self.setLayout(vbox)
            self.encodingComboBox.setCurrentIndex(self.encodingComboBox.findText("System"))

            self.connect(self.browseToolButton,
                SIGNAL("clicked()"), self.browseToFile)
            self.connect(self.encodingComboBox,
                SIGNAL("currentIndexChanged(QString)"), self.changeEncoding)

        def browseToFile(self):
            dialog = QFileDialog(self, "manageR - Open Vector File",
                unicode(robjects.r.getwd()[0]), self.filters)
            if not dialog.exec_() == QDialog.Accepted:
                return
            files = dialog.selectedFiles()
            file = files.first().trimmed()
            self.layerLineEdit.setText(file)
            self.emit(SIGNAL("filePathChanged(QString)"), file)

        def changeEncoding(self, text):
            self.emit(SIGNAL("encodingChanged(QString)"), text)

    class RasterPage(QWidget):
        def __init__(self, parent=None, filters=""):
            QWidget.__init__(self, parent)
            self.parent = parent
            self.filters = filters
            self.layerLineEdit = QLineEdit()
            self.browseToolButton = QToolButton()
            self.browseToolButton.setAutoRaise(True)
            self.browseToolButton.setIcon(QIcon(":document-open"))
            layerLabel = QLabel("&Dataset:")
            layerLabel.setBuddy(self.layerLineEdit)

            hbox = QHBoxLayout()
            hbox.addWidget(layerLabel)
            hbox.addWidget(self.layerLineEdit)
            hbox.addWidget(self.browseToolButton)
            vbox = QVBoxLayout()
            vbox.addLayout(hbox)
            self.setLayout(vbox)

            self.connect(self.browseToolButton, SIGNAL("clicked()"), self.browseToFile)

        def browseToFile(self):
            dialog = QFileDialog(self, "manageR - Open Raster File",
                unicode(robjects.r.getwd()[0]), self.filters)
            if not dialog.exec_() == QDialog.Accepted:
                return
            files = dialog.selectedFiles()
            file = files.first().trimmed()
            self.layerLineEdit.setText(file)
            self.emit(SIGNAL("filePathChanged(QString)"), file)

    def __init__(self, parent=None, vectors="", rasters="", encodings=[]):
        QDialog.__init__(self, parent)
        self.contentsWidget = QListWidget()
        self.setWindowIcon(QIcon(":icon"))
        self.contentsWidget.setViewMode(QListView.IconMode)
        self.contentsWidget.setIconSize(QSize(76, 66))
        self.contentsWidget.setMovement(QListView.Static)
        self.contentsWidget.setMaximumWidth(106)
        self.contentsWidget.setMinimumWidth(106)
        self.contentsWidget.setMinimumHeight(220)
        self.contentsWidget.setSpacing(12)
        self.__filePath = ""
        self.__encoding = "System"
        self.__type = 0

        self.pagesWidget = QStackedWidget()
        vectorPage = self.VectorPage(self, vectors, encodings)
        self.pagesWidget.addWidget(vectorPage)
        rasterPage = self.RasterPage(self, rasters)
        self.pagesWidget.addWidget(rasterPage)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,
            Qt.Horizontal, self)

        self.connect(buttons, SIGNAL("accepted()"), self.accept)
        self.connect(buttons, SIGNAL("rejected()"), self.reject)
        self.connect(vectorPage, SIGNAL("filePathChanged(QString)"), self.setFilePath)
        self.connect(vectorPage, SIGNAL("encodingChanged(QString)"), self.setEncoding)
        self.connect(rasterPage, SIGNAL("filePathChanged(QString)"), self.setFilePath)

        self.createIcons()
        self.contentsWidget.setCurrentRow(0)

        horizontalLayout = QHBoxLayout()
        horizontalLayout.addWidget(self.contentsWidget)
        horizontalLayout.addWidget(self.pagesWidget, 1)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(horizontalLayout)
        mainLayout.addStretch(1)
        mainLayout.addSpacing(12)
        mainLayout.addWidget(buttons)
        self.setLayout(mainLayout)
        self.setWindowTitle("manageR - Import Layer")

    def createIcons(self):
        vectorButton = QListWidgetItem(self.contentsWidget)
        vectorButton.setIcon(QIcon(":custom-vector.svg"))
        vectorButton.setText("Vector Layer")
        vectorButton.setTextAlignment(Qt.AlignHCenter)
        vectorButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        rasterButton = QListWidgetItem(self.contentsWidget)
        rasterButton.setIcon(QIcon(":custom-raster.svg"))
        rasterButton.setText("Raster Layer")
        rasterButton.setTextAlignment(Qt.AlignHCenter)
        rasterButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        self.connect(self.contentsWidget,
            SIGNAL("currentItemChanged(QListWidgetItem*, QListWidgetItem*)"),
            self.changePage)

    def changePage(self, current, previous):
        if not current:
            current = previous
        self.pagesWidget.setCurrentIndex(self.contentsWidget.row(current))

    def filePath(self):
        return self.__filePath
        
    def setFilePath(self, filePath):
        self.__filePath = filePath

    def encoding(self):
        return self.__encoding
    
    def setEncoding(self, encoding):
        self.__encoding = encoding
        
    def layerType(self):
        return self.__type
        
    def setLayerType(self, type):
        self.__type = type

    def accept(self):
        self.__type = self.pagesWidget.currentIndex()
        QDialog.accept(self)
コード例 #16
0
ファイル: sidebar.py プロジェクト: eaglexmw/codimension
class SideBar( QWidget ):
    """ Sidebar with a widget area which is hidden or shown.
        On by clicking any tab, off by clicking the current tab.
    """

    North = 0
    East  = 1
    South = 2
    West  = 3

    def __init__( self, orientation = 2, parent = None ):
        QWidget.__init__( self, parent )

        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase( True )
        self.__tabBar.setShape( QTabBar.RoundedNorth )
        self.__tabBar.setFocusPolicy( Qt.NoFocus )
        self.__tabBar.setUsesScrollButtons( True )
        self.__tabBar.setElideMode( 1 )
        self.__stackedWidget = QStackedWidget( self )
        self.__stackedWidget.setContentsMargins( 0, 0, 0, 0 )
        self.barLayout = QBoxLayout( QBoxLayout.LeftToRight )
        self.barLayout.setMargin( 0 )
        self.layout = QBoxLayout( QBoxLayout.TopToBottom )
        self.layout.setMargin( 0 )
        self.layout.setSpacing( 0 )
        self.barLayout.addWidget( self.__tabBar )
        self.layout.addLayout( self.barLayout )
        self.layout.addWidget( self.__stackedWidget )
        self.setLayout( self.layout )

        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()

        self.splitter = None

        self.__tabBar.installEventFilter( self )

        self.__orientation = orientation
        self.setOrientation( orientation )

        self.__tabBar.currentChanged.connect(
                                        self.__stackedWidget.setCurrentIndex )
        return

    def setSplitter( self, splitter ):
        """ Set the splitter managing the sidebar """
        self.splitter = splitter
        return

    def __getIndex( self ):
        " Provides the widget index in splitters "
        if self.__orientation == SideBar.West:
            return 0
        if self.__orientation == SideBar.East:
            return 2
        if self.__orientation == SideBar.South:
            return 1
        return 0

    def __getWidget( self ):
        " Provides a reference to the widget "
        return self.splitter.widget( self.__getIndex() )

    def shrink( self ):
        """ Shrink the sidebar """
        if self.__minimized:
            return

        self.__minimized = True
        self.__bigSize = self.size()
        if self.__orientation in [ SideBar.North, SideBar.South ]:
            self.__minSize = self.minimumHeight()
            self.__maxSize = self.maximumHeight()
        else:
            self.__minSize = self.minimumWidth()
            self.__maxSize = self.maximumWidth()

        self.__stackedWidget.hide()

        sizes = self.splitter.sizes()
        selfIndex = self.__getIndex()

        if self.__orientation in [ SideBar.North, SideBar.South ]:
            newHeight = self.__tabBar.minimumSizeHint().height()
            self.setFixedHeight( newHeight )

            diff = sizes[ selfIndex ] - newHeight
            sizes[ selfIndex ] = newHeight
        else:
            newWidth = self.__tabBar.minimumSizeHint().width()
            self.setFixedWidth( newWidth )

            diff = sizes[ selfIndex ] - newWidth
            sizes[ selfIndex ] = newWidth

        if selfIndex == 0:
            sizes[ 1 ] += diff
        else:
            sizes[ selfIndex - 1 ] += diff

        self.splitter.setSizes( sizes )
        return

    def expand( self ):
        """ Expand the sidebar """
        if not self.__minimized:
            return

        self.__minimized = False
        self.__stackedWidget.show()
        self.resize( self.__bigSize )

        sizes = self.splitter.sizes()
        selfIndex = self.__getIndex()

        if self.__orientation in [ SideBar.North, SideBar.South ]:
            self.setMinimumHeight( self.__minSize )
            self.setMaximumHeight( self.__maxSize )

            diff = self.__bigSize.height() - sizes[ selfIndex ]
            sizes[ selfIndex ] = self.__bigSize.height()
        else:
            self.setMinimumWidth( self.__minSize )
            self.setMaximumWidth( self.__maxSize )

            diff = self.__bigSize.width() - sizes[ selfIndex ]
            sizes[ selfIndex ] = self.__bigSize.width()

        if selfIndex == 0:
            sizes[ 1 ] -= diff
        else:
            sizes[ selfIndex - 1 ] -= diff

        self.splitter.setSizes( sizes )
        return

    def isMinimized( self ):
        """ Provides the minimized state """
        return self.__minimized

    def eventFilter( self, obj, evt ):
        """ Handle click events for the tabbar """

        if obj == self.__tabBar:
            if evt.type() == QEvent.MouseButtonPress:
                pos = evt.pos()

                index = self.__tabBar.count() - 1
                while index >= 0:
                    if self.__tabBar.tabRect( index ).contains( pos ):
                        break
                    index -= 1

                if index == self.__tabBar.currentIndex():
                    if self.isMinimized():
                        self.expand()
                    else:
                        self.shrink()
                    return True

                elif self.isMinimized():
                    if self.isTabEnabled( index ):
                        self.expand()

        return QWidget.eventFilter( self, obj, evt )

    def addTab( self, widget, iconOrLabel, label = None ):
        """ Add a tab to the sidebar """

        if label:
            self.__tabBar.addTab( iconOrLabel, label )
        else:
            self.__tabBar.addTab( iconOrLabel )
        self.__stackedWidget.addWidget( widget )
        return

    def insertTab( self, index, widget, iconOrLabel, label = None ):
        """ Insert a tab into the sidebar """

        if label:
            self.__tabBar.insertTab( index, iconOrLabel, label )
        else:
            self.__tabBar.insertTab( index, iconOrLabel )
        self.__stackedWidget.insertWidget( index, widget )
        return

    def removeTab( self, index ):
        """ Remove a tab """

        self.__stackedWidget.removeWidget( self.__stackedWidget.widget( index ) )
        self.__tabBar.removeTab( index )
        return

    def clear( self ):
        """ Remove all tabs """

        while self.count() > 0:
            self.removeTab( 0 )
        return

    def prevTab( self ):
        """ Show the previous tab """

        index = self.currentIndex() - 1
        if index < 0:
            index = self.count() - 1

        self.setCurrentIndex( index )
        self.currentWidget().setFocus()
        return

    def nextTab( self ):
        """ Show the next tab """

        index = self.currentIndex() + 1
        if index >= self.count():
            index = 0

        self.setCurrentIndex( index )
        self.currentWidget().setFocus()
        return

    def count( self ):
        """ Provides the number of tabs """

        return self.__tabBar.count()

    def currentIndex( self ):
        """ Provides the index of the current tab """

        return self.__stackedWidget.currentIndex()

    def setCurrentIndex( self, index ):
        """ Switch to the certain tab """

        if index >= self.currentIndex():
            return

        self.__tabBar.setCurrentIndex( index )
        self.__stackedWidget.setCurrentIndex(index)
        if self.isMinimized():
            self.expand()
        return

    def currentWidget( self ):
        """ Provide a reference to the current widget """

        return self.__stackedWidget.currentWidget()

    def setCurrentWidget( self, widget ):
        """ Set the current widget """

        self.__stackedWidget.setCurrentWidget( widget )
        self.__tabBar.setCurrentIndex( self.__stackedWidget.currentIndex() )
        if self.isMinimized():
            self.expand()
        return

    def indexOf( self, widget ):
        """ Provides the index of the given widget """

        return self.__stackedWidget.indexOf( widget )

    def isTabEnabled( self, index ):
        """ Check if the tab is enabled """

        return self.__tabBar.isTabEnabled( index )

    def setTabEnabled( self, index, enabled ):
        """ Set the enabled state of the tab """

        self.__tabBar.setTabEnabled( index, enabled )
        return

    def orientation( self ):
        """ Provides the orientation of the sidebar """

        return self.__orientation

    def setOrientation( self, orient ):
        """ Set the orientation of the sidebar """

        if orient == SideBar.North:
            self.__tabBar.setShape( QTabBar.RoundedNorth )
            self.barLayout.setDirection( QBoxLayout.LeftToRight )
            self.layout.setDirection( QBoxLayout.TopToBottom )
            self.layout.setAlignment( self.barLayout, Qt.AlignLeft )
        elif orient == SideBar.East:
            self.__tabBar.setShape( QTabBar.RoundedEast )
            self.barLayout.setDirection( QBoxLayout.TopToBottom )
            self.layout.setDirection( QBoxLayout.RightToLeft )
            self.layout.setAlignment( self.barLayout, Qt.AlignTop )
        elif orient == SideBar.South:
            self.__tabBar.setShape( QTabBar.RoundedSouth )
            self.barLayout.setDirection( QBoxLayout.LeftToRight )
            self.layout.setDirection( QBoxLayout.BottomToTop )
            self.layout.setAlignment( self.barLayout, Qt.AlignLeft )
        else:
            # default
            orient = SideBar.West
            self.__tabBar.setShape( QTabBar.RoundedWest )
            self.barLayout.setDirection( QBoxLayout.TopToBottom )
            self.layout.setDirection( QBoxLayout.LeftToRight )
            self.layout.setAlignment( self.barLayout, Qt.AlignTop )
        self.__orientation = orient
        return

    def tabIcon( self, index ):
        """ Provide the icon of the tab """

        return self.__tabBar.tabIcon( index )

    def setTabIcon( self, index, icon ):
        """ Set the icon of the tab """

        self.__tabBar.setTabIcon( index, icon )
        return

    def tabText( self, index ):
        """ Provide the text of the tab """

        return self.__tabBar.tabText( index )

    def setTabText( self, index, text ):
        """ Set the text of the tab """

        self.__tabBar.setTabText( index, text )
        return

    def tabToolTip( self, index ):
        """ Provide the tooltip text of the tab """

        return self.__tabBar.tabToolTip( index )

    def setTabToolTip( self, index, tip ):
        """ Set the tooltip text of the tab """

        self.__tabBar.setTabToolTip( index, tip )
        return

    def tabWhatsThis( self, index ):
        """ Provide the WhatsThis text of the tab """

        return self.__tabBar.tabWhatsThis( index )

    def setTabWhatsThis( self, index, text ):
        """ Set the WhatsThis text for the tab """

        self.__tabBar.setTabWhatsThis( index, text )
        return

    def widget( self, index ):
        """ Provides the reference to the widget (QWidget) """

        return self.__stackedWidget.widget( index )
コード例 #17
0
class GUI(QtGui.QMainWindow):
    def __init__(self, win_parent=None):
        '''
        Initialize main window
        '''
        QtGui.QMainWindow.__init__(self, win_parent)
        self.setWindowTitle('MapFormers: Get nodes geolocations')
        self.setGeometry(250, 200, 714, 491)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setWindowFlags(Qt.CustomizeWindowHint)
        self.setWindowFlags(Qt.WindowSystemMenuHint)
        self.setWindowIcon(QtGui.QIcon(Paths["Icon"]))
        self.Elem_init()
        self.InitialValues()
        self.setGeometry_()
        self.InitialValues()
        self.setLabels()
        self.SetLayouts()

        if not CheckAttr(Visum.Net.Nodes, 'Google_X'):
            Visum.Net.Nodes.AddUserDefinedAttribute('Google_X', 'Google_X',
                                                    'Google_X', 2,
                                                    10)  #else create UDAs
        if not CheckAttr(Visum.Net.Nodes, 'Google_Y'):
            Visum.Net.Nodes.AddUserDefinedAttribute('Google_Y', 'Google_Y',
                                                    'Google_Y', 2,
                                                    10)  #else create UDAs

        self.connect(self.SB_NodeNumber, QtCore.SIGNAL('editingFinished()'),
                     self.MakeVisScreenshot)
        self.connect(self.DSB_Zoom, QtCore.SIGNAL('editingFinished()'),
                     self.MakeVisScreenshot)

        self.connect(self.SB_NodeNumber, QtCore.SIGNAL('editingFinished()'),
                     self.UpdateGeoPos)
        self.connect(self.SB_NodeNumber, QtCore.SIGNAL('valueChanged()'),
                     self.UpdateGeoPos)

        self.connect(self.B_ImportPos, QtCore.SIGNAL('clicked()'),
                     self.ImportGeoPosition)

        self.connect(self.B_Next, QtCore.SIGNAL('clicked()'), self.NextWindow)
        self.connect(self.B_Back, QtCore.SIGNAL('clicked()'), self.BackWindow)

        self.connect(self.B_Calculate, QtCore.SIGNAL('clicked()'),
                     self.Transform)
        self.connect(self.RB_prj, QtCore.SIGNAL('clicked()'), self.RBPrjClick)
        self.connect(self.RB_regression, QtCore.SIGNAL('clicked()'),
                     self.RBRegClick)
        self.connect(self.RB_partiall, QtCore.SIGNAL('clicked()'),
                     self.RBParClick)

        self.connect(self.B_Cancel, QtCore.SIGNAL('clicked()'),
                     self.closeEvent)
        self.connect(self.B_Cancel_T2, QtCore.SIGNAL('clicked()'),
                     self.closeEvent)

        self.connect(self.B_Help, QtCore.SIGNAL('clicked()'), self.openHelp)
        self.connect(self.B_Help_T2, QtCore.SIGNAL('clicked()'), self.openHelp)

    def Elem_init(self):

        self.SW_Main = QStackedWidget(self)

        self.SW_Tab1 = QWidget(self.SW_Main)
        self.SW_Tab2 = QWidget(self.SW_Main)

        self.GB_LeftSide = QGroupBox(self.SW_Tab1)
        self.GB_RightSide = QGroupBox(self.SW_Tab1)
        self.BottomWidget = QtGui.QWidget(self.SW_Tab1)

        self.Wid_LayVer_LeftSide = QtGui.QWidget(self.GB_LeftSide)
        self.L_ImageLeft = QtGui.QLabel(self.Wid_LayVer_LeftSide)

        self.GB_Options_LB = QtGui.QGroupBox(self.GB_LeftSide)

        self.L_NodeNumber = QtGui.QLabel(self.GB_Options_LB)
        self.L_zoom = QtGui.QLabel(self.GB_Options_LB)
        self.SB_NodeNumber = QtGui.QSpinBox(self.GB_Options_LB)
        self.DSB_Zoom = QtGui.QDoubleSpinBox(self.GB_Options_LB)
        self.L_GeoT = QtGui.QLabel(self.GB_Options_LB)
        self.L_GeoPos = QtGui.QLabel(self.GB_Options_LB)

        self.ImageLeft = QtGui.QPixmap(Paths["Screenshot"])

        self.Wid_LayVer_RightSide = QtGui.QWidget(self.GB_RightSide)

        self.B_ImportPos = QtGui.QPushButton(self.Wid_LayVer_RightSide)
        self.Web = QWebView(self.Wid_LayVer_RightSide)

        self.B_Help = QtGui.QPushButton(self.BottomWidget)
        self.B_Next = QtGui.QPushButton(self.BottomWidget)
        self.B_Cancel = QtGui.QPushButton(self.BottomWidget)
        self.L_ImageLogo = QtGui.QLabel(self.BottomWidget)

        self.ImageLogo = QtGui.QPixmap(Paths["Logo"])

        self.BG_Transform = QtGui.QGroupBox(self.SW_Tab2)
        self.BottomWidget_T2 = QtGui.QWidget(self.SW_Tab2)

        self.GB_Opt_T2 = QtGui.QGroupBox(self.SW_Tab2)

        self.SB_NodeNumber_T2 = QtGui.QSpinBox(self.GB_Opt_T2)
        self.DSB_Factor_T2 = QtGui.QDoubleSpinBox(self.GB_Opt_T2)
        self.L_Factor_T2 = QtGui.QLabel(self.GB_Opt_T2)
        self.L_NodeNumber_T2 = QtGui.QLabel(self.GB_Opt_T2)

        self.RB_prj = QRadioButton(self.BG_Transform)
        self.RB_regression = QRadioButton(self.BG_Transform)
        self.RB_partiall = QRadioButton(self.BG_Transform)

        self.B_Help_T2 = QtGui.QPushButton(self.BottomWidget_T2)
        self.B_Back = QtGui.QPushButton(self.BottomWidget_T2)
        self.B_Calculate = QtGui.QPushButton(self.BottomWidget_T2)
        self.B_Cancel_T2 = QtGui.QPushButton(self.BottomWidget_T2)
        self.L_ImageLogo_T2 = QtGui.QLabel(self.BottomWidget_T2)

        self.LayGrid_Main = QtGui.QGridLayout()
        self.LayVer_LeftSide = QtGui.QVBoxLayout()
        self.LayVer_RightSide = QtGui.QVBoxLayout()
        self.LayGrid_Bottom = QtGui.QGridLayout()
        self.LayGrid_Opt = QtGui.QGridLayout()
        self.LayVer_Main_T2 = QtGui.QVBoxLayout()
        self.Lay_Transform = QVBoxLayout()
        self.LayGrid_Bottom_T2 = QtGui.QGridLayout()
        self.BL_Lay_Transform = QtGui.QVBoxLayout()

        self.LayHor_Opt_T2 = QtGui.QHBoxLayout()

        self.V_NodeFilter = Visum.Filters.NodeFilter()
        self.V_LinkFilter = Visum.Filters.LinkFilter()

    def setLabels(self):

        self.GB_LeftSide.setTitle("Visum Node")
        self.GB_RightSide.setTitle("Map reference")
        self.L_NodeNumber.setText("Node number:")
        self.L_zoom.setText("Zoom:")
        self.L_GeoT.setText("Current node's geoposition:")
        self.L_GeoPos.setText("no reference")
        self.B_ImportPos.setText("Save reference")
        self.B_Help.setText("Help")
        self.B_Next.setText("Next ->")
        self.B_Cancel.setText("Cancel")
        self.RB_prj.setText(
            "Option 1: Transform network by means of .prj file.\n (This option will worn only if network scale is linear (scale for X axis = scale for Y axis) - \n in most cases it will not work for Your network."
        )
        self.RB_regression.setText(
            "Option 2: Transform network by means of linear regression calibrated with input reference data. \n Specify confidence factor [0-1] for input data in the box below - default value is 0.8"
        )
        self.RB_partiall.setText(
            "Option 3: Adjust only active part of the network (nodes, and links) based on reference node from box below"
        )
        self.BG_Transform.setTitle("Transform network")
        self.B_Help_T2.setText("Help")
        self.B_Back.setText("<- Back")
        self.B_Calculate.setText("Calculate")
        self.B_Cancel_T2.setText("Cancel")
        self.L_Factor_T2.setText("Confidence factor:")
        self.L_NodeNumber_T2.setText("Node number:")

    def setGeometry_(self):

        self.B_Help.setFixedSize(85, 23)
        self.B_Next.setFixedSize(85, 23)
        self.B_Cancel.setFixedSize(85, 23)
        self.L_ImageLogo.setFixedSize(200, 32)
        self.B_Help_T2.setFixedSize(85, 23)
        self.B_Back.setFixedSize(85, 23)
        self.B_Calculate.setFixedSize(85, 23)
        self.B_Cancel_T2.setFixedSize(85, 23)
        self.L_ImageLogo_T2.setFixedSize(200, 32)

        self.L_ImageLeft.setMinimumSize(300, 300)
        self.L_ImageLeft.setBaseSize(350, 350)
        self.Web.setContentsMargins(0, 0, 0, 0)
        self.Web.setMinimumSize(350, 350)
        self.Web.setBaseSize(375, 375)

    def InitialValues(self):

        self.setCentralWidget(self.SW_Main)

        self.Web.page().mainFrame().load(QUrl(Paths["Html"]))
        self.Web.page().setViewportSize(
            self.Web.page().mainFrame().contentsSize())

        NodeIter = Visum.Net.Nodes.Iterator
        try:
            FirstActiveNode = NodeIter.Item.AttValue("No")
        except:
            Visum.Net.AddNode(1, 1, 1)
            NodeIter = Visum.Net.Nodes.Iterator
            FirstActiveNode = NodeIter.Item.AttValue("No")

        Visum.Graphic.Autozoom(Visum.Net.Nodes.ItemByKey(FirstActiveNode))
        self.V_NodeFilter.Init()
        self.V_NodeFilter.AddCondition("OP_NONE", False, "NO", "EqualVal",
                                       FirstActiveNode)
        self.V_NodeFilter.UseFilter = True

        self.V_LinkFilter.Init()
        self.V_LinkFilter.AddCondition("OP_NONE", False, "ToNodeNo",
                                       "EqualVal", FirstActiveNode)
        self.V_LinkFilter.UseFilter = True

        Visum.Graphic.Screenshot(Paths["Screenshot"])
        Screenshot = QtGui.QPixmap(Paths["Screenshot"])

        self.SB_NodeNumber.setValue(FirstActiveNode)
        self.SB_NodeNumber.setMaximum(1000000000)

        self.SB_NodeNumber_T2.setValue(FirstActiveNode)
        self.SB_NodeNumber_T2.setMaximum(1000000000)

        self.DSB_Factor_T2.setValue(0.8)
        self.DSB_Factor_T2.setMaximum(1)

        self.DSB_Zoom.setValue(1)
        self.DSB_Zoom.setSingleStep(0.5)
        self.DSB_Zoom.setMaximum(1000000)

        self.L_ImageLeft.setPixmap(Screenshot)
        self.L_ImageLeft.setScaledContents(True)

        self.ImageLogo.scaled(200, 23, Qt.IgnoreAspectRatio,
                              Qt.SmoothTransformation)
        #self.L_ImageLogo.setScaledContents(True)
        self.L_ImageLogo.setPixmap(self.ImageLogo)

        self.L_ImageLogo_T2.setScaledContents(True)
        self.L_ImageLogo_T2.setPixmap(self.ImageLogo)

        self.L_ImageLeft.show()
        self.RBRegClick()

        self.RB_regression.setChecked(True)

    def SetLayouts(self):

        self.L_NodeNumber.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.L_zoom.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.SB_NodeNumber.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        self.DSB_Zoom.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        self.L_GeoT.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.L_GeoPos.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        self.L_ImageLogo_T2.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
        self.L_ImageLogo.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)

        self.L_NodeNumber_T2.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.SB_NodeNumber_T2.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        self.L_Factor_T2.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.DSB_Factor_T2.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)

        self.GB_Options_LB.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
        self.BottomWidget_T2.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Fixed)
        self.GB_Opt_T2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        self.LayGrid_Opt.addWidget(self.L_NodeNumber, 1, 0, 1, 1)
        self.LayGrid_Opt.addWidget(self.L_zoom, 1, 2, 1, 1)
        self.LayGrid_Opt.addWidget(self.SB_NodeNumber, 1, 1, 1, 1)
        self.LayGrid_Opt.addWidget(self.DSB_Zoom, 1, 3, 1, 1)
        self.LayGrid_Opt.addWidget(self.L_GeoT, 0, 0, 1, 2)
        self.LayGrid_Opt.addWidget(self.L_GeoPos, 0, 2, 1, 2)
        self.LayGrid_Opt.setVerticalSpacing(20)

        self.LayVer_LeftSide.addWidget(self.L_ImageLeft)
        self.LayVer_LeftSide.addWidget(self.GB_Options_LB)
        self.LayVer_LeftSide.setSpacing(20)

        self.LayVer_RightSide.addWidget(self.Web)
        self.LayVer_RightSide.addWidget(self.B_ImportPos)
        self.LayVer_RightSide.setSpacing(20)

        self.LayGrid_Bottom.addWidget(self.B_Help, 0, 0, 1, 1)
        self.LayGrid_Bottom.addWidget(QWidget(), 0, 1, 1, 1)
        self.LayGrid_Bottom.addWidget(self.L_ImageLogo, 0, 2, 1, 1)
        self.LayGrid_Bottom.addWidget(QWidget(), 0, 3, 1, 1)
        self.LayGrid_Bottom.addWidget(self.B_Next, 0, 4, 1, 1)
        self.LayGrid_Bottom.addWidget(self.B_Cancel, 0, 5, 1, 1)

        self.LayGrid_Main.addWidget(self.GB_LeftSide, 0, 0, 1, 2)
        self.LayGrid_Main.addWidget(self.GB_RightSide, 0, 2, 1, 4)
        self.LayGrid_Main.addWidget(self.BottomWidget, 1, 0, 1, 6)

        self.BL_Lay_Transform.addWidget(self.RB_prj)
        self.BL_Lay_Transform.addWidget(self.RB_regression)
        self.BL_Lay_Transform.addWidget(self.RB_partiall)

        self.LayGrid_Bottom_T2.addWidget(self.B_Help_T2, 0, 0, 1, 1)
        self.LayGrid_Bottom_T2.addWidget(QWidget(), 0, 1, 1, 1)
        self.LayGrid_Bottom_T2.addWidget(self.L_ImageLogo_T2, 0, 2, 1, 1)
        self.LayGrid_Bottom_T2.addWidget(QWidget(), 0, 3, 1, 1)
        self.LayGrid_Bottom_T2.addWidget(self.B_Back, 0, 4, 1, 1)
        self.LayGrid_Bottom_T2.addWidget(self.B_Calculate, 0, 5, 1, 1)
        self.LayGrid_Bottom_T2.addWidget(self.B_Cancel_T2, 0, 6, 1, 1)

        self.LayHor_Opt_T2.addWidget(self.L_NodeNumber_T2)
        self.LayHor_Opt_T2.addWidget(self.SB_NodeNumber_T2)
        self.LayHor_Opt_T2.addWidget(self.L_Factor_T2)
        self.LayHor_Opt_T2.addWidget(self.DSB_Factor_T2)
        self.LayHor_Opt_T2.addWidget(QWidget())

        self.LayVer_Main_T2.addWidget(self.BG_Transform)
        self.LayVer_Main_T2.addWidget(self.GB_Opt_T2)
        self.LayVer_Main_T2.addWidget(QWidget())
        self.LayVer_Main_T2.addWidget(self.BottomWidget_T2)

        self.GB_Opt_T2.setLayout(self.LayHor_Opt_T2)

        self.SW_Main.addWidget(self.SW_Tab1)
        self.SW_Main.addWidget(self.SW_Tab2)

        self.GB_LeftSide.setLayout(self.LayVer_LeftSide)
        self.GB_RightSide.setLayout(self.LayVer_RightSide)
        self.GB_Options_LB.setLayout(self.LayGrid_Opt)
        self.BottomWidget.setLayout(self.LayGrid_Bottom)
        self.SW_Tab1.setLayout(self.LayGrid_Main)
        self.BG_Transform.setLayout(self.BL_Lay_Transform)
        self.BottomWidget_T2.setLayout(self.LayGrid_Bottom_T2)
        self.SW_Tab2.setLayout(self.LayVer_Main_T2)

    def RBPrjClick(self):
        self.DSB_Factor_T2.setDisabled(True)
        self.SB_NodeNumber_T2.setDisabled(True)

    def RBRegClick(self):
        self.DSB_Factor_T2.setEnabled(True)
        self.SB_NodeNumber_T2.setDisabled(True)

    def RBParClick(self):
        self.DSB_Factor_T2.setDisabled(True)
        self.SB_NodeNumber_T2.setEnabled(True)

    def NextWindow(self):
        self.SW_Main.setCurrentIndex(1)
        self.setWindowTitle('MapFormers: Transform network'
                            )  #dodanie filtra na nodes - Google_X>0
        self.V_NodeFilter.Init()
        self.V_NodeFilter.AddCondition("OP_NONE", False, "Google_X", 3, 0)
        self.V_NodeFilter.UseFilter = True

    def BackWindow(self):
        self.SW_Main.setCurrentIndex(0)
        self.setWindowTitle('MapFormers: Get nodes geolocations')

    def UpdateGeoPos(self):
        '''
        Script updates label displaying node's geolocation
        '''

        NodeNumber = self.SB_NodeNumber.value()
        try:

            xf = Visum.Net.Nodes.ItemByKey(NodeNumber).AttValue("Google_X")
            x = QString()
            x.setNum(xf, 'g', 5)
            yf = Visum.Net.Nodes.ItemByKey(NodeNumber).AttValue("Google_Y")
            y = QString()
            y.setNum(yf, 'g', 5)
            if (xf == 0 and yf == 0):
                self.Web.page().mainFrame().evaluateJavaScript(
                    "removemarkers();")
                self.L_GeoPos.setText("no reference")
            else:
                self.L_GeoPos.setText("x: " + x + " N" + " y: " + y + " E")
                self.Web.page().mainFrame().evaluateJavaScript(
                    "Gx = %f; Gy = %f;" % (xf, yf))
                self.Web.page().mainFrame().evaluateJavaScript("markerf();")

        except:
            self.L_GeoPos.setText("node does not exist")

    def ImportGeoPosition(self):
        '''        
        evaluate JavaScript to return previously selected geographical position in OpenLayers WebWidget
        '''
        NodeNumber = self.SB_NodeNumber.value()
        try:
            Visum.Net.Nodes.GetMultiAttValues(
                'Google_X')  #check if UDAs exists
        except:
            Visum.Net.Nodes.AddUserDefinedAttribute('Google_X', 'Google_X',
                                                    'Google_X', 2,
                                                    10)  #else create UDAs
            Visum.Net.Nodes.AddUserDefinedAttribute('Google_Y', 'Google_Y',
                                                    'Google_Y', 2, 10)

        Visum.Net.Nodes.ItemByKey(NodeNumber).SetAttValue(
            "Google_X",
            self.Web.page().mainFrame().evaluateJavaScript(
                "returnposx();").toReal()[0]
        )  # w pliku html trzeba sie upewnic, ze to zawsze bedzie wspolrzedna lon/lat ! ! ! czasami osm samo zmienia na Projected Coordinate System (czyli wartosci okolo miliona, tak nie moze byc, bo nigdy nie dojdziemy do ladu!zawsze musza byc lon/lat
        Visum.Net.Nodes.ItemByKey(NodeNumber).SetAttValue(
            "Google_Y",
            self.Web.page().mainFrame().evaluateJavaScript(
                "returnposy();").toReal()[0])
        self.UpdateGeoPos()

    def Transform(self):

        type = [
            self.RB_prj.isChecked(), False,
            self.RB_regression.isChecked(),
            self.RB_partiall.isChecked()
        ]

        nodeno = self.SB_NodeNumber_T2.value()
        factor = self.DSB_Factor_T2.value()

        def rescale(scaleX, scaleY, deltaX, deltaY, activeOnly):
            def link_iter():
                def New_WKT(WKT, scaleX, scaleY, deltaX, deltaY):

                    WKT = str(WKT[11:-1])
                    WKT = WKT.split(',')
                    for i in range(len(WKT)):
                        WKT[i] = WKT[i].split(' ')
                    WKT = [[i for i in el] for el in WKT]
                    del WKT[0]
                    del WKT[-1]
                    Mtx = [[
                        scaleX * float(el[0]) + deltaX,
                        scaleY * float(el[1]) + deltaY
                    ] for el in WKT]

                    Nowy = [[float(el[0]), float(el[1])] for el in Mtx]
                    Nowy = ', '.join([str(x) for x in Nowy])
                    Nowy = Nowy.replace('],', 'www')
                    Nowy = Nowy.replace(',', '')
                    Nowy = Nowy.replace('www', ',')
                    Nowy = Nowy.replace('[', '')
                    Nowy = Nowy.replace(']', '')
                    Nowy = 'LINESTRING(' + Nowy + ')'
                    return Nowy

                Container = Visum.Net.Links
                WKTs = Container.GetMultiAttValues('WKTPOLY', activeOnly)
                New_WKTs = []
                for i in range(len(WKTs)):
                    New_WKTs.append((WKTs[i][0],
                                     New_WKT(WKTs[i][1], scaleX, scaleY,
                                             deltaX, deltaY)))
                return tuple(New_WKTs)

            def iter(Container):
                Xy = Container.GetMultiAttValues('XCoord', activeOnly)
                Yy = Container.GetMultiAttValues('YCoord', activeOnly)
                New_Xy = []
                New_Yy = []
                for i in range(len(Xy)):
                    New_Xy.append((Xy[i][0], scaleX * Xy[i][1] + deltaX))
                    New_Yy.append((Yy[i][0], scaleY * Yy[i][1] + deltaY))
                return tuple(New_Xy), tuple(New_Yy)
                Container.SetMultiAttValues('XCoord', tuple(New_Xy))
                Container.SetMultiAttValues('YCoord', tuple(New_Yy))

            Node_X, Node_Y = iter(Visum.Net.Nodes)
            New_WKTs = link_iter()
            Zone_X, Zone_Y = iter(Visum.Net.Zones)
            #Visum.Graphic.ShowMinimized()
            Visum.Net.Nodes.SetMultiAttValues('XCoord', Node_X)
            Visum.Net.Nodes.SetMultiAttValues('YCoord', Node_Y)
            try:
                Visum.Net.Links.SetMultiAttValues('WKTPOLY', New_WKTs)
            except:
                pass
            try:
                Visum.Net.Zones.SetMultiAttValues('XCoord', Zone_X)
                Visum.Net.Zones.SetMultiAttValues('YCoord', Zone_Y)
            except:
                pass

        def get_wgs(X):  #transform google lon lat to X,Y

            from pyproj import Proj

            pr_tm = Proj(
                '+proj=merc +lat_0=0 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs'
            )

            x_latlong = X[0]
            y_latlong = X[1]

            x_tm, y_tm = pr_tm(X[0], X[1])

            return x_tm, y_tm

        def set_Visum_projection(false_easting, false_northing, scale):
            scale = 1 / float(
                scale)  #""" reciprocal of scale  correct effect """
            Visum_Projection = u'PROJCS["Mapformers",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["GRS_1980",6378137.0,298.257223562]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Mercator"],PARAMETER["False_Easting",' + str(
                false_easting
            ) + ' ],PARAMETER["False_Northing",' + str(
                false_northing
            ) + ' ],PARAMETER["Central_Meridian",0],PARAMETER["Standard_Parallel_1",0],UNIT["Meter",' + str(
                scale) + ']]'
            Visum.Net.NetParameters.SetProjection(Visum_Projection, True)

        def get_coords():
            Visum_X = Visum.Net.Nodes.GetMultiAttValues('XCoord', True)
            Visum_X = [el[1] for el in Visum_X]
            Visum_Y = Visum.Net.Nodes.GetMultiAttValues('YCoord', True)
            Visum_Y = [el[1] for el in Visum_Y]
            Google_X = Visum.Net.Nodes.GetMultiAttValues('Google_X', True)
            Google_X = [el[1] for el in Google_X]
            Google_Y = Visum.Net.Nodes.GetMultiAttValues('Google_Y', True)
            Google_Y = [el[1] for el in Google_Y]

            #if Google_X[0]<200:
            #    for i in range(len(Google_X)):
            #        point=[Google_X[i],Google_Y[i]]
            #        [Google_X[i],Google_Y[i]]=get_wgs(point)

            return Visum_X, Visum_Y, Google_X, Google_Y

        def linreg(Visum_, Google_):
            try:
                numpy
            except:
                import numpy as np

            (scale, delta) = np.polyfit(Visum_, Google_, 1)
            nGoogle_ = np.polyval([scale, delta], Visum_)
            err = (sum((nGoogle_ - Google_)**2) / len(Visum_))**.5
            return scale, delta, err

        def cleaned_linreg(Visum_, Google_, cut_factor):
            try:
                numpy
            except:
                import numpy as np

            errs = []
            cut_factor = min((max(cut_factor, .1)), 1)
            range_ = range(max(1, int(len(Google_) * cut_factor)))
            for j in range_:
                (scale, delta) = np.polyfit(Visum_, Google_, 1)
                nGoogle_ = np.polyval([scale, delta], Visum_)
                err = [(nGoogle_[i] - Google_[i])**2
                       for i in range(len(nGoogle_))]
                errs.append((sum((nGoogle_ - Google_)**2) / len(Visum_))**.5)
                max_err = err.index(max(err))
                Visum_.remove(Visum_[max_err])
                Google_.remove(Google_[max_err])

            return scale, delta, errs

        def dist(X, Y):
            return ((X[0] - X[1])**2 + (Y[0] - Y[1])**2)**.5

        def do_projection(Visum_X, Visum_Y, Google_X, Google_Y):
            dist_Visum = dist(
                Visum_X, Visum_Y
            )  #"""calculate distance in Visum, and real distance in Google"""
            dist_Google = dist(Google_X, Google_Y)
            scale = dist_Google / dist_Visum
            set_Visum_projection(
                0, 0, 1)  #"""first set base projection with scale =1"""
            set_Visum_projection(0, 0, scale)  #"""now adjust the scale"""
            Visum_X = Visum.Net.Nodes.GetMultiAttValues('XCoord', True)
            Visum_X = [el[1] for el in Visum_X]
            Visum_Y = Visum.Net.Nodes.GetMultiAttValues('YCoord', True)
            Visum_Y = [el[1] for el in Visum_Y]  #"""get new rescaled coords"""
            delta_X = Google_X[0] - Visum_X[0]
            delta_Y = Google_Y[0] - Visum_Y[0]
            set_Visum_projection(
                0, 0, 1)  #"""first set base projection with scale = 1"""
            set_Visum_projection(0, 0, scale)  #"""now adjust the scale"""
            set_Visum_projection(
                0, 0, 1)  #"""now set bas projection one more time"""
            set_Visum_projection(delta_X, delta_Y,
                                 scale)  #"""and go to proper projection"""

        def analyse_Coords(Visum_X, Visum_Y, Google_X, Google_Y):
            def dst_mtx(A, *B):
                try:
                    B
                    mtx = [[abs(a - b) for a in A] for b in B]
                except:
                    mtx = [[abs(a - b) for a in A] for b in A]
                return mtx

            def get_scale(Visum_d, Google_d):
                range_ = range(len(Visum_d))
                Visum_deltas = dst_mtx(Visum_d)
                for i in range_:
                    for j in range_:
                        if i == j:
                            Visum_deltas[i][i] = 1000000000000000000000

                Google_deltas = dst_mtx(Google_d)
                scales = [[
                    Google_deltas[i][j] / Visum_deltas[i][j] for i in range_
                ] for j in range_]
                return sum([sum(row) for row in scales
                            ]) / (len(Visum_d)**2 - len(Visum_d))

            def get_delta(Visum_d, Google_d, scale):
                size = len(Visum_d)

                return -sum(
                    [Visum_d[i] * scale - Google_d[i]
                     for i in range(size)]) / float(size)

            def get_tg_Mtx(Visum_X, Visum_Y, Google_X, Google_Y):
                # to do ! dla macierzy obliczyc tg nachylenia par punktow dla Googla i dla Visuma
                # policzyc roznice miedzy katami i statycznie opisac (mean, std, dev, etc.)
                pass

            scale_X = get_scale(Visum_X, Google_X)
            scale_Y = get_scale(Visum_Y, Google_Y)
            delta_X = get_delta(Visum_X, Google_X, scale_X)
            delta_Y = get_delta(Visum_Y, Google_Y, scale_Y)
            return scale_X, scale_Y, delta_X, delta_Y

        #tg_V=abs(Visum_X[0]-Visum_X[1])/abs(Visum_Y[0]-Visum_Y[1])
        #tg_G=abs(Google_X[0]-Google_X[1])/abs(Google_Y[0]-Google_Y[1])
        #dev=1-tg_V/tg_G

        Visum_X, Visum_Y, Google_X, Google_Y = get_coords()
        Visum.Graphic.ShowMinimized()

        if type == [1, 0, 0, 0]:
            """ poprzez projekcje Visum set projection """
            do_projection(Visum_X, Visum_Y, Google_X, Google_Y)

        elif type == [0, 1, 0, 0]:
            """ przypadek rescale dla dwu punktow """

            scale_X, scale_Y, delta_X, delta_Y = analyse_Coords(
                Visum_X, Visum_Y, Google_X, Google_Y)
            rescale(scale_X, scale_Y, delta_X, delta_Y, False)

        elif type == [0, 0, 1, 0]:
            """ przypadek rescale dla wielu punktow """
            scale_X, delta_X, _ = cleaned_linreg(
                Visum_X, Google_X, factor)  #zmiana 0,8 -> factor.
            scale_Y, delta_Y, _ = cleaned_linreg(Visum_Y, Google_Y, factor)
            rescale(scale_X, scale_Y, delta_X, delta_Y, False)

        else:
            """ przesuniecie czesci sieci (dodatkowy tuning) """
            Node = Visum.Net.Nodes.ItemByKey(nodeno)
            delta_X = Node.AttValue('Google_X') - Node.AttValue('XCoord')
            delta_Y = Node.AttValue('Google_Y') - Node.AttValue('YCoord')
            rescale(1, 1, delta_X, delta_Y, True)

        Visum.Graphic.ShowMaximized()
        #"""finito"""

    def MakeVisScreenshot(self):
        '''
        make the screenshot of visum network with selected options
        '''
        NodeNumber = self.SB_NodeNumber.value()
        zoom = self.DSB_Zoom.value()
        try:
            zoom = 1 / zoom
        except:
            pass

        try:
            Visum.Graphic.Autozoom(Visum.Net.Nodes.ItemByKey(NodeNumber))
            self.V_NodeFilter.Init()
            self.V_NodeFilter.AddCondition("OP_NONE", False, "NO", "EqualVal",
                                           NodeNumber)
            self.V_NodeFilter.UseFilter = True

            self.V_LinkFilter.Init()
            self.V_LinkFilter.AddCondition("OP_NONE", False, "ToNodeNo",
                                           "EqualVal", NodeNumber)
            self.V_LinkFilter.UseFilter = True

            Window = Visum.Graphic.GetWindow()
            WWidth = Window[2] - Window[0]
            WHeight = Window[3] - Window[1]
            WXCenter = Window[0] + WWidth / 2
            WYCenter = Window[1] + WHeight / 2
            WXmin = WXCenter - (WWidth * zoom)
            WYmin = WYCenter - (WHeight * zoom)
            WXmax = WXCenter + (WWidth * zoom)
            WYmax = WYCenter + (WHeight * zoom)
            Visum.Graphic.SetWindow(WXmin, WYmin, WXmax, WYmax)
            Visum.Graphic.Screenshot(Paths["Screenshot"])

            Screenshot = QtGui.QPixmap(Paths["Screenshot"])
            Screenshot.scaled(350, 350, 0, 1)
            self.L_ImageLeft.setPixmap(Screenshot)

        except:
            self.L_GeoPos.setText("node does not exist")

    def closeEvent(self):
        os.remove(Paths["Screenshot"])
        QtGui.qApp.quit()

    def openHelp(self):
        os.startfile(Paths["Help"])
コード例 #18
0
ファイル: Declaration.py プロジェクト: sarahdi/openfisca
class Declaration(QDialog, ui_declaration.Ui_Declaration):
    def __init__(self, parent, noi):
        super(Declaration, self).__init__(parent)
        self.setupUi(self)
        self.noidec = noi
        self.parent = parent
        self.scenario = parent.scenario


        self.pages_widget = QStackedWidget()
        self.connect(self.pages_widget, SIGNAL("currentChanged(int)"), self.current_page_changed)
        self.connect(self.contents_widget, SIGNAL("currentRowChanged(int)"), self.pages_widget.setCurrentIndex)
                
        self.scrollArea.setWidget(self.pages_widget)

        self.connect(self.next_btn, SIGNAL('clicked()'), self.next_page)
        self.connect(self.prev_btn, SIGNAL('clicked()'), self.prev_page)

        self.pages = [Page01(self),  Page02(self), Page03(self), Page04(self), 
                      Page05(self), Page06(self), Page07(self), PageIsf(self)]

        for widget in self.pages:
            self.add_page(widget)


        self.set_current_index(0)
        self.current_page_changed(0)

    def current_page_changed(self, index):
        nb = self.pages_widget.count() - 1
        self.prev_btn.setEnabled(True)
        self.next_btn.setEnabled(True)
        if index == nb:
            self.next_btn.setEnabled(False)
        if index == 0:
            self.prev_btn.setEnabled(False)            

    def next_page(self):
        idx = self.pages_widget.currentIndex()
        self.set_current_index(idx + 1)

    def prev_page(self):
        idx = self.pages_widget.currentIndex()
        self.set_current_index(idx - 1)

    def get_current_index(self):
        """Return current page index"""
        return self.contents_widget.currentRow()
        
    def set_current_index(self, index):
        """Set current page index"""
        self.contents_widget.setCurrentRow(index)
        self.pages_widget.setCurrentIndex(index)

    def accept(self):
        for page in self.pages:
            for key in page.__dict__:
                widget = getattr(page,key)
                if  isinstance(widget, QSpinBox):
                    var = str(widget.objectName())
                    val = widget.value()
                    page.updateFoyer(var, val)
                elif isinstance(widget, QCheckBox):
                    var = str(widget.objectName())
                    val = 1*(widget.checkState()>=1)
                    page.updateFoyer(var, val)
        QDialog.accept(self)

    def add_page(self, widget):
        self.pages_widget.addWidget(widget)
        item = QListWidgetItem(self.contents_widget)
        item.setText(widget.get_name())
        item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
コード例 #19
0
ファイル: qmap.py プロジェクト: s-chand/qmap
class QMap():
    def __init__(self, iface):
        self.iface = iface
        self.actions = []
        self.panels= []
        self.navtoolbar = self.iface.mapNavToolToolBar()
        self.mainwindow = self.iface.mainWindow()
        self.iface.projectRead.connect(self.projectOpened)
        self.iface.initializationCompleted.connect(self.setupUI)
        self.actionGroup = QActionGroup(self.mainwindow)
        self.actionGroup.setExclusive(True)
        self.menuGroup = QActionGroup(self.mainwindow)
        self.menuGroup.setExclusive(True)
                
        self.movetool = MoveTool(self.iface.mapCanvas(), [])
        self.report = PopDownReport(self.iface.messageBar())
        
        self.dialogprovider = DialogProvider(iface.mapCanvas(), iface)
        self.dialogprovider.accepted.connect(self.clearToolRubberBand)
        self.dialogprovider.rejected.connect(self.clearToolRubberBand)
        
        self.edittool = EditTool(self.iface.mapCanvas(),[])
        self.edittool.finished.connect(self.openForm)

    @property
    def _mapLayers(self):
        return QgsMapLayerRegistry.instance().mapLayers()
        
    def clearToolRubberBand(self):
        tool = self.iface.mapCanvas().mapTool()
        try:
            tool.clearBand()
        except AttributeError:
            # No clearBand method found, but that's cool.
            pass
        
    def missingLayers(self, layers):
        def showError():
            html = ["<h1>Missing Layers</h1>", "<ul>"]
            for layer in layers:
                html.append("<li>{}</li>".format(layer))
            html.append("</ul>")
            
            self.errorreport.updateHTML("".join(html))
        
        message = "Seems like {} didn't load correctly".format(utils._pluralstring('layer', len(layers)))
        
        utils.warning("Missing layers")
        map(utils.warning, layers)
            
        self.widget = self.messageBar.createMessage("Missing Layers", 
                                                 message, 
                                                 QIcon(":/icons/sad"))
        button = QPushButton(self.widget)
        button.setCheckable(True)
        button.setChecked(self.errorreport.isVisible())
        button.setText("Show missing layers")
        button.toggled.connect(showError)
        button.toggled.connect(functools.partial(self.errorreport.setVisible))
        self.widget.destroyed.connect(self.hideReports)
        self.widget.layout().addWidget(button)
        self.messageBar.pushWidget(self.widget, QgsMessageBar.WARNING)
        
    def excepthook(self, ex_type, value, tb):
        """ 
        Custom exception hook so that we can handle errors in a
        nicer way
        """
        where = ''.join(traceback.format_tb(tb))
        msg = '{}'.format(value)
        utils.critical(msg)
        
        def showError():
            html = """
                <html>
                <body bgcolor="#FFEDED">
                <p><b>{}</b></p>
                <p align="left"><small>{}</small></p>
                </body>
                </html>
            """.format(msg, where)
            self.errorreport.updateHTML(html)
        
        self.widget = self.messageBar.createMessage("oops", "Looks like an error occurred", QIcon(":/icons/sad"))
        button = QPushButton(self.widget)
        button.setCheckable(True)
        button.setChecked(self.errorreport.isVisible())
        button.setText("Show error")
        button.toggled.connect(showError)
        button.toggled.connect(functools.partial(self.errorreport.setVisible))
        self.widget.destroyed.connect(self.hideReports)
        self.widget.layout().addWidget(button)
        self.messageBar.pushWidget(self.widget, QgsMessageBar.CRITICAL)
    
    def hideReports(self):
        self.errorreport.setVisible(False)
        self.report.setVisible(False)
    
    def setupUI(self):
        """
        Set up the main QGIS interface items.  Called after QGIS has loaded
        the plugin.
        """
        fullscreen = utils.settings["fullscreen"]
        if fullscreen:
            self.mainwindow.showFullScreen()
        else:
            self.mainwindow.showMaximized()

        self.navtoolbar.setMovable(False)
        self.navtoolbar.setAllowedAreas(Qt.TopToolBarArea)
        
        self.mainwindow.insertToolBar(self.toolbar, self.navtoolbar)
        self.openProjectAction.trigger()
            
    def setMapTool(self, tool):
        """
        Set the current mapview canvas tool

        tool -- The QgsMapTool to set
        """
        self.iface.mapCanvas().setMapTool(tool)

    def createToolBars(self):
        """
        Create all the needed toolbars
        """
        
        self.menutoolbar = QToolBar("Menu", self.mainwindow)
        self.menutoolbar.setMovable(False)
        self.menutoolbar.setAllowedAreas(Qt.LeftToolBarArea)
        self.mainwindow.addToolBar(Qt.LeftToolBarArea, self.menutoolbar)
        
        self.toolbar = QToolBar("QMap", self.mainwindow)
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.setMovable(False)

        self.editingtoolbar = FloatingToolBar("Editing", self.toolbar)
        self.extraaddtoolbar = FloatingToolBar("Extra Add Tools", self.toolbar)
        self.syncactionstoolbar = FloatingToolBar("Syncing", self.toolbar)
        self.syncactionstoolbar.setOrientation(Qt.Vertical)

    def createActions(self):
        """
        Create all the actions
        """

        self.homeAction = (QAction(QIcon(":/icons/zoomfull"),
                                  "Default View", self.mainwindow))
        self.gpsAction = (GPSAction(QIcon(":/icons/gps"), self.iface.mapCanvas(),
                                   self.mainwindow))
        self.openProjectAction = (QAction(QIcon(":/icons/open"), "Projects",
                                         self.mainwindow))
        self.openProjectAction.setCheckable(True)
        self.toggleRasterAction = (QAction(QIcon(":/icons/photo"), "Aerial Photos",
                                          self.mainwindow))
        self.syncAction = QAction(QIcon(":/icons/sync"), "Sync", self.mainwindow)
        self.syncAction.setVisible(False)
        
        self.editattributesaction = QAction(QIcon(":/icons/edit"), "Edit Attributes", self.mainwindow)
        self.editattributesaction.setCheckable(True)
        self.editattributesaction.toggled.connect(functools.partial(self.setMapTool, self.edittool))

        self.moveaction = QAction(QIcon(":/icons/move"), "Move Feature", self.mainwindow)
        self.moveaction.setCheckable(True)

        self.editingmodeaction = QAction(QIcon(":/icons/edittools"), "Editing Tools", self.mainwindow)
        self.editingmodeaction.setCheckable(True)

        self.addatgpsaction = QAction(QIcon(":/icons/gpsadd"), "Add at GPS", self.mainwindow)
        
        self.edittool.layersupdated.connect(self.editattributesaction.setVisible)
        self.movetool.layersupdated.connect(self.moveaction.setVisible)
        self.edittool.layersupdated.connect(self.updateEditTools)
        self.movetool.layersupdated.connect(self.updateEditTools)
        
    def updateEditTools(self, *args):
        """
            Show or hide the Editing Tools button based on the sub tools.
        """
        if self.edittool.layers and self.movetool.layers:  
            self.editingmodeaction.setVisible(True)
        else:
            self.editingmodeaction.setVisible(False)

    def initGui(self):
        """
        Create all the icons and setup the tool bars.  Called by QGIS when
        loading. This is called before setupUI.
        """
        QApplication.setWindowIcon(QIcon(":/branding/logo"))
        self.mainwindow.findChildren(QMenuBar)[0].setVisible(False)
        self.mainwindow.setContextMenuPolicy(Qt.PreventContextMenu)
        self.mainwindow.setWindowTitle("IntraMaps Roam: Mobile Data Collection")
        
        # Disable QGIS logging window popups. We do our own logging
        QgsMessageLog.instance().messageReceived.disconnect()
        
        s = """
        QToolButton { 
            padding: 6px;
            color: #4f4f4f;
         }
        
        QToolButton:hover { 
            padding: 6px;
            background-color: rgb(211, 228, 255);
         }
         
        QToolBar {
         background: white;
        }
        
        QCheckBox::indicator {
             width: 40px;
             height: 40px;
         }
        
        QLabel {
            color: #4f4f4f;
        }
        
        QDialog { background-color: rgb(255, 255, 255); }
        
        QPushButton { 
            border: 1px solid #e1e1e1;
             padding: 6px;
            color: #4f4f4f;
         }
        
        QPushButton:hover { 
            border: 1px solid #e1e1e1;
             padding: 6px;
            background-color: rgb(211, 228, 255);
         }
        
        QCheckBox {
            color: #4f4f4f;
        }
        
        QComboBox::drop-down {
            width: 30px;
        }


        """
        self.mainwindow.setStyleSheet(s)
        
        mainwidget = self.mainwindow.centralWidget()
        mainwidget.setLayout(QGridLayout())
        mainwidget.layout().setContentsMargins(0,0,0,0)
        
        newlayout = QGridLayout()
        newlayout.setContentsMargins(0,0,0,0)
        newlayout.addWidget(self.iface.mapCanvas(), 0,0,2,1)
        newlayout.addWidget(self.iface.messageBar(), 0,0,1,1)
        
        wid = QWidget()
        wid.setLayout(newlayout)
        
        self.stack = QStackedWidget()
        self.messageBar = QgsMessageBar(wid)
        self.messageBar.setSizePolicy( QSizePolicy.Minimum, QSizePolicy.Fixed )
        self.errorreport = PopDownReport(self.messageBar)
         
        mainwidget.layout().addWidget(self.stack, 0,0,2,1)
        mainwidget.layout().addWidget(self.messageBar, 0,0,1,1)
        
        self.helppage = HelpPage()
        helppath = os.path.join(os.path.dirname(__file__) , 'help',"help.html")
        self.helppage.setHelpPage(helppath)
        
        self.projectwidget = ProjectsWidget()   
        self.projectwidget.requestOpenProject.connect(self.loadProject)
        self.stack.addWidget(wid)
        self.stack.addWidget(self.projectwidget)
        self.stack.addWidget(self.helppage)
                
        sys.excepthook = self.excepthook

        def createSpacer(width=30):
            widget = QWidget()
            widget.setMinimumWidth(width)
            return widget

        self.createToolBars()
        self.createActions()

        spacewidget = createSpacer(60)
        gpsspacewidget = createSpacer()
        gpsspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.moveaction.toggled.connect(functools.partial(self.setMapTool, self.movetool))
        showediting = (functools.partial(self.editingtoolbar.showToolbar, 
                                         self.editingmodeaction,
                                         self.editattributesaction))
        self.editingmodeaction.toggled.connect(showediting)

        self.addatgpsaction.triggered.connect(self.addAtGPS)
        self.addatgpsaction.setEnabled(self.gpsAction.isConnected)
        self.gpsAction.gpsfixed.connect(self.addatgpsaction.setEnabled)

        self.editingtoolbar.addToActionGroup(self.editattributesaction)
        self.editingtoolbar.addToActionGroup(self.moveaction)

        self.actionGroup.addAction(self.editingmodeaction)

        self.homeAction.triggered.connect(self.zoomToDefaultView)
        
        self.openProjectAction.triggered.connect(self.showOpenProjectDialog)
        self.openProjectAction.triggered.connect(functools.partial(self.stack.setCurrentIndex, 1))
        
        self.toggleRasterAction.triggered.connect(self.toggleRasterLayers)

        self.navtoolbar.insertAction(self.iface.actionZoomIn(), self.iface.actionTouch())
        self.navtoolbar.insertAction(self.iface.actionTouch(), self.homeAction)
        self.navtoolbar.insertAction(self.iface.actionTouch(), self.iface.actionZoomFullExtent())
        self.navtoolbar.insertAction(self.homeAction, self.iface.actionZoomFullExtent())

        self.navtoolbar.addAction(self.toggleRasterAction)
        self.navtoolbar.insertWidget(self.iface.actionZoomFullExtent(), spacewidget)
        self.toolbar.addAction(self.editingmodeaction)
        self.toolbar.addAction(self.syncAction)
        self.toolbar.addAction(self.gpsAction)
        self.toolbar.insertWidget(self.syncAction, gpsspacewidget)
        self.toolbar.insertSeparator(self.gpsAction)

        self.extraaddtoolbar.addAction(self.addatgpsaction)

        self.editingtoolbar.addAction(self.editattributesaction)
        self.editingtoolbar.addAction(self.moveaction)
        
        self.mapview = QAction(QIcon(":/icons/map"), "Map", self.menutoolbar)
        self.mapview.setCheckable(True)
        self.mapview.triggered.connect(functools.partial(self.stack.setCurrentIndex, 0))
        
        self.help = QAction(QIcon(":/icons/help"), "Help", self.menutoolbar)
        self.help.setCheckable(True)
        self.help.triggered.connect(functools.partial(self.stack.setCurrentIndex, 2))
        self.help.setVisible(False)
        
        self.userlabel = QLabel("Current User <br> {user}".format(user=getpass.getuser()))
        self.userlabel.setAlignment(Qt.AlignCenter)
        self.userlabel.setStyleSheet("""
            QLabel {
                    color: #8c8c8c;
                    font: 10px "Calibri" ;
                    }""")
        
        self.quit = QAction(QIcon(":/icons/quit"), "Quit", self.menutoolbar)
        self.quit.triggered.connect(self.iface.actionExit().trigger)

        self.menuGroup.addAction(self.mapview)
        self.menuGroup.addAction(self.openProjectAction)
        self.menuGroup.addAction(self.help)
        
        self.menutoolbar.addAction(self.mapview)
        self.menutoolbar.addAction(self.openProjectAction)
        self.menutoolbar.addAction(self.help)
        self.menutoolbar.addAction(self.quit)
        
        quitspacewidget = createSpacer()
        quitspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        labelaction = self.menutoolbar.insertWidget(self.quit, self.userlabel)
        self.menutoolbar.insertWidget(labelaction, quitspacewidget)
        
        self.setupIcons()
        self.stack.currentChanged.connect(self.updateUIState)
        
    def updateUIState(self, page):
        """
        Update the UI state to reflect the currently selected
        page in the stacked widget
        """
        def setToolbarsActive(enabled):
            toolbars = self.mainwindow.findChildren(QToolBar)
            for toolbar in toolbars:
                if toolbar == self.menutoolbar:
                    continue
                toolbar.setEnabled(enabled)
        
        def setPanelsVisible(visible):
            for panel in self.panels:
                panel.setVisible(visible)
                
        ismapview = page == 0
        setToolbarsActive(ismapview)
        setPanelsVisible(ismapview)

    def addAtGPS(self):
        """
        Add a record at the current GPS location.
        """
        action = self.actionGroup.checkedAction()
        if not action:
            return
        layer = action.data()
        if not layer:
            return
        
        point = self.gpsAction.position
        self.addNewFeature(layer=layer, geometry=point)
        
    def zoomToDefaultView(self):
        """
        Zoom the mapview canvas to the extents the project was opened at i.e. the
        default extent.
        """
        self.iface.mapCanvas().setExtent(self.defaultextent)
        self.iface.mapCanvas().refresh()

    def toggleRasterLayers(self):
        """
        Toggle all raster layers on or off.
        """
        legend = self.iface.legendInterface()
        #Freeze the canvas to save on UI refresh
        self.iface.mapCanvas().freeze()
        for layer in self._mapLayers.values():
            if layer.type() == QgsMapLayer.RasterLayer:
                isvisible = legend.isLayerVisible(layer)
                legend.setLayerVisible(layer, not isvisible)
        self.iface.mapCanvas().freeze(False)
        self.iface.mapCanvas().refresh()

    def setupIcons(self):
        """
        Update toolbars to have text and icons, change normal QGIS
        icons to new style
        """
        toolbars = self.mainwindow.findChildren(QToolBar)
        for toolbar in toolbars:
            toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
            toolbar.setIconSize(QSize(32, 32))

        self.iface.actionTouch().setIconText("Pan")
        self.iface.actionTouch().setIcon(QIcon(":/icons/pan"))
        self.iface.actionZoomIn().setIcon(QIcon(":/icons/in"))
        self.iface.actionZoomOut().setIcon(QIcon(":/icons/out"))
        self.iface.actionPan().setIcon(QIcon(":/icons/pan"))
        self.iface.actionZoomFullExtent().setIcon(QIcon(":/icons/home"))
        self.iface.actionZoomFullExtent().setIconText("Home View")

        self.actionGroup.addAction(self.iface.actionZoomIn())
        self.actionGroup.addAction(self.iface.actionZoomOut())
        self.actionGroup.addAction(self.iface.actionTouch())

    def projectOpened(self):
        """
            Called when a new project is opened in QGIS.
        """
        for panel in self.panels:
            self.mainwindow.removeDockWidget(panel)
            del panel

        projectpath = QgsProject.instance().fileName()
        project = QMapProject(os.path.dirname(projectpath), self.iface)
        self.createFormButtons(projectlayers = project.getConfiguredLayers())
        
        # Enable the raster layers button only if the project contains a raster layer.
        hasrasters = any(layer.type() for layer in self._mapLayers.values())
        self.toggleRasterAction.setEnabled(hasrasters)
        self.defaultextent = self.iface.mapCanvas().extent()
        self.connectSyncProviders(project)
        
        # Show panels
        self.panels = list(project.getPanels())
        for panel in self.panels:
            self.mainwindow.addDockWidget(Qt.BottomDockWidgetArea , panel)
            
        self.iface.messageBar().popWidget()
        
    def createFormButtons(self, projectlayers):
        """
            Create buttons for each form that is definded
        """
        # Remove all the old buttons
        for action in self.actions:
            self.actionGroup.removeAction(action)
            self.toolbar.removeAction(action)
                
        self.edittool.layers = []
        self.movetool.layers = []
        for layer in projectlayers:
            try:
                qgslayer = QgsMapLayerRegistry.instance().mapLayersByName(layer.name)[0]
                if qgslayer.type() == QgsMapLayer.RasterLayer:
                    utils.log("We can't support raster layers for data entry")
                    continue
                       
                layer.QGISLayer = qgslayer
            except KeyError:
                utils.log("Layer not found in project")
                continue
            
            if 'capture' in layer.capabilities:
                text = layer.icontext
                try:
                    tool = layer.getMaptool(self.iface.mapCanvas())
                except NoMapToolConfigured:
                    utils.log("No map tool configured")
                    continue
                except ErrorInMapTool as error:
                    self.messageBar.pushMessage("Error configuring map tool", error.message, level=QgsMessageBar.WARNING)
                    continue
                    
                # Hack until I fix it later
                if isinstance(tool, PointTool):
                    add = functools.partial(self.addNewFeature, qgslayer)
                    tool.geometryComplete.connect(add)
                else:
                    tool.finished.connect(self.openForm)
         
                action = QAction(QIcon(layer.icon), text, self.mainwindow)
                action.setData(layer)
                action.setCheckable(True)
                action.toggled.connect(functools.partial(self.setMapTool, tool))
                
                self.toolbar.insertAction(self.editingmodeaction, action)
                
                if not tool.isEditTool():
                    # Connect the GPS tools strip to the action pressed event.                
                    showgpstools = (functools.partial(self.extraaddtoolbar.showToolbar, 
                                                 action,
                                                 None))
                    
                    action.toggled.connect(showgpstools)
                    
                self.actionGroup.addAction(action)
                self.actions.append(action)
            
            if 'edit' in layer.capabilities:
                # TODO Use snapping options from project
                radius = (QgsTolerance.toleranceInMapUnits( 10, qgslayer,
                                                            self.iface.mapCanvas().mapRenderer(), 
                                                            QgsTolerance.Pixels))
                self.edittool.addLayer(qgslayer)
                self.edittool.searchRadius = radius
                
            if 'move' in layer.capabilities:
                self.movetool.addLayer(qgslayer)
            
    def openForm(self, layer, feature):
        if not layer.isEditable():
            layer.startEditing()
            
        self.dialogprovider.openDialog(feature=feature, layer=layer)
            
    def addNewFeature(self, layer, geometry):
        fields = layer.pendingFields()
        
        if not layer.isEditable():
            layer.startEditing()
    
        feature = QgsFeature()
        feature.setGeometry( geometry )
        feature.initAttributes(fields.count())
        feature.setFields(fields)
        
        for indx in xrange(fields.count()):
            feature[indx] = layer.dataProvider().defaultValue(indx)

        self.dialogprovider.openDialog(feature=feature, layer=layer)

    def showOpenProjectDialog(self):
        """
        Show the project selection dialog.
        """
        self.stack.setCurrentIndex(1)
        path = os.path.join(os.path.dirname(__file__), '..' , 'projects/')
        projects = getProjects(path, self.iface)
        self.projectwidget.loadProjectList(projects)
        
    def loadProject(self, project):
        """
        Load a project into QGIS.
        """
        utils.log(project)
        utils.log(project.name)
        utils.log(project.projectfile)
        utils.log(project.vaild)
        
        (passed, message) = project.onProjectLoad()
        
        if not passed:
            QMessageBox.warning(self.mainwindow, "Project Load Rejected", 
                                "Project couldn't be loaded because {}".format(message))
            return
        
        self.mapview.trigger()
        self.iface.newProject(False)        
        self.iface.mapCanvas().freeze()
        fileinfo = QFileInfo(project.projectfile)
        self.badLayerHandler = BadLayerHandler(callback=self.missingLayers)
        QgsProject.instance().setBadLayerHandler( self.badLayerHandler )
        
        self.iface.messageBar().pushMessage("Project Loading","", QgsMessageBar.INFO)
        QgsProject.instance().read(fileinfo)
        
        self.iface.mapCanvas().updateScale()
        self.iface.mapCanvas().freeze(False)
        self.iface.mapCanvas().refresh()
        self.mainwindow.setWindowTitle("IntraMaps Roam: Mobile Data Collection")
        self.iface.projectRead.emit()
        
    def unload(self):
        del self.toolbar
        
    def connectSyncProviders(self, project):
        self.syncactionstoolbar.clear()
        
        syncactions = list(project.getSyncProviders())
        
        # Don't show the sync button if there is no sync providers
        if not syncactions:
            self.syncAction.setVisible(False)
            return
        
        self.syncAction.setVisible(True)
        
        for provider in syncactions:
            action = QAction(QIcon(":/icons/sync"), "Sync {}".format(provider.name), self.mainwindow)
            action.triggered.connect(functools.partial(self.syncProvider, provider))
            self.syncactionstoolbar.addAction(action)
        
        try:
            self.syncAction.toggled.disconnect()
        except TypeError:
            pass
        try:
            self.syncAction.triggered.disconnect()
        except TypeError:
            pass
        
        if len(syncactions) == 1:
            # If one provider is set then we just connect the main button.    
            self.syncAction.setCheckable(False)
            self.syncAction.setText("Sync")
            self.syncAction.triggered.connect(functools.partial(self.syncProvider, syncactions[0]))
        else:
            # the sync button because a sync menu
            self.syncAction.setCheckable(True)
            self.syncAction.setText("Sync Menu")
            showsyncoptions = (functools.partial(self.syncactionstoolbar.showToolbar, 
                                                 self.syncAction, None))
            self.syncAction.toggled.connect(showsyncoptions)

    def syncstarted(self):                   
        # Remove the old widget if it's still there.
        # I don't really like this. Seems hacky.
        try:
            self.iface.messageBar().popWidget(self.syncwidget)
        except RuntimeError:
            pass
        except AttributeError:
            pass
        
        self.iface.messageBar().findChildren(QToolButton)[0].setVisible(False)        
        self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync in progress", QIcon(":/icons/syncing"))
        button = QPushButton(self.syncwidget)
        button.setCheckable(True)
        button.setText("Status")
        button.setIcon(QIcon(":/icons/syncinfo"))
        button.toggled.connect(functools.partial(self.report.setVisible))
        pro = QProgressBar()
        pro.setMaximum(0)
        pro.setMinimum(0)
        self.syncwidget.layout().addWidget(pro)
        self.syncwidget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.syncwidget, QgsMessageBar.INFO)
        
    def synccomplete(self):
        try:
            self.iface.messageBar().popWidget(self.syncwidget)
        except RuntimeError:
            pass
        
        stylesheet = ("QgsMessageBar { background-color: rgba(239, 255, 233); border: 0px solid #b9cfe4; } "
                     "QLabel,QTextEdit { color: #057f35; } ")
        
        closebutton = self.iface.messageBar().findChildren(QToolButton)[0]
        closebutton.setVisible(True)
        closebutton.clicked.connect(functools.partial(self.report.setVisible, False))
        self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Complete", QIcon(":/icons/syncdone"))
        button = QPushButton(self.syncwidget)
        button.setCheckable(True)
        button.setChecked(self.report.isVisible())
        button.setText("Sync Report")
        button.setIcon(QIcon(":/icons/syncinfo"))
        button.toggled.connect(functools.partial(self.report.setVisible))      
        pro = QProgressBar()
        pro.setMaximum(100)
        pro.setValue(100)
        self.syncwidget.layout().addWidget(pro)      
        self.syncwidget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.syncwidget)
        self.iface.messageBar().setStyleSheet(stylesheet)
        self.iface.mapCanvas().refresh()
        
    def syncerror(self):
        try:
            self.iface.messageBar().popWidget(self.syncwidget)
        except RuntimeError:
            pass
        
        closebutton = self.iface.messageBar().findChildren(QToolButton)[0]
        closebutton.setVisible(True)
        closebutton.clicked.connect(functools.partial(self.report.setVisible, False))
        self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Error", QIcon(":/icons/syncfail"))
        button = QPushButton(self.syncwidget)
        button.setCheckable(True)
        button.setChecked(self.report.isVisible())
        button.setText("Sync Report")
        button.setIcon(QIcon(":/icons/syncinfo"))
        button.toggled.connect(functools.partial(self.report.setVisible))            
        self.syncwidget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.syncwidget, QgsMessageBar.CRITICAL)
        self.iface.mapCanvas().refresh()
        
    def syncProvider(self, provider):
        self.syncAction.toggle()
        provider.syncStarted.connect(functools.partial(self.syncAction.setEnabled, False))
        provider.syncStarted.connect(self.syncstarted)
        
        provider.syncComplete.connect(self.synccomplete)
        provider.syncComplete.connect(functools.partial(self.syncAction.setEnabled, True))
        provider.syncComplete.connect(functools.partial(self.report.updateHTML))
        
        provider.syncMessage.connect(self.report.updateHTML)
        
        provider.syncError.connect(self.report.updateHTML)
        provider.syncError.connect(self.syncerror)
        provider.syncComplete.connect(functools.partial(self.syncAction.setEnabled, True))
        
        provider.startSync()
コード例 #20
0
ファイル: qChatTab.py プロジェクト: GageAmes/Cryptully
class QChatTab(QWidget):
    def __init__(self, chatWindow, nick):
        QWidget.__init__(self)

        self.chatWindow = chatWindow
        self.nick = nick
        self.unreadCount = 0

        self.widgetStack = QStackedWidget(self)
        self.widgetStack.addWidget(QNickInputWidget('new_chat.png', 150, self.connectClicked, parent=self))
        self.widgetStack.addWidget(QConnectingWidget(self))
        self.widgetStack.addWidget(QChatWidget(self.chatWindow.connectionManager, self))

        # Skip the chat layout if the nick was given denoting an incoming connection
        if self.nick is None or self.nick == '':
            self.widgetStack.setCurrentIndex(0)
        else:
            self.widgetStack.setCurrentIndex(2)

        layout = QHBoxLayout()
        layout.addWidget(self.widgetStack)
        self.setLayout(layout)


    def connectClicked(self, nick):
        # Check that the nick isn't already connected
        if self.chatWindow.isNickInTabs(nick):
            QMessageBox.warning(self, errors.TITLE_ALREADY_CONNECTED, errors.ALREADY_CONNECTED % (nick))
            return

        self.nick = nick
        self.widgetStack.widget(1).setConnectingToNick(self.nick)
        self.widgetStack.setCurrentIndex(1)
        self.chatWindow.connectionManager.openChat(self.nick)


    def showNowChattingMessage(self):
        self.widgetStack.setCurrentIndex(2)
        self.widgetStack.widget(2).showNowChattingMessage(self.nick)


    def appendMessage(self, message, source):
        self.widgetStack.widget(2).appendMessage(message, source)


    def resetOrDisable(self):
        # If the connecting widget is showing, reset to the nick input widget
        # If the chat widget is showing, disable it to prevent sending of more messages
        curWidgetIndex = self.widgetStack.currentIndex()
        if curWidgetIndex == 1:
            self.widgetStack.setCurrentIndex(0)
        elif curWidgetIndex == 2:
            self.widgetStack.widget(2).disable()


    def enable(self):
        self.widgetStack.setCurrentIndex(2)
        self.widgetStack.widget(2).enable()
コード例 #21
0
class AnalysisWindow(QMainWindow):
    def __init__(self, parent, controller):
        # create window
        QMainWindow.__init__(self)

        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Tracking Analysis")
        self.setGeometry(100, 200, 10, 10)

        # set controller
        self.controller = controller

        # create main widget & layout
        self.main_widget = QWidget(self)
        self.main_widget.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
        self.main_layout = QGridLayout(self.main_widget)

        # create left widget & layout
        self.left_widget = QWidget(self)
        self.main_layout.addWidget(self.left_widget, 0, 0)

        self.left_layout = QVBoxLayout(self.left_widget)
        self.left_layout.setAlignment(Qt.AlignTop)

        # create list of tracking items
        self.tracking_list_items = []
        self.tracking_list = QListWidget(self)
        self.tracking_list.currentRowChanged.connect(self.controller.switch_tracking_file)
        self.left_layout.addWidget(self.tracking_list)

        # create tracking list buttons
        self.tracking_list_buttons = QHBoxLayout(self)
        self.left_layout.addLayout(self.tracking_list_buttons)

        self.add_tracking_button = QPushButton('+')
        self.add_tracking_button.clicked.connect(self.controller.select_and_open_tracking_files)
        self.add_tracking_button.setToolTip("Add tracking file.")
        self.tracking_list_buttons.addWidget(self.add_tracking_button)

        self.remove_tracking_button = QPushButton('-')
        self.remove_tracking_button.clicked.connect(self.controller.remove_tracking_file)
        self.remove_tracking_button.setToolTip("Remove selected tracking file.")
        self.tracking_list_buttons.addWidget(self.remove_tracking_button)

        self.prev_tracking_button = QPushButton('<')
        self.prev_tracking_button.clicked.connect(self.controller.prev_tracking_file)
        self.prev_tracking_button.setToolTip("Switch to previous tracking file.")
        self.tracking_list_buttons.addWidget(self.prev_tracking_button)

        self.next_tracking_button = QPushButton('>')
        self.next_tracking_button.clicked.connect(self.controller.next_tracking_file)
        self.next_tracking_button.setToolTip("Switch to next tracking file.")
        self.tracking_list_buttons.addWidget(self.next_tracking_button)

        # create right widget & layout
        self.right_widget = QWidget(self)
        self.right_widget.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
        self.main_layout.addWidget(self.right_widget, 0, 1)
        
        self.right_layout = QVBoxLayout(self.right_widget)
        self.right_layout.setAlignment(Qt.AlignTop)
        self.right_layout.setSpacing(5)

        # create button layout for main widget
        plot_horiz_layout = QHBoxLayout()
        self.right_layout.addLayout(plot_horiz_layout)

        # add param labels & textboxes
        plot_type_label = QLabel()
        plot_type_label.setText("Plot:")
        plot_horiz_layout.addWidget(plot_type_label)
        plot_horiz_layout.addStretch(1)

        # create tab widget for plot type
        self.plot_tabs_widget = QTabBar()
        self.plot_tabs_widget.setDrawBase(False)
        self.plot_tabs_widget.setExpanding(False)
        self.plot_tabs_widget.currentChanged.connect(self.controller.change_plot_type)
        plot_horiz_layout.addWidget(self.plot_tabs_widget)

        # create button layout for main widget
        crop_horiz_layout = QHBoxLayout()
        self.right_layout.addLayout(crop_horiz_layout)

        # add param labels & textboxes
        crop_type_label = QLabel()
        crop_type_label.setText("Crop #:")
        crop_horiz_layout.addWidget(crop_type_label)
        crop_horiz_layout.addStretch(1)

        # create tab widget for crop number
        self.crop_tabs_widget = QTabBar()
        self.crop_tabs_widget.setDrawBase(False)
        self.crop_tabs_widget.setExpanding(False)
        self.crop_tabs_widget.currentChanged.connect(self.controller.change_crop)
        crop_horiz_layout.addWidget(self.crop_tabs_widget)

        # create button layout for main widget
        button_layout = QHBoxLayout()
        button_layout.addStretch(1)
        self.right_layout.addLayout(button_layout)

        # add buttons
        self.show_tracking_params_button = QPushButton('Tracking Parameters', self)
        self.show_tracking_params_button.setMinimumHeight(30)
        self.show_tracking_params_button.clicked.connect(self.controller.show_tracking_params)
        button_layout.addWidget(self.show_tracking_params_button)

        # create stacked widget & layout
        self.stacked_widget = QStackedWidget(self)
        self.stacked_widget.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
        self.right_layout.addWidget(self.stacked_widget)

        self.create_tail_tracking_widget(self.stacked_widget)
        self.create_body_tracking_widget(self.stacked_widget)

        # self.right_layout = QVBoxLayout(self.right_widget)
        # self.right_layout.setAlignment(Qt.AlignTop)
        # self.right_layout.setSpacing(5)

        # self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        # set window titlebar buttons
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint)

        self.show()

    def update_plot(self, array, plot_type, extra_tracking=None, keep_xlim=True):
        print("Updating plot")

        if plot_type == "tail":
            self.stacked_widget.setCurrentIndex(0)
            self.plot_window.plot_tail_angle_array(array, extra_tracking=extra_tracking, keep_xlim=keep_xlim)
        elif plot_type == "body":
            self.stacked_widget.setCurrentIndex(1)
            self.plot_window.plot_heading_angle_array(array, keep_xlim=keep_xlim)
        else:
            pass

    def switch_tracking_item(self, row_number):
        print("Switching tracking item")

        tracking_params = self.controller.tracking_params[row_number]

        self.change_selected_tracking_row(row_number)

        self.plot_tabs_widget.blockSignals(True)

        # add plot tabs
        for i in range(self.plot_tabs_widget.count()-1, -1, -1):
            self.plot_tabs_widget.removeTab(i)

        if tracking_params['type'] == "freeswimming":
            if tracking_params['track_tail']:
                self.plot_tabs_widget.addTab("Tail")

            self.plot_tabs_widget.addTab("Body")

            if tracking_params['track_eyes']:
                self.plot_tabs_widget.addTab("Eyes")
        else:
            self.plot_tabs_widget.addTab("Tail")

        self.plot_tabs_widget.blockSignals(False)

        self.crop_tabs_widget.blockSignals(True)
        for i in range(self.crop_tabs_widget.count()-1, -1, -1):
            self.crop_tabs_widget.removeTab(i)

        # add crop tabs
        n_crops = len(tracking_params['crop_params'])

        for i in range(n_crops):
            self.crop_tabs_widget.addTab("{}".format(i+1))
        self.crop_tabs_widget.blockSignals(False)

    def add_tracking_item(self, item_name):
        print("Adding tracking item")
        self.tracking_list_items.append(QListWidgetItem(item_name, self.tracking_list))

        # self.update_plot()

    def change_selected_tracking_row(self, row_number):
        self.tracking_list.blockSignals(True)
        self.tracking_list.setCurrentRow(row_number)
        self.tracking_list.blockSignals(False)

    def create_tail_tracking_widget(self, parent_widget):
        # create tail tab widget & layout
        tail_tab_widget = QWidget()
        tail_tab_layout = QVBoxLayout(tail_tab_widget)

        # create button layout for tail tab
        bottom_tail_button_layout = QVBoxLayout()
        # bottom_tail_button_layout.setSpacing(5)
        bottom_tail_button_layout.addStretch(1)
        tail_tab_layout.addLayout(bottom_tail_button_layout)

        # add buttons
        track_bouts_button = QPushButton('Track Bouts', self)
        track_bouts_button.setMinimumHeight(30)
        track_bouts_button.setMaximumWidth(100)
        track_bouts_button.clicked.connect(lambda:self.controller.track_bouts())
        bottom_tail_button_layout.addWidget(track_bouts_button)

        track_freqs_button = QPushButton('Track Freq', self)
        track_freqs_button.setMinimumHeight(30)
        track_freqs_button.setMaximumWidth(100)
        track_freqs_button.clicked.connect(lambda:self.controller.track_freqs())
        bottom_tail_button_layout.addWidget(track_freqs_button)

        # add checkbox for switching plots
        self.smoothed_deriv_checkbox = QCheckBox("Show smoothed derivative")
        self.smoothed_deriv_checkbox.toggled.connect(lambda:self.show_smoothed_deriv(self.smoothed_deriv_checkbox))
        bottom_tail_button_layout.addWidget(self.smoothed_deriv_checkbox)

        # add param labels & textboxes
        smoothing_window_label = QLabel()
        smoothing_window_label.setText("Smoothing window:")
        bottom_tail_button_layout.addWidget(smoothing_window_label)

        self.smoothing_window_param_box = QLineEdit(self)
        self.smoothing_window_param_box.setMinimumHeight(20)
        self.smoothing_window_param_box.setMaximumWidth(40)
        self.smoothing_window_param_box.setText(str(self.controller.smoothing_window_width))
        bottom_tail_button_layout.addWidget(self.smoothing_window_param_box)

        threshold_label = QLabel()
        threshold_label.setText("Threshold:")
        bottom_tail_button_layout.addWidget(threshold_label)

        self.threshold_param_box = QLineEdit(self)
        self.threshold_param_box.setMinimumHeight(20)
        self.threshold_param_box.setMaximumWidth(40)
        self.threshold_param_box.setText(str(self.controller.threshold))
        bottom_tail_button_layout.addWidget(self.threshold_param_box)

        min_width_label = QLabel()
        min_width_label.setText("Min width:")
        bottom_tail_button_layout.addWidget(min_width_label)

        self.min_width_param_box = QLineEdit(self)
        self.min_width_param_box.setMinimumHeight(20)
        self.min_width_param_box.setMaximumWidth(40)
        self.min_width_param_box.setText(str(self.controller.min_width))
        bottom_tail_button_layout.addWidget(self.min_width_param_box)

        parent_widget.addWidget(tail_tab_widget)

    def create_body_tracking_widget(self, parent_widget):
        # create head tab widget & layout
        head_tab_widget = QWidget()
        head_tab_layout = QVBoxLayout(head_tab_widget)

        # create button layout for head tab
        bottom_head_button_layout = QHBoxLayout()
        head_tab_layout.addLayout(bottom_head_button_layout)

        # add buttons
        track_position_button = QPushButton('Track Pos', self)
        track_position_button.setMinimumHeight(30)
        track_position_button.setMaximumWidth(100)
        track_position_button.clicked.connect(lambda:self.track_position())
        bottom_head_button_layout.addWidget(track_position_button)

        # add checkbox for switching plots
        speed_checkbox = QCheckBox("Show speed")
        speed_checkbox.toggled.connect(lambda:self.show_speed(self.speed_checkbox))
        bottom_head_button_layout.addWidget(speed_checkbox)

        parent_widget.addWidget(head_tab_widget)

    def create_crops(self, parent_layout):
        crop_tabs_widget = QTabWidget()
        crop_tabs_widget.currentChanged.connect(self.change_crop)
        crop_tabs_widget.setElideMode(Qt.ElideLeft)
        crop_tabs_layout = QVBoxLayout(crop_tabs_widget)
        parent_layout.addWidget(crop_tabs_widget)

        self.crop_tabs_widgets.append(crop_tabs_widget)
        self.crop_tabs_layouts.append(crop_tabs_layout)

        n_crops = len(self.controller.tracking_params[self.controller.curr_tracking_num]['crop_params'])

        for k in range(n_crops):
            self.create_crop()

    def clear_crops(self):
        self.crop_tab_layouts  = [[]]
        self.crop_tab_widgets  = [[]]
        self.plot_tab_layouts  = [{'tail': [],
                                  'eyes': [],
                                  'body': []}]
        self.plot_tab_widgets  = [{'tail': [],
                                  'eyes': [],
                                  'body': []}]
        self.plot_tabs_widgets = [[]]
        self.plot_tabs_layouts = [[]]

        self.head_angle_arrays = []
        self.tail_angle_arrays = []

        for c in range(self.n_crops-1, -1, -1):
            # remove tab
            self.crop_tabs_widget.removeTab(c)

        self.n_crops = 0
        self.current_crop = -1

    def show_smoothed_deriv(self, checkbox):
        if self.smoothed_abs_deriv_abs_angle_array != None:
            if checkbox.isChecked():
                self.tail_canvas.plot_tail_angle_array(self.smoothed_abs_deriv_abs_angle_array, self.bouts, keep_limits=True)
            else:
                self.tail_canvas.plot_tail_angle_array(self.tail_end_angle_array[self.current_crop], self.bouts, self.peak_maxes_y, self.peak_maxes_x, self.peak_mins_y, self.peak_mins_x, self.freqs, keep_limits=True)

    def show_speed(self, checkbox):
        if self.speed_array != None:
            if checkbox.isChecked():
                self.head_canvas.plot_head_array(self.speed_array, keep_limits=True)
            else:
                self.head_canvas.plot_head_array(self.head_angle_array, keep_limits=True)

    def load_data(self, data_path=None):
        if data_path == None:
            # ask the user to select a directory
            self.path = str(QFileDialog.getExistingDirectory(self, 'Open folder'))
        else:
            self.path = data_path

        # load saved tracking data
        (self.tail_coords_array, self.spline_coords_array,
         self.heading_angle_array, self.body_position_array,
         self.eye_coords_array, self.params) = an.open_saved_data(self.path)

        if self.params != None:
            # calculate tail angles
            if self.params['type'] == "freeswimming" and self.params['track_tail']:
                self.tail_angle_array = an.get_freeswimming_tail_angles(self.tail_coords_array, self.heading_angle_array, self.body_position_array)
            elif self.params['type'] == "headfixed":
                self.tail_angle_array = an.get_headfixed_tail_angles(self.tail_coords_array, self.params['tail_direction'])

            # get array of average angle of the last few points of the tail
            # self.tail_end_angle_array = np.mean(self.tail_angle_array[:, :, -3:], axis=-1)
            # self.tail_end_angle_array = self.tail_angle_array[:, :, -1]
            self.tail_end_angle_array = an.get_tail_end_angles(self.tail_angle_array, num_to_average=3)
            
            # clear crops
            self.clear_crops()

            # get number of saved crops
            n_crops_total = len(self.params['crop_params'])

            for k in range(n_crops_total):
                # create a crop
                self.create_crop()

                # plot heading angle
                if self.heading_angle_array is not None:
                    self.plot_canvases[k].plot_heading_angle_array(self.heading_angle_array[k])

                # plot tail angle
                if self.tail_angle_array is not None:
                    self.tail_canvases[k].plot_tail_angle_array(self.tail_end_angle_array[k])

    # def track_bouts(self):
    #     if self.tail_angle_array != None:
    #         # get params
    #         self.smoothing_window_width = int(self.smoothing_window_param_box.text())
    #         self.threshold = float(self.threshold_param_box.text())
    #         self.min_width = int(self.min_width_param_box.text())

    #         # get smoothed derivative
    #         abs_angle_array = np.abs(self.tail_end_angle_array[self.current_crop])
    #         deriv_abs_angle_array = np.gradient(abs_angle_array)
    #         abs_deriv_abs_angle_array = np.abs(deriv_abs_angle_array)
    #         normpdf = scipy.stats.norm.pdf(range(-int(self.smoothing_window_width/2),int(self.smoothing_window_width/2)),0,3)
    #         self.smoothed_abs_deriv_abs_angle_array =  np.convolve(abs_deriv_abs_angle_array,  normpdf/np.sum(normpdf),mode='valid')

    #         # calculate bout periods
    #         self.bouts = an.contiguous_regions(self.smoothed_abs_deriv_abs_angle_array > self.threshold)

    #         # remove bouts that don't have the minimum bout length
    #         for i in range(self.bouts.shape[0]-1, -1, -1):
    #             if self.bouts[i, 1] - self.bouts[i, 0] < self.min_width:
    #                 self.bouts = np.delete(self.bouts, (i), 0)

    #         # update plot
    #         self.smoothed_deriv_checkbox.setChecked(False)
    #         self.tail_canvas.plot_tail_angle_array(self.tail_end_angle_array[self.current_crop], self.bouts, keep_limits=True)

    # def track_freqs(self):
    #     if self.bouts != None:
    #         # initiate bout maxima & minima coord lists
    #         self.peak_maxes_y = []
    #         self.peak_maxes_x = []
    #         self.peak_mins_y = []
    #         self.peak_mins_x = []

    #         # initiate instantaneous frequency array
    #         self.freqs = np.zeros(self.tail_angle_array.shape[0])

    #         for i in range(self.bouts.shape[0]):
    #             # get local maxima & minima
    #             peak_max, peak_min = peakdetect.peakdet(self.tail_end_angle_array[self.current_crop][self.bouts[i, 0]:self.bouts[i, 1]], 0.02)

    #             # change local coordinates (relative to the start of the bout) to global coordinates
    #             peak_max[:, 0] += self.bouts[i, 0]
    #             peak_min[:, 0] += self.bouts[i, 0]

    #             # add to the bout maxima & minima coord lists
    #             self.peak_maxes_y += list(peak_max[:, 1])
    #             self.peak_maxes_x += list(peak_max[:, 0])
    #             self.peak_mins_y += list(peak_min[:, 1])
    #             self.peak_mins_x += list(peak_min[:, 0])

    #         # calculate instantaneous frequencies
    #         for i in range(len(self.peak_maxes_x)-1):
    #             self.freqs[self.peak_maxes_x[i]:self.peak_maxes_x[i+1]] = 1.0/(self.peak_maxes_x[i+1] - self.peak_maxes_x[i])

    #         # update plot
    #         self.smoothed_deriv_checkbox.setChecked(False)
    #         self.tail_canvas.plot_tail_angle_array(self.tail_end_angle_array[self.current_crop], self.bouts, self.peak_maxes_y, self.peak_maxes_x, self.peak_mins_y, self.peak_mins_x, self.freqs, keep_limits=True)

    def track_position(self):
        if self.head_angle_array != None:
            # get params
            self.smoothing_window_width = int(self.smoothing_window_param_box.text())

            abs_angle_array = np.abs(self.tail_angle_array)
            deriv_abs_angle_array = np.gradient(abs_angle_array)
            abs_deriv_abs_angle_array = np.abs(deriv_abs_angle_array)
            self.smoothed_abs_deriv_abs_angle_array = np.convolve(abs_deriv_abs_angle_array, np.ones((self.smoothing_window_width,))/self.smoothing_window_width, mode='valid')

            positions_y, positions_x, self.speed_array = an.get_position_history(self.path, plot=False)

    def fileQuit(self):
        self.close()

    def closeEvent(self, event):
        self.controller.close_all()

    def resizeEvent(self, re):
        QMainWindow.resizeEvent(self, re)
コード例 #22
0
ファイル: misc_container.py プロジェクト: uKev/ninja-ide
 def setCurrentIndex(self, index):
     self.fader_widget = ui_tools.FaderWidget(self.currentWidget(),
                                              self.widget(index))
     QStackedWidget.setCurrentIndex(self, index)
コード例 #23
0
ファイル: widget.py プロジェクト: kissofblood/neuron
class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.widgetInputCount = inputcountselectionpanel.Widget()
        self.widgetExperiment = experimentpanel.Widget()

        self.stackedWidget = QStackedWidget()
        self.stackedWidget.addWidget(self.widgetInputCount)
        self.stackedWidget.addWidget(self.widgetExperiment)

        self.buttonBack = QPushButton('Back')
        self.buttonBack.setEnabled(False)
        self.buttonNext = QPushButton('Next')

        hboxLayoutButton = QHBoxLayout()
        hboxLayoutButton.addStretch(1)
        hboxLayoutButton.addWidget(self.buttonBack)
        hboxLayoutButton.addWidget(self.buttonNext)

        vboxLayout = QVBoxLayout()
        vboxLayout.addWidget(self.stackedWidget)
        vboxLayout.addLayout(hboxLayoutButton)

        self.setWindowTitle('Examination of a single neuron with multiple inputs (example 01c)')
        self.setLayout(vboxLayout)
        self.connect(self.buttonNext, SIGNAL('clicked()'), self.nextWidget)
        self.connect(self.buttonBack, SIGNAL('clicked()'), self.backWidget)
        self.connect(self.widgetExperiment.buttonRecalculate, SIGNAL('clicked()'), self.updateResult)

    def nextWidget(self):
        self.buttonNext.setEnabled(False)
        self.buttonBack.setEnabled(True)
        self.stackedWidget.setCurrentIndex(1)
        self.widgetExperiment.tableWidget.clear()
        self.widgetExperiment.memoryEdit.clear()
        self.widgetExperiment.signalEdit.clear()
        self.widgetExperiment.outputEdit.clear()

        self.widgetExperiment.tableWidget.setRowCount(self.widgetInputCount.spinInput.value())
        self.widgetExperiment.tableWidget.setColumnCount(3)
        self.widgetExperiment.tableWidget.setHorizontalHeaderLabels(['i', 'w(i)', 'x(i)'])
        self.neuron = Neuron(self.widgetInputCount.spinInput.value())
        for i in xrange(len(self.neuron.weights)):
            spinBox1 = QDoubleSpinBox()
            spinBox1.setRange(-100.0, 100.0)
            spinBox2 = QDoubleSpinBox()
            spinBox2.setRange(-100.0, 100.0)
            self.connect(spinBox1, SIGNAL('valueChanged(double)'), self.updateResult)
            self.connect(spinBox2, SIGNAL('valueChanged(double)'), self.updateResult)

            self.widgetExperiment.tableWidget.setCellWidget(i, 0, QLabel(str(i + 1)))
            self.widgetExperiment.tableWidget.setCellWidget(i, 1, spinBox1)
            self.widgetExperiment.tableWidget.setCellWidget(i, 2, spinBox2)

    def backWidget(self):
        self.buttonNext.setEnabled(True)
        self.buttonBack.setEnabled(False)
        self.stackedWidget.setCurrentIndex(0)

    def updateResult(self):
        for i in xrange(len(self.neuron.weights)):
            self.neuron.weights[i] = self.widgetExperiment.tableWidget.cellWidget(i, 1).value()
        inputs = [self.widgetExperiment.tableWidget.cellWidget(i, 2).value() for i in xrange(len(self.neuron.weights))]
        response = self.neuron.response(inputs)
        signalStrength = Neuron.strength(inputs, Neuron.StrenghtNormEuclidean)
        memStrength = self.neuron.memoryTraceStrength(Neuron.StrenghtNormEuclidean)

        self.widgetExperiment.signalEdit.setText(str(signalStrength))
        self.widgetExperiment.memoryEdit.setText(str(memStrength))
        self.widgetExperiment.outputEdit.setText(str(response))
コード例 #24
0
ファイル: qChatTab.py プロジェクト: Python3pkg/Cryptully
class QChatTab(QWidget):
    def __init__(self, chatWindow, nick):
        QWidget.__init__(self)

        self.chatWindow = chatWindow
        self.nick = nick
        self.unreadCount = 0

        self.widgetStack = QStackedWidget(self)
        self.widgetStack.addWidget(
            QNickInputWidget('new_chat.png',
                             150,
                             self.connectClicked,
                             parent=self))
        self.widgetStack.addWidget(QConnectingWidget(self))
        self.widgetStack.addWidget(
            QChatWidget(self.chatWindow.connectionManager, self))

        # Skip the chat layout if the nick was given denoting an incoming connection
        if self.nick is None or self.nick == '':
            self.widgetStack.setCurrentIndex(0)
        else:
            self.widgetStack.setCurrentIndex(2)

        layout = QHBoxLayout()
        layout.addWidget(self.widgetStack)
        self.setLayout(layout)

    def connectClicked(self, nick):
        # Check that the nick isn't already connected
        if self.chatWindow.isNickInTabs(nick):
            QMessageBox.warning(self, errors.TITLE_ALREADY_CONNECTED,
                                errors.ALREADY_CONNECTED % (nick))
            return

        self.nick = nick
        self.widgetStack.widget(1).setConnectingToNick(self.nick)
        self.widgetStack.setCurrentIndex(1)
        self.chatWindow.connectionManager.openChat(self.nick)

    def showNowChattingMessage(self):
        self.widgetStack.setCurrentIndex(2)
        self.widgetStack.widget(2).showNowChattingMessage(self.nick)

    def appendMessage(self, message, source):
        self.widgetStack.widget(2).appendMessage(message, source)

    def resetOrDisable(self):
        # If the connecting widget is showing, reset to the nick input widget
        # If the chat widget is showing, disable it to prevent sending of more messages
        curWidgetIndex = self.widgetStack.currentIndex()
        if curWidgetIndex == 1:
            self.widgetStack.setCurrentIndex(0)
        elif curWidgetIndex == 2:
            self.widgetStack.widget(2).disable()

    def enable(self):
        self.widgetStack.setCurrentIndex(2)
        self.widgetStack.widget(2).enable()
コード例 #25
0
ファイル: plugin.py プロジェクト: vpicavet/Roam
class QMap():
    def __init__(self, iface):
        self.iface = iface
        self.actions = []
        self.panels= []
        self.navtoolbar = self.iface.mapNavToolToolBar()
        self.mainwindow = self.iface.mainWindow()
        self.iface.projectRead.connect(self.projectOpened)
        self.iface.initializationCompleted.connect(self.setupUI)
        self.actionGroup = QActionGroup(self.mainwindow)
        self.actionGroup.setExclusive(True)
        self.menuGroup = QActionGroup(self.mainwindow)
        self.menuGroup.setExclusive(True)
                
        self.movetool = MoveTool(self.iface.mapCanvas(), [])
        self.infotool = InfoTool(self.iface.mapCanvas())
        self.infotool.infoResults.connect(self.showInfoResults)
        
        self.report = PopDownReport(self.iface.messageBar())
        
        self.dialogprovider = DialogProvider(iface.mapCanvas(), iface)
        self.dialogprovider.accepted.connect(self.clearToolRubberBand)
        self.dialogprovider.rejected.connect(self.clearToolRubberBand)
        
        self.edittool = EditTool(self.iface.mapCanvas(),[])
        self.edittool.finished.connect(self.openForm)
        self.edittool.featuresfound.connect(self.showFeatureSelection)

        self.infodock = InfoDock(self.iface.mainWindow())
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.infodock)
        self.infodock.hide()

        self.band = QgsRubberBand(self.iface.mapCanvas())
        self.band.setIconSize(20)
        self.band.setWidth(10)
        self.band.setColor(QColor(186, 93, 212, 76))

    def showFeatureSelection(self, features):
        listUi = ListFeaturesForm(self.mainwindow)
        listUi.loadFeatureList(features)
        listUi.openFeatureForm.connect(self.openForm)
        listUi.exec_()

    def showInfoResults(self, results):
        self.infodock.clearResults()
        self.infodock.setResults(results)
        self.infodock.show()
        self.infodock.repaint()
        
    @property
    def _mapLayers(self):
        return QgsMapLayerRegistry.instance().mapLayers()
        
    def clearToolRubberBand(self):
        tool = self.iface.mapCanvas().mapTool()
        try:
            tool.clearBand()
        except AttributeError:
            # No clearBand method found, but that's cool.
            pass
        
    def missingLayers(self, layers):
        def showError():
            html = ["<h1>Missing Layers</h1>", "<ul>"]
            for layer in layers:
                html.append("<li>{}</li>".format(layer))
            html.append("</ul>")
            
            self.errorreport.updateHTML("".join(html))
        
        message = "Seems like {} didn't load correctly".format(utils._pluralstring('layer', len(layers)))
        
        utils.warning("Missing layers")
        map(utils.warning, layers)
            
        self.widget = self.iface.messageBar().createMessage("Missing Layers",
                                                 message, 
                                                 QIcon(":/icons/sad"))
        button = QPushButton(self.widget)
        button.setCheckable(True)
        button.setChecked(self.errorreport.isVisible())
        button.setText("Show missing layers")
        button.toggled.connect(showError)
        button.toggled.connect(functools.partial(self.errorreport.setVisible))
        self.widget.destroyed.connect(self.hideReports)
        self.widget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.widget, QgsMessageBar.WARNING)
        
    def excepthook(self, ex_type, value, tb):
        """ 
        Custom exception hook so that we can handle errors in a
        nicer way
        """
        where = ''.join(traceback.format_tb(tb))
        msg = '{}'.format(value)
        utils.critical(msg)
        
        def showError():
            html = """
                <html>
                <body bgcolor="#FFEDED">
                <p><b>{}</b></p>
                <p align="left"><small>{}</small></p>
                </body>
                </html>
            """.format(msg, where)
            self.errorreport.updateHTML(html)
        
        self.widget = self.iface.messageBar().createMessage("oops", "Looks like an error occurred", QIcon(":/icons/sad"))
        button = QPushButton(self.widget)
        button.setCheckable(True)
        button.setChecked(self.errorreport.isVisible())
        button.setText("Show error")
        button.toggled.connect(showError)
        button.toggled.connect(functools.partial(self.errorreport.setVisible))
        self.widget.destroyed.connect(self.hideReports)
        self.widget.layout().addWidget(button)
        self.messageBar.pushWidget(self.widget, QgsMessageBar.CRITICAL)
    
    def hideReports(self):
        self.errorreport.setVisible(False)
        self.report.setVisible(False)
    
    def setupUI(self):
        """
        Set up the main QGIS interface items.  Called after QGIS has loaded
        the plugin.
        """
        self.updateAppSize()
        
        utils.settings_notify.settings_changed.connect(self.updateAppSize)

        self.navtoolbar.setMovable(False)
        self.navtoolbar.setAllowedAreas(Qt.TopToolBarArea)
        
        self.mainwindow.insertToolBar(self.toolbar, self.navtoolbar)
        self.openProjectAction.trigger()
        
    def updateAppSize(self):
        fullscreen = utils.settings.get("fullscreen", False)
        if fullscreen:
            self.mainwindow.showFullScreen()
        else:
            self.mainwindow.showMaximized()
            
    def setMapTool(self, tool):
        """
        Set the current mapview canvas tool

        tool -- The QgsMapTool to set
        """
        self.iface.mapCanvas().setMapTool(tool)

    def createToolBars(self):
        """
        Create all the needed toolbars
        """
        
        self.menutoolbar = QToolBar("Menu", self.mainwindow)
        self.menutoolbar.setMovable(False)
        self.menutoolbar.setAllowedAreas(Qt.LeftToolBarArea)
        self.mainwindow.addToolBar(Qt.LeftToolBarArea, self.menutoolbar)
        
        self.toolbar = QToolBar("QMap", self.mainwindow)
        self.mainwindow.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.setMovable(False)

        self.editingtoolbar = FloatingToolBar("Editing", self.toolbar)
        self.extraaddtoolbar = FloatingToolBar("Extra Add Tools", self.toolbar)
        self.syncactionstoolbar = FloatingToolBar("Syncing", self.toolbar)
        self.syncactionstoolbar.setOrientation(Qt.Vertical)

    def createActions(self):
        """
        Create all the actions
        """

        self.homeAction = (QAction(QIcon(":/icons/zoomfull"),
                                  "Default View", self.mainwindow))
        self.gpsAction = (GPSAction(QIcon(":/icons/gps"), self.iface.mapCanvas(),
                                   self.mainwindow))
        
        self.openProjectAction = (QAction(QIcon(":/icons/open"), "Projects",
                                         self.mainwindow))
        self.openProjectAction.setCheckable(True)
        
        self.configAction = (QAction(QIcon(":/icons/config"), "Settings",
                                         self.mainwindow))
        self.configAction.setCheckable(True)
        
        self.toggleRasterAction = (QAction(QIcon(":/icons/photo"), "Aerial Photos",
                                          self.mainwindow))
        self.syncAction = QAction(QIcon(":/icons/sync"), "Sync", self.mainwindow)
        self.syncAction.setVisible(False)
        
        self.editattributesaction = QAction(QIcon(":/icons/edit"), "Edit Attributes", self.mainwindow)
        self.editattributesaction.setCheckable(True)
        self.editattributesaction.toggled.connect(functools.partial(self.setMapTool, self.edittool))

        self.moveaction = QAction(QIcon(":/icons/move"), "Move Feature", self.mainwindow)
        self.moveaction.setCheckable(True)

        self.editingmodeaction = QAction(QIcon(":/icons/edittools"), "Edit Tools", self.mainwindow)
        self.editingmodeaction.setCheckable(True)
        
        self.infoaction = QAction(QIcon(":/icons/info"), "Info", self.mainwindow)
        self.infoaction.setCheckable(True)

        self.addatgpsaction = QAction(QIcon(":/icons/gpsadd"), "Add at GPS", self.mainwindow)
        
        self.edittool.layersupdated.connect(self.editattributesaction.setVisible)
        self.movetool.layersupdated.connect(self.moveaction.setVisible)
        self.movetool.layersupdated.connect(self.editingmodeaction.setVisible)
        
    def initGui(self):
        """
        Create all the icons and setup the tool bars.  Called by QGIS when
        loading. This is called before setupUI.
        """
        QApplication.setWindowIcon(QIcon(":/branding/logo"))
        self.mainwindow.findChildren(QMenuBar)[0].setVisible(False)
        self.mainwindow.setContextMenuPolicy(Qt.PreventContextMenu)
        self.mainwindow.setWindowTitle("IntraMaps Roam: Mobile Data Collection")
        
        # Disable QGIS logging window popups. We do our own logging
        QgsMessageLog.instance().messageReceived.disconnect()
        
        s = """
        QToolButton { 
            padding: 6px;
            color: #4f4f4f;
         }
        
        QToolButton:hover { 
            padding: 6px;
            background-color: rgb(211, 228, 255);
         }
         
        QToolBar {
         background: white;
        }
        
        QCheckBox::indicator {
             width: 40px;
             height: 40px;
         }
        
        QLabel {
            color: #4f4f4f;
        }
        
        QDialog { background-color: rgb(255, 255, 255); }
        
        QPushButton { 
            border: 1px solid #e1e1e1;
             padding: 6px;
            color: #4f4f4f;
         }
        
        QPushButton:hover { 
            border: 1px solid #e1e1e1;
             padding: 6px;
            background-color: rgb(211, 228, 255);
         }
        
        QCheckBox {
            color: #4f4f4f;
        }
        
        QComboBox::drop-down {
            width: 30px;
        }
        
        QComboBox {
            border: 1px solid #d3d3d3;
        }

        QStackedWidget {
             background-color: rgb(255, 255, 255);
        }
        """
        self.mainwindow.setStyleSheet(s)
        
        mainwidget = self.mainwindow.centralWidget()
        mainwidget.setLayout(QGridLayout())
        mainwidget.layout().setContentsMargins(0,0,0,0)
        
        newlayout = QGridLayout()
        newlayout.setContentsMargins(0,0,0,0)
        newlayout.addWidget(self.iface.mapCanvas(), 0,0,2,1)
        newlayout.addWidget(self.iface.messageBar(), 0,0,1,1)
        
        wid = QWidget()
        wid.setLayout(newlayout)
        
        self.stack = QStackedWidget(self.mainwindow)
        self.messageBar = QgsMessageBar(wid)
        self.messageBar.setSizePolicy( QSizePolicy.Minimum, QSizePolicy.Fixed )
        self.errorreport = PopDownReport(self.messageBar)

        mainwidget.layout().addWidget(self.stack, 0,0,2,1)
        mainwidget.layout().addWidget(self.messageBar, 0,0,1,1)

        self.helppage = HelpPage()
        helppath = os.path.join(os.path.dirname(__file__) , 'help',"help.html")
        self.helppage.setHelpPage(helppath)
        
        self.settingswidget = SettingsWidget(self.stack)
        
        self.projectwidget = ProjectsWidget()   
        self.projectwidget.requestOpenProject.connect(self.loadProject)
        self.stack.addWidget(wid)
        self.stack.addWidget(self.projectwidget)
        self.stack.addWidget(self.helppage)
        self.stack.addWidget(self.settingswidget)
                
        sys.excepthook = self.excepthook

        def createSpacer(width=30):
            widget = QWidget()
            widget.setMinimumWidth(width)
            return widget

        self.createToolBars()
        self.createActions()

        spacewidget = createSpacer(60)
        gpsspacewidget = createSpacer()
        gpsspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.moveaction.toggled.connect(functools.partial(self.setMapTool, self.movetool))
        self.infoaction.toggled.connect(functools.partial(self.setMapTool, self.infotool))
        
        showediting = (functools.partial(self.editingtoolbar.showToolbar, 
                                         self.editingmodeaction,
                                         self.moveaction))
        self.editingmodeaction.toggled.connect(showediting)

        self.addatgpsaction.triggered.connect(self.addAtGPS)
        self.addatgpsaction.setEnabled(self.gpsAction.isConnected)
        self.gpsAction.gpsfixed.connect(self.addatgpsaction.setEnabled)

        self.editingtoolbar.addToActionGroup(self.moveaction)

        self.actionGroup.addAction(self.editingmodeaction)
        self.actionGroup.addAction(self.editattributesaction)
        self.actionGroup.addAction(self.infoaction)

        self.homeAction.triggered.connect(self.zoomToDefaultView)
        
        self.openProjectAction.triggered.connect(self.showOpenProjectDialog)
        self.openProjectAction.triggered.connect(functools.partial(self.stack.setCurrentIndex, 1))
        
        self.configAction.triggered.connect(functools.partial(self.stack.setCurrentIndex, 3))
        self.configAction.triggered.connect(self.settingswidget.populateControls)
        self.configAction.triggered.connect(self.settingswidget.readSettings)
        
        self.toggleRasterAction.triggered.connect(self.toggleRasterLayers)

        self.navtoolbar.insertAction(self.iface.actionZoomIn(), self.iface.actionTouch())
        self.navtoolbar.insertAction(self.iface.actionTouch(), self.homeAction)
        self.navtoolbar.insertAction(self.iface.actionTouch(), self.iface.actionZoomFullExtent())
        self.navtoolbar.insertAction(self.homeAction, self.iface.actionZoomFullExtent())

        self.navtoolbar.addAction(self.toggleRasterAction)
        self.navtoolbar.insertWidget(self.iface.actionZoomFullExtent(), spacewidget)
        self.toolbar.addAction(self.infoaction)
        self.toolbar.addAction(self.editingmodeaction)
        self.toolbar.addAction(self.editattributesaction)
        self.toolbar.addAction(self.syncAction)
        self.toolbar.addAction(self.gpsAction)
        self.toolbar.insertWidget(self.syncAction, gpsspacewidget)
        self.toolbar.insertSeparator(self.gpsAction)

        self.extraaddtoolbar.addAction(self.addatgpsaction)

        self.editingtoolbar.addAction(self.moveaction)
        
        self.mapview = QAction(QIcon(":/icons/map"), "Map", self.menutoolbar)
        self.mapview.setCheckable(True)
        self.mapview.triggered.connect(functools.partial(self.stack.setCurrentIndex, 0))
        
        self.help = QAction(QIcon(":/icons/help"), "Help", self.menutoolbar)
        self.help.setCheckable(True)
        self.help.triggered.connect(functools.partial(self.stack.setCurrentIndex, 2))
        self.help.setVisible(False)
        
        self.projectlabel = QLabel("Project: <br> None")
        self.projectlabel.setAlignment(Qt.AlignCenter)
        self.projectlabel.setStyleSheet("""
            QLabel {
                    color: #8c8c8c;
                    font: 10px "Calibri" ;
                    }""")

        self.userlabel = QLabel("User: <br> {user}".format(user=getpass.getuser()))
        self.userlabel.setAlignment(Qt.AlignCenter)
        self.userlabel.setStyleSheet("""
            QLabel {
                    color: #8c8c8c;
                    font: 10px "Calibri" ;
                    }""")
        
        self.quit = QAction(QIcon(":/icons/quit"), "Quit", self.menutoolbar)
        self.quit.triggered.connect(self.iface.actionExit().trigger)

        self.menuGroup.addAction(self.mapview)
        self.menuGroup.addAction(self.openProjectAction)
        self.menuGroup.addAction(self.help)
        self.menuGroup.addAction(self.configAction)
        
        self.menutoolbar.addAction(self.mapview)
        self.menutoolbar.addAction(self.openProjectAction)
        self.menutoolbar.addAction(self.help)
        self.menutoolbar.addAction(self.configAction)
        self.menutoolbar.addAction(self.quit)
        
        quitspacewidget = createSpacer()
        quitspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        labelaction = self.menutoolbar.insertWidget(self.configAction, self.userlabel)
        
        self.menutoolbar.insertWidget(labelaction, quitspacewidget)
        self.menutoolbar.insertWidget(labelaction, self.projectlabel)
        self.setupIcons()
        self.stack.currentChanged.connect(self.updateUIState)
        
    def updateUIState(self, page):
        """
        Update the UI state to reflect the currently selected
        page in the stacked widget
        """
        def setToolbarsActive(enabled):
            toolbars = self.mainwindow.findChildren(QToolBar)
            for toolbar in toolbars:
                if toolbar == self.menutoolbar:
                    continue
                toolbar.setEnabled(enabled)
        
        def setPanelsVisible(visible):
            for panel in self.panels:
                panel.setVisible(visible)
                
        ismapview = page == 0
        setToolbarsActive(ismapview)
        setPanelsVisible(ismapview)
        self.infodock.hide()

    def addAtGPS(self):
        """
        Add a record at the current GPS location.
        """
        action = self.actionGroup.checkedAction()
        if not action:
            return
        layer = action.data()
        if not layer:
            return
        
        point = self.gpsAction.position
        self.addNewFeature(layer=layer, geometry=point)
        
    def zoomToDefaultView(self):
        """
        Zoom the mapview canvas to the extents the project was opened at i.e. the
        default extent.
        """
        self.iface.mapCanvas().setExtent(self.defaultextent)
        self.iface.mapCanvas().refresh()

    def toggleRasterLayers(self):
        """
        Toggle all raster layers on or off.
        """
        legend = self.iface.legendInterface()
        #Freeze the canvas to save on UI refresh
        self.iface.mapCanvas().freeze()
        for layer in self._mapLayers.values():
            if layer.type() == QgsMapLayer.RasterLayer:
                isvisible = legend.isLayerVisible(layer)
                legend.setLayerVisible(layer, not isvisible)
        self.iface.mapCanvas().freeze(False)
        self.iface.mapCanvas().refresh()

    def setupIcons(self):
        """
        Update toolbars to have text and icons, change normal QGIS
        icons to new style
        """
        toolbars = self.mainwindow.findChildren(QToolBar)
        for toolbar in toolbars:
            toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
            toolbar.setIconSize(QSize(32, 32))

        self.iface.actionTouch().setIconText("Pan")
        self.iface.actionTouch().setIcon(QIcon(":/icons/pan"))
        self.iface.actionZoomIn().setIcon(QIcon(":/icons/in"))
        self.iface.actionZoomOut().setIcon(QIcon(":/icons/out"))
        self.iface.actionPan().setIcon(QIcon(":/icons/pan"))
        self.iface.actionZoomFullExtent().setIcon(QIcon(":/icons/home"))
        self.iface.actionZoomFullExtent().setIconText("Home View")

        self.actionGroup.addAction(self.iface.actionZoomIn())
        self.actionGroup.addAction(self.iface.actionZoomOut())
        self.actionGroup.addAction(self.iface.actionTouch())

    def projectOpened(self):
        """
            Called when a new project is opened in QGIS.
        """
        for panel in self.panels:
            self.mainwindow.removeDockWidget(panel)
            del panel

        projectpath = QgsProject.instance().fileName()
        project = QMapProject(os.path.dirname(projectpath), self.iface)
        self.projectlabel.setText("Project: <br> {}".format(project.name))
        self.createFormButtons(projectlayers = project.getConfiguredLayers())
        
        # Enable the raster layers button only if the project contains a raster layer.
        hasrasters = any(layer.type() for layer in self._mapLayers.values())
        self.toggleRasterAction.setEnabled(hasrasters)
        self.defaultextent = self.iface.mapCanvas().extent()
        self.connectSyncProviders(project)
        
        # Show panels
        self.panels = list(project.getPanels())
        for panel in self.panels:
            self.mainwindow.addDockWidget(Qt.BottomDockWidgetArea , panel)
            
        self.iface.messageBar().popWidget()

    def captureLayer(self, layer):
        text = layer.icontext
        tool = layer.getMaptool(self.iface.mapCanvas())

        # Hack until I fix it later
        if isinstance(tool, PointTool):
            add = functools.partial(self.addNewFeature, qgslayer)
            tool.geometryComplete.connect(add)
        else:
            tool.finished.connect(self.openForm)
            tool.error.connect(functools.partial(self.showToolError, text))

        action = QAction(QIcon(layer.icon), text, self.mainwindow)
        action.setData(layer)
        action.setCheckable(True)
        action.toggled.connect(functools.partial(self.setMapTool, tool))

        self.toolbar.insertAction(self.editingmodeaction, action)

        if not tool.isEditTool():
            # Connect the GPS tools strip to the action pressed event.
            showgpstools = (functools.partial(self.extraaddtoolbar.showToolbar,
                                         action,
                                         None))

            action.toggled.connect(showgpstools)

        self.actionGroup.addAction(action)
        self.actions.append(action)

    def editLayer(self, layer):
        self.edittool.addLayer(layer.QGISLayer)
        self.edittool.searchRadius = 10

    def moveLayer(self, layer):
        self.movetool.addLayer(layer.QGISLayer)

    def createFormButtons(self, projectlayers):
        """
            Create buttons for each form that is definded
        """
        # Remove all the old buttons
        for action in self.actions:
            self.actionGroup.removeAction(action)
            self.toolbar.removeAction(action)
                
        self.edittool.layers = []
        self.movetool.layers = []
        capabilitityhandlers = { "capture" : self.captureLayer,
                                 "edit" : self.editLayer,
                                 "move" : self.moveLayer}

        for layer in projectlayers:
            try:
                qgslayer = QgsMapLayerRegistry.instance().mapLayersByName(layer.name)[0]
                if qgslayer.type() == QgsMapLayer.RasterLayer:
                    utils.log("We can't support raster layers for data entry")
                    continue
                       
                layer.QGISLayer = qgslayer
            except IndexError:
                utils.log("Layer {} not found in project".format(layer.name))
                continue

            for capability in layer.capabilities:
                try:
                    capabilitityhandlers[capability](layer)
                except NoMapToolConfigured:
                    utils.log("No map tool configured")
                    continue
                except ErrorInMapTool as error:
                    self.iface.messageBar().pushMessage("Error configuring map tool", error.message, level=QgsMessageBar.WARNING)
                    continue

    def showToolError(self, label, message):
        self.iface.messageBar().pushMessage(label, message, QgsMessageBar.WARNING)
            
    def openForm(self, layer, feature):
        if not layer.isEditable():
            layer.startEditing()

        self.band.setToGeometry(feature.geometry(), layer)
        self.dialogprovider.openDialog(feature=feature, layer=layer)
        self.band.reset()

    def addNewFeature(self, layer, geometry):
        fields = layer.pendingFields()
        
        feature = QgsFeature()
        feature.setGeometry( geometry )
        feature.initAttributes(fields.count())
        feature.setFields(fields)
        
        for indx in xrange(fields.count()):
            feature[indx] = layer.dataProvider().defaultValue(indx)

        self.openForm(layer, feature)

    def showOpenProjectDialog(self):
        """
        Show the project selection dialog.
        """
        self.stack.setCurrentIndex(1)
        self.infodock.hide()
        path = os.path.join(os.path.dirname(__file__), '..' , 'projects/')
        projects = getProjects(path, self.iface)
        self.projectwidget.loadProjectList(projects)
        
    def loadProject(self, project):
        """
        Load a project into QGIS.
        """
        utils.log(project)
        utils.log(project.name)
        utils.log(project.projectfile)
        utils.log(project.vaild)
        
        (passed, message) = project.onProjectLoad()
        
        if not passed:
            QMessageBox.warning(self.mainwindow, "Project Load Rejected", 
                                "Project couldn't be loaded because {}".format(message))
            return
        
        self.mapview.trigger()
        self.iface.newProject(False)        
        self.iface.mapCanvas().freeze()
        self.infodock.clearResults()
        # No idea why we have to set this each time.  Maybe QGIS deletes it for
        # some reason.
        self.badLayerHandler = BadLayerHandler(callback=self.missingLayers)
        QgsProject.instance().setBadLayerHandler( self.badLayerHandler )
        
        self.iface.messageBar().pushMessage("Project Loading","", QgsMessageBar.INFO)
        QApplication.processEvents()

        fileinfo = QFileInfo(project.projectfile)
        QgsProject.instance().read(fileinfo)

        self.iface.mapCanvas().updateScale()
        self.iface.mapCanvas().freeze(False)
        self.iface.mapCanvas().refresh()
        self.mainwindow.setWindowTitle("IntraMaps Roam: Mobile Data Collection")
        self.iface.projectRead.emit()
        
    def unload(self):
        del self.toolbar
        
    def connectSyncProviders(self, project):
        self.syncactionstoolbar.clear()
        
        syncactions = list(project.syncprovders())
        
        # Don't show the sync button if there is no sync providers
        if not syncactions:
            self.syncAction.setVisible(False)
            return
        
        self.syncAction.setVisible(True)
        
        for provider in syncactions:
            action = QAction(QIcon(":/icons/sync"), "Sync {}".format(provider.name), self.mainwindow)
            action.triggered.connect(functools.partial(self.syncProvider, provider))
            self.syncactionstoolbar.addAction(action)
        
        try:
            self.syncAction.toggled.disconnect()
        except TypeError:
            pass
        try:
            self.syncAction.triggered.disconnect()
        except TypeError:
            pass
        
        if len(syncactions) == 1:
            # If one provider is set then we just connect the main button.    
            self.syncAction.setCheckable(False)
            self.syncAction.setText("Sync")
            self.syncAction.triggered.connect(functools.partial(self.syncProvider, syncactions[0]))
        else:
            # the sync button because a sync menu
            self.syncAction.setCheckable(True)
            self.syncAction.setText("Sync Menu")
            showsyncoptions = (functools.partial(self.syncactionstoolbar.showToolbar, 
                                                 self.syncAction, None))
            self.syncAction.toggled.connect(showsyncoptions)

    def syncstarted(self):                   
        # Remove the old widget if it's still there.
        # I don't really like this. Seems hacky.
        try:
            self.iface.messageBar().popWidget(self.syncwidget)
        except RuntimeError:
            pass
        except AttributeError:
            pass
        
        self.iface.messageBar().findChildren(QToolButton)[0].setVisible(False)
        self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync in progress", QIcon(":/icons/syncing"))
        button = QPushButton(self.syncwidget)
        button.setCheckable(True)
        button.setText("Status")
        button.setIcon(QIcon(":/icons/syncinfo"))
        button.toggled.connect(functools.partial(self.report.setVisible))
        pro = QProgressBar()
        pro.setMaximum(0)
        pro.setMinimum(0)
        self.syncwidget.layout().addWidget(pro)
        self.syncwidget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.syncwidget, QgsMessageBar.INFO)
        
    def synccomplete(self):
        try:
            self.iface.messageBar().popWidget(self.syncwidget)
        except RuntimeError:
            pass
        
        stylesheet = ("QgsMessageBar { background-color: rgba(239, 255, 233); border: 0px solid #b9cfe4; } "
                     "QLabel,QTextEdit { color: #057f35; } ")
        
        closebutton = self.iface.messageBar().findChildren(QToolButton)[0]
        closebutton.setVisible(True)
        closebutton.clicked.connect(functools.partial(self.report.setVisible, False))
        self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Complete", QIcon(":/icons/syncdone"))
        button = QPushButton(self.syncwidget)
        button.setCheckable(True)
        button.setChecked(self.report.isVisible())
        button.setText("Sync Report")
        button.setIcon(QIcon(":/icons/syncinfo"))
        button.toggled.connect(functools.partial(self.report.setVisible))      
        pro = QProgressBar()
        pro.setMaximum(100)
        pro.setValue(100)
        self.syncwidget.layout().addWidget(pro)      
        self.syncwidget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.syncwidget)
        self.iface.messageBar().setStyleSheet(stylesheet)
        self.iface.mapCanvas().refresh()
        
    def syncerror(self):
        try:
            self.iface.messageBar().popWidget(self.syncwidget)
        except RuntimeError:
            pass
        
        closebutton = self.iface.messageBar().findChildren(QToolButton)[0]
        closebutton.setVisible(True)
        closebutton.clicked.connect(functools.partial(self.report.setVisible, False))
        self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Error", QIcon(":/icons/syncfail"))
        button = QPushButton(self.syncwidget)
        button.setCheckable(True)
        button.setChecked(self.report.isVisible())
        button.setText("Sync Report")
        button.setIcon(QIcon(":/icons/syncinfo"))
        button.toggled.connect(functools.partial(self.report.setVisible))            
        self.syncwidget.layout().addWidget(button)
        self.iface.messageBar().pushWidget(self.syncwidget, QgsMessageBar.CRITICAL)
        self.iface.mapCanvas().refresh()
        
    def syncProvider(self, provider):
        self.syncAction.toggle()
        provider.syncStarted.connect(functools.partial(self.syncAction.setEnabled, False))
        provider.syncStarted.connect(self.syncstarted)
        
        provider.syncComplete.connect(self.synccomplete)
        provider.syncComplete.connect(functools.partial(self.syncAction.setEnabled, True))
        provider.syncComplete.connect(functools.partial(self.report.updateHTML))
        
        provider.syncMessage.connect(self.report.updateHTML)
        
        provider.syncError.connect(self.report.updateHTML)
        provider.syncError.connect(self.syncerror)
        provider.syncError.connect(functools.partial(self.syncAction.setEnabled, True))
        
        provider.startSync()
コード例 #26
0
ファイル: view.py プロジェクト: Mouchnino/moneyguru
class EntryView(BaseView):
    def _setup(self):
        self._setupUi()
        self.etable = EntryTable(self.model.etable, view=self.tableView)
        self.efbar = EntryFilterBar(model=self.model.filter_bar, view=self.filterBar)
        self.bgraph = Chart(self.model.bargraph, view=self.barGraphView)
        self.lgraph = Chart(self.model.balgraph, view=self.lineGraphView)
        self._setupColumns() # Can only be done after the model has been connected
        
        self.reconciliationButton.clicked.connect(self.model.toggle_reconciliation_mode)
    
    def _setupUi(self):
        self.resize(483, 423)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setMargin(0)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setSpacing(0)
        self.filterBar = RadioBox(self)
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.filterBar.sizePolicy().hasHeightForWidth())
        self.filterBar.setSizePolicy(sizePolicy)
        self.horizontalLayout.addWidget(self.filterBar)
        self.horizontalLayout.addItem(horizontalSpacer())
        self.reconciliationButton = QPushButton(tr("Reconciliation"))
        self.reconciliationButton.setCheckable(True)
        self.horizontalLayout.addWidget(self.reconciliationButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.splitterView = QSplitter()
        self.splitterView.setOrientation(Qt.Vertical)
        self.splitterView.setChildrenCollapsible(False)
        self.tableView = TableView(self)
        self.tableView.setAcceptDrops(True)
        self.tableView.setEditTriggers(QAbstractItemView.DoubleClicked|QAbstractItemView.EditKeyPressed)
        self.tableView.setDragEnabled(True)
        self.tableView.setDragDropMode(QAbstractItemView.InternalMove)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setSortingEnabled(True)
        self.tableView.horizontalHeader().setHighlightSections(False)
        self.tableView.horizontalHeader().setMinimumSectionSize(18)
        self.tableView.verticalHeader().setVisible(False)
        self.tableView.verticalHeader().setDefaultSectionSize(18)
        self.splitterView.addWidget(self.tableView)
        self.graphView = QStackedWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.graphView.sizePolicy().hasHeightForWidth())
        self.graphView.setSizePolicy(sizePolicy)
        self.graphView.setMinimumSize(0, 200)
        self.lineGraphView = LineGraphView()
        self.graphView.addWidget(self.lineGraphView)
        self.barGraphView = BarGraphView()
        self.graphView.addWidget(self.barGraphView)
        self.splitterView.addWidget(self.graphView)
        self.graphView.setCurrentIndex(1)
        self.splitterView.setStretchFactor(0, 1)
        self.splitterView.setStretchFactor(1, 0)
        self.verticalLayout.addWidget(self.splitterView)
    
    def _setupColumns(self):
        h = self.tableView.horizontalHeader()
        h.setMovable(True) # column drag & drop reorder
    
    #--- QWidget override
    def setFocus(self):
        self.etable.view.setFocus()
    
    #--- Public
    def fitViewsForPrint(self, viewPrinter):
        hidden = self.model.mainwindow.hidden_areas
        viewPrinter.fitTable(self.etable)
        if PaneArea.BottomGraph not in hidden:
            viewPrinter.fit(self.graphView.currentWidget(), 300, 150, expandH=True, expandV=True)
    
    def restoreSubviewsSize(self):
        graphHeight = self.model.graph_height_to_restore
        if graphHeight:
            splitterHeight = self.splitterView.height()
            sizes = [splitterHeight-graphHeight, graphHeight]
            self.splitterView.setSizes(sizes)
    
    #--- model --> view
    def refresh_reconciliation_button(self):
        if self.model.can_toggle_reconciliation_mode:
            self.reconciliationButton.setEnabled(True)
            self.reconciliationButton.setChecked(self.model.reconciliation_mode)
        else:
            self.reconciliationButton.setEnabled(False)
            self.reconciliationButton.setChecked(False)
    
    def show_bar_graph(self):
        self.graphView.setCurrentIndex(1)
    
    def show_line_graph(self):
        self.graphView.setCurrentIndex(0)
    
    def update_visibility(self):
        hidden = self.model.mainwindow.hidden_areas
        self.graphView.setHidden(PaneArea.BottomGraph in hidden)
コード例 #27
0
ファイル: preferencias.py プロジェクト: ekimdev/edis
class Preferencias(QDialog):

    def __init__(self, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("Preferencias - EDIS"))
        self.setMinimumSize(700, 500)
        self.general = preferencias_general.ConfiguracionGeneral(self)
        self.editor = preferencias_editor.TabEditor()
        self.gui = preferencias_gui.ConfiguracionGUI(self)
        self._ejecucion = preferencias_ejecucion.ConfiguracionEjecucion(self)

        # valor: texto en combo, clave: instancia de widgets
        self.widgets = OrderedDict([
            ('General', self.general),
            ('Editor', self.editor),
            ('GUI', self.gui),
            ('Ejecucion', self._ejecucion)])
            #])

        self.load_ui()

        # Conexiones
        self.connect(self.button_general, SIGNAL("clicked()"),
                     lambda: self.cambiar_widget(0))
        self.connect(self.button_editor, SIGNAL("clicked()"),
                     lambda: self.cambiar_widget(1))
        self.connect(self.button_gui, SIGNAL("clicked()"),
                     lambda: self.cambiar_widget(2))
        self.connect(self.button_compi, SIGNAL("clicked()"),
                     lambda: self.cambiar_widget(3))
        self.connect(self.btn_cancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btn_guardar, SIGNAL("clicked()"), self._guardar)

        EDIS.cargar_componente("preferencias", self)

    def load_ui(self):
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)

        toolbar = QToolBar()
        toolbar.setIconSize(QSize(40, 40))
        toolbar.setObjectName("preferencias")
        toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)

        self.button_general = ToolButton("General",
                                         paths.ICONOS['general'])
        self.button_editor = ToolButton("Editor",
                                        paths.ICONOS['edit'])
        self.button_gui = ToolButton("Interfáz", paths.ICONOS['gui'])
        self.button_compi = ToolButton("Ejecución", paths.ICONOS['build'])

        toolbar.addWidget(self.button_general)
        toolbar.addWidget(self.button_editor)
        toolbar.addWidget(self.button_gui)
        toolbar.addWidget(self.button_compi)

        box.addWidget(toolbar)

        self.stack = QStackedWidget()
        box.addWidget(self.stack)

        [self.stack.addWidget(widget)
            for widget in list(self.widgets.values())]

        box_buttons = QHBoxLayout()
        box_buttons.setMargin(10)
        box_buttons.setSpacing(10)
        box_buttons.addStretch(1)
        self.btn_cancel = QPushButton(self.tr("Cancelar"))
        self.btn_guardar = QPushButton(self.tr("Guardar"))
        box_buttons.addWidget(self.btn_cancel)
        box_buttons.addWidget(self.btn_guardar)

        box.addLayout(box_buttons)

    def mostrar(self):
        self.stack.setCurrentIndex(0)
        self.show()

    def cambiar_widget(self, index):
        if not self.isVisible():
            self.show()
        self.stack.setCurrentIndex(index)

    def _guardar(self):
        [self.stack.widget(i).guardar()
            for i in range(self.stack.count())]
        self.close()
コード例 #28
0
class DbConnOptions(QWidget):
    def __init__(self, parent, conn_properties):        
        super(DbConnOptions, self).__init__(parent)
        
        self.plugin_manager = get_plugin_manager()
        self.available_types = {}
        self.conn_properties = None
        
        for dbplugin in self.plugin_manager.getPluginsOfCategory("db"):
            self.available_types[dbplugin.name] = dbplugin.plugin_object
                
        lay = QGridLayout(self)
        
        if len(self.available_types) == 0:
            lay.addWidget(QLabel("No DB plugin activated", parent), 0, 0, Qt.AlignRight)
            return
            
        lay.addWidget(QLabel("Name: ", parent), 0, 0, Qt.AlignRight)        
        self.nameCombo = QComboBox(parent)
        lay.addWidget(self.nameCombo, 0, 1)
        lay.addWidget(QLabel("Type: ", parent), 1, 0, Qt.AlignRight)
        self.typeCombo = QComboBox(parent)
        lay.addWidget(self.typeCombo, 1, 1)
        self.conn_details = QStackedWidget(parent)
        lay.addWidget(self.conn_details, 2, 0, 1, 2)        
        newConnButton = QPushButton("New Connection", parent)
        lay.addWidget(newConnButton, 3, 1)
        self.warningLbl = QLabel("The standard connection is used by the lunchinator internally to store messages etc." + \
                             " It can be used by plugins as well, but it cannot be changed.")
        self.warningLbl.setWordWrap(True)
        lay.addWidget(self.warningLbl, 4, 0, 4, 2)
        
        for p in self.available_types.values():
            w = p.create_db_options_widget(parent)
            if w == None:
                w = QLabel("Plugin not activated", parent)
            self.conn_details.addWidget(w)   
            
        self.typeCombo.addItems(self.available_types.keys())
        
        self.reset_connection_properties(conn_properties)  
        newConnButton.clicked.connect(self.new_conn)      
        
    def reset_connection_properties(self, conn_properties):
        try:
            self.nameCombo.currentIndexChanged.disconnect(self.name_changed)
            self.typeCombo.currentIndexChanged.disconnect(self.type_changed)
        except:
            pass
        
        self.conn_properties = deepcopy(conn_properties)
        self.nameCombo.clear()
        self.nameCombo.addItems(self.conn_properties.keys())
            
        type_name = self.conn_properties[str(self.nameCombo.currentText())]["plugin_type"]
        type_index = self.typeCombo.findText(type_name)
        self.typeCombo.setCurrentIndex(type_index)  
        self.conn_details.setCurrentIndex(type_index)
        
        self.fill_conn_details()       
        
        self.typeCombo.currentIndexChanged.connect(self.type_changed)
        self.nameCombo.currentIndexChanged.connect(self.name_changed)
    
    def store_conn_details(self):
        p = self.available_types[self.last_type]
        o = p.get_options_from_widget()
        if o:
            self.conn_properties[self.last_name].update(o)
            self.conn_properties[self.last_name]["plugin_type"] = self.last_type
        
    def fill_conn_details(self):        
        self.last_type = str(self.typeCombo.currentText())
        self.last_name = str(self.nameCombo.currentText())
        
        p = self.available_types[self.last_type]
        p.fill_options_widget(self.conn_properties[self.last_name])
            
        if self.nameCombo.currentText()=="Standard":
            self.typeCombo.setEnabled(False)
            self.conn_details.setEnabled(False)
            self.warningLbl.setVisible(True)
        else:
            self.typeCombo.setEnabled(True)
            self.conn_details.setEnabled(True)
            self.warningLbl.setVisible(False)
        
    @loggingSlot(int)
    def type_changed(self, index):
        self.conn_details.setCurrentIndex(index)
        self.store_conn_details()
        self.fill_conn_details()
        
    @loggingSlot(int)
    def name_changed(self, _index):
        type_name = self.conn_properties[str(self.nameCombo.currentText())]["plugin_type"]
        type_index = self.typeCombo.findText(type_name)
        if type_index == self.typeCombo.currentIndex():
            self.store_conn_details()
            self.fill_conn_details()
        else:
            self.typeCombo.setCurrentIndex(type_index)
            
    @loggingSlot()
    def new_conn(self):
        i = len(self.conn_properties)
        while u"Conn %d" % i in self.conn_properties:
            i += 1
        proposedName = u"Conn %d" % i
        
        new_conn_name = None
        while not new_conn_name or new_conn_name in self.conn_properties:
            if new_conn_name in self.conn_properties:
                msg = u"Connection \"%s\" already exists. Enter a different name:" % new_conn_name
            else:
                msg = u"Enter the name of the new connection:"
            new_conn_name, ok = QInputDialog.getText(self,
                                                     u"Connection Name",
                                                     msg,
                                                     QLineEdit.Normal,
                                                     proposedName)
            if not ok:
                return 
            new_conn_name = convert_string(new_conn_name)
        
        self.conn_properties[new_conn_name] = {"plugin_type" : str(self.typeCombo.currentText()) }
        self.nameCombo.addItem(new_conn_name)
        self.nameCombo.setCurrentIndex(self.nameCombo.count() - 1)
        
    def get_connection_properties(self):
        self.store_conn_details()
        return self.conn_properties
コード例 #29
0
class OWImportImages(widget.OWWidget):
    name = "Import Images"
    description = "Import images from a directory(s)"
    icon = "icons/ImportImages.svg"
    priority = 110

    outputs = [("Data", Orange.data.Table)]

    #: list of recent paths
    recent_paths = settings.Setting([])  # type: List[RecentPath]
    currentPath = settings.Setting(None)

    want_main_area = False
    resizing_enabled = False

    Modality = Qt.ApplicationModal
    # Modality = Qt.WindowModal

    MaxRecentItems = 20

    def __init__(self):
        super().__init__()
        #: widget's runtime state
        self.__state = State.NoState
        self._imageMeta = []
        self._imageCategories = {}

        self.__invalidated = False
        self.__pendingTask = None

        vbox = gui.vBox(self.controlArea)
        hbox = gui.hBox(vbox)
        self.recent_cb = QComboBox(
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
            minimumContentsLength=16,
        )
        self.recent_cb.activated[int].connect(self.__onRecentActivated)
        icons = standard_icons(self)

        browseaction = QAction(
            "Open/Load Images", self,
            iconText="\N{HORIZONTAL ELLIPSIS}",
            icon=icons.dir_open_icon,
            toolTip="Select a directory from which to load the images"
        )
        browseaction.triggered.connect(self.__runOpenDialog)
        reloadaction = QAction(
            "Reload", self,
            icon=icons.reload_icon,
            toolTip="Reload current image set"
        )
        reloadaction.triggered.connect(self.reload)
        self.__actions = namespace(
            browse=browseaction,
            reload=reloadaction,
        )

        browsebutton = QPushButton(
            browseaction.iconText(),
            icon=browseaction.icon(),
            toolTip=browseaction.toolTip(),
            clicked=browseaction.trigger
        )
        reloadbutton = QPushButton(
            reloadaction.iconText(),
            icon=reloadaction.icon(),
            clicked=reloadaction.trigger,
            default=True,
        )

        hbox.layout().addWidget(self.recent_cb)
        hbox.layout().addWidget(browsebutton)
        hbox.layout().addWidget(reloadbutton)

        self.addActions([browseaction, reloadaction])

        reloadaction.changed.connect(
            lambda: reloadbutton.setEnabled(reloadaction.isEnabled())
        )
        box = gui.vBox(vbox, "Info")
        self.infostack = QStackedWidget()

        self.info_area = QLabel(
            text="No image set selected",
            wordWrap=True
        )
        self.progress_widget = QProgressBar(
            minimum=0, maximum=0
        )
        self.cancel_button = QPushButton(
            "Cancel", icon=icons.cancel_icon,
        )
        self.cancel_button.clicked.connect(self.cancel)

        w = QWidget()
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(0, 0, 0, 0)

        hlayout.addWidget(self.progress_widget)
        hlayout.addWidget(self.cancel_button)
        vlayout.addLayout(hlayout)

        self.pathlabel = TextLabel()
        self.pathlabel.setTextElideMode(Qt.ElideMiddle)
        self.pathlabel.setAttribute(Qt.WA_MacSmallSize)

        vlayout.addWidget(self.pathlabel)
        w.setLayout(vlayout)

        self.infostack.addWidget(self.info_area)
        self.infostack.addWidget(w)

        box.layout().addWidget(self.infostack)

        self.__initRecentItemsModel()
        self.__invalidated = True
        self.__executor = ThreadExecutor(self)

        QApplication.postEvent(self, QEvent(RuntimeEvent.Init))

    def __initRecentItemsModel(self):
        if self.currentPath is not None and \
                not os.path.isdir(self.currentPath):
            self.currentPath = None

        recent_paths = []
        for item in self.recent_paths:
            if os.path.isdir(item.abspath):
                recent_paths.append(item)
        recent_paths = recent_paths[:OWImportImages.MaxRecentItems]
        recent_model = self.recent_cb.model()
        for pathitem in recent_paths:
            item = RecentPath_asqstandarditem(pathitem)
            recent_model.appendRow(item)

        self.recent_paths = recent_paths

        if self.currentPath is not None and \
                os.path.isdir(self.currentPath) and self.recent_paths and \
                os.path.samefile(self.currentPath, self.recent_paths[0].abspath):
            self.recent_cb.setCurrentIndex(0)
        else:
            self.currentPath = None
            self.recent_cb.setCurrentIndex(-1)
        self.__actions.reload.setEnabled(self.currentPath is not None)

    def customEvent(self, event):
        """Reimplemented."""
        if event.type() == RuntimeEvent.Init:
            if self.__invalidated:
                try:
                    self.start()
                finally:
                    self.__invalidated = False

        super().customEvent(event)

    def __runOpenDialog(self):
        startdir = os.path.expanduser("~/")
        if self.recent_paths:
            startdir = self.recent_paths[0].abspath

        if OWImportImages.Modality == Qt.WindowModal:
            dlg = QFileDialog(
                self, "Select Top Level Directory", startdir,
                acceptMode=QFileDialog.AcceptOpen,
                modal=True,
            )
            dlg.setFileMode(QFileDialog.Directory)
            dlg.setOption(QFileDialog.ShowDirsOnly)
            dlg.setDirectory(startdir)
            dlg.setAttribute(Qt.WA_DeleteOnClose)

            @dlg.accepted.connect
            def on_accepted():
                dirpath = dlg.selectedFiles()
                if dirpath:
                    self.setCurrentPath(dirpath[0])
                    self.start()
            dlg.open()
        else:
            dirpath = QFileDialog.getExistingDirectory(
                self, "Select Top Level Directory", startdir
            )
            if dirpath:
                self.setCurrentPath(dirpath)
                self.start()

    def __onRecentActivated(self, index):
        item = self.recent_cb.itemData(index)
        if item is None:
            return
        assert isinstance(item, RecentPath)
        self.setCurrentPath(item.abspath)
        self.start()

    def __updateInfo(self):
        if self.__state == State.NoState:
            text = "No image set selected"
        elif self.__state == State.Processing:
            text = "Processing"
        elif self.__state == State.Done:
            nvalid = sum(imeta.isvalid for imeta in self._imageMeta)
            ncategories = len(self._imageCategories)
            if ncategories < 2:
                text = "{} images".format(nvalid)
            else:
                text = "{} images / {} categories".format(nvalid, ncategories)
        elif self.__state == State.Cancelled:
            text = "Cancelled"
        elif self.__state == State.Error:
            text = "Error state"
        else:
            assert False

        self.info_area.setText(text)

        if self.__state == State.Processing:
            self.infostack.setCurrentIndex(1)
        else:
            self.infostack.setCurrentIndex(0)

    def setCurrentPath(self, path):
        """
        Set the current root image path to path

        If the path does not exists or is not a directory the current path
        is left unchanged

        Parameters
        ----------
        path : str
            New root import path.

        Returns
        -------
        status : bool
            True if the current root import path was successfully
            changed to path.
        """
        if self.currentPath is not None and path is not None and \
                os.path.isdir(self.currentPath) and os.path.isdir(path) and \
                os.path.samefile(self.currentPath, path):
            return True

        if not os.path.exists(path):
            warnings.warn("'{}' does not exist".format(path), UserWarning)
            return False
        elif not os.path.isdir(path):
            warnings.warn("'{}' is not a directory".format(path), UserWarning)
            return False

        newindex = self.addRecentPath(path)
        self.recent_cb.setCurrentIndex(newindex)
        if newindex >= 0:
            self.currentPath = path
        else:
            self.currentPath = None
        self.__actions.reload.setEnabled(self.currentPath is not None)

        if self.__state == State.Processing:
            self.cancel()

        return True

    def addRecentPath(self, path):
        """
        Prepend a path entry to the list of recent paths

        If an entry with the same path already exists in the recent path
        list it is moved to the first place

        Parameters
        ----------
        path : str
        """
        existing = None
        for pathitem in self.recent_paths:
            if os.path.samefile(pathitem.abspath, path):
                existing = pathitem
                break

        model = self.recent_cb.model()

        if existing is not None:
            selected_index = self.recent_paths.index(existing)
            assert model.item(selected_index).data(Qt.UserRole) is existing
            self.recent_paths.remove(existing)
            row = model.takeRow(selected_index)
            self.recent_paths.insert(0, existing)
            model.insertRow(0, row)
        else:
            item = RecentPath(path, None, None)
            self.recent_paths.insert(0, item)
            model.insertRow(0, RecentPath_asqstandarditem(item))
        return 0

    def __setRuntimeState(self, state):
        assert state in State
        self.setBlocking(state == State.Processing)
        message = ""
        if state == State.Processing:
            assert self.__state in [State.Done,
                                    State.NoState,
                                    State.Error,
                                    State.Cancelled]
            message = "Processing"
        elif state == State.Done:
            assert self.__state == State.Processing
        elif state == State.Cancelled:
            assert self.__state == State.Processing
            message = "Cancelled"
        elif state == State.Error:
            message = "Error during processing"
        elif state == State.NoState:
            message = ""
        else:
            assert False

        self.__state = state

        if self.__state == State.Processing:
            self.infostack.setCurrentIndex(1)
        else:
            self.infostack.setCurrentIndex(0)

        self.setStatusMessage(message)
        self.__updateInfo()

    def reload(self):
        """
        Restart the image scan task
        """
        if self.__state == State.Processing:
            self.cancel()

        self._imageMeta = []
        self._imageCategories = {}
        self.start()

    def start(self):
        """
        Start/execute the image indexing operation
        """
        self.error()

        self.__invalidated = False
        if self.currentPath is None:
            return

        if self.__state == State.Processing:
            assert self.__pendingTask is not None
            log.info("Starting a new task while one is in progress. "
                     "Cancel the existing task (dir:'{}')"
                     .format(self.__pendingTask.startdir))
            self.cancel()

        startdir = self.currentPath

        self.__setRuntimeState(State.Processing)

        report_progress = methodinvoke(
            self, "__onReportProgress", (object,))

        task = ImageScan(startdir, report_progress=report_progress)

        # collect the task state in one convenient place
        self.__pendingTask = taskstate = namespace(
            task=task,
            startdir=startdir,
            future=None,
            watcher=None,
            cancelled=False,
            cancel=None,
        )

        def cancel():
            # Cancel the task and disconnect
            if taskstate.future.cancel():
                pass
            else:
                taskstate.task.cancelled = True
                taskstate.cancelled = True
                try:
                    taskstate.future.result(timeout=3)
                except UserInterruptError:
                    pass
                except TimeoutError:
                    log.info("The task did not stop in in a timely manner")
            taskstate.watcher.finished.disconnect(self.__onRunFinished)

        taskstate.cancel = cancel

        def run_image_scan_task_interupt():
            try:
                return task.run()
            except UserInterruptError:
                # Suppress interrupt errors, so they are not logged
                return

        taskstate.future = self.__executor.submit(run_image_scan_task_interupt)
        taskstate.watcher = FutureWatcher(taskstate.future)
        taskstate.watcher.finished.connect(self.__onRunFinished)

    @Slot()
    def __onRunFinished(self):
        assert QThread.currentThread() is self.thread()
        assert self.__state == State.Processing
        assert self.__pendingTask is not None
        assert self.sender() is self.__pendingTask.watcher
        assert self.__pendingTask.future.done()
        task = self.__pendingTask
        self.__pendingTask = None

        try:
            image_meta = task.future.result()
        except Exception as err:
            sys.excepthook(*sys.exc_info())
            state = State.Error
            image_meta = []
            self.error(traceback.format_exc())
        else:
            state = State.Done
            self.error()

        categories = {}

        for imeta in image_meta:
            # derive categories from the path relative to the starting dir
            dirname = os.path.dirname(imeta.path)
            relpath = os.path.relpath(dirname, task.startdir)
            categories[dirname] = relpath

        self._imageMeta = image_meta
        self._imageCategories = categories

        self.__setRuntimeState(state)
        self.commit()

    def cancel(self):
        """
        Cancel current pending task (if any).
        """
        if self.__state == State.Processing:
            assert self.__pendingTask is not None
            self.__pendingTask.cancel()
            self.__pendingTask = None
            self.__setRuntimeState(State.Cancelled)

    @Slot(object)
    def __onReportProgress(self, arg):
        # report on scan progress from a worker thread
        # arg must be a namespace(count: int, lastpath: str)
        assert QThread.currentThread() is self.thread()
        if self.__state == State.Processing:
            self.pathlabel.setText(prettyfypath(arg.lastpath))

    def commit(self):
        """
        Create and commit a Table from the collected image meta data.
        """
        if self._imageMeta:
            categories = self._imageCategories
            if len(categories) > 1:
                cat_var = Orange.data.DiscreteVariable(
                    "category", values=list(sorted(categories.values()))
                )
            else:
                cat_var = None
            # Image name (file basename without the extension)
            imagename_var = Orange.data.StringVariable("image name")
            # Full fs path
            image_var = Orange.data.StringVariable("image")
            image_var.attributes["type"] = "image"
            # file size/width/height
            size_var = Orange.data.ContinuousVariable(
                "size", number_of_decimals=0)
            width_var = Orange.data.ContinuousVariable(
                "width", number_of_decimals=0)
            height_var = Orange.data.ContinuousVariable(
                "height", number_of_decimals=0)
            domain = Orange.data.Domain(
                [], [cat_var] if cat_var is not None else [],
                [imagename_var, image_var, size_var, width_var, height_var]
            )
            cat_data = []
            meta_data = []

            for imgmeta in self._imageMeta:
                if imgmeta.isvalid:
                    if cat_var is not None:
                        category = categories.get(os.path.dirname(imgmeta.path))
                        cat_data.append([cat_var.to_val(category)])
                    else:
                        cat_data.append([])
                    basename = os.path.basename(imgmeta.path)
                    imgname, _ = os.path.splitext(basename)

                    meta_data.append(
                        [imgname, imgmeta.path, imgmeta.size,
                         imgmeta.width, imgmeta.height]
                    )

            cat_data = numpy.array(cat_data, dtype=float)
            meta_data = numpy.array(meta_data, dtype=object)
            table = Orange.data.Table.from_numpy(
                domain, numpy.empty((len(cat_data), 0), dtype=float),
                cat_data, meta_data
            )
        else:
            table = None

        self.send("Data", table)

    def onDeleteWidget(self):
        self.cancel()
        self.__executor.shutdown(wait=True)
コード例 #30
0
class Preferences(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Configuraciones - Edis"))
        self.__sections = []
        # Opacity effect
        self.effect = QGraphicsOpacityEffect()
        self.setGraphicsEffect(self.effect)
        self.animation = QPropertyAnimation(self.effect, "opacity")

        Edis.load_component("preferences", self)
        # Install sections
        #lint:disable
        from src.ui.dialogs.preferences import (environment_configuration,
                                                editor_configuration,
                                                compiler_configuration)
        #lint:enable
        self.load_ui()
        key_escape = QShortcut(QKeySequence(Qt.Key_Escape), self)
        self.connect(key_escape, SIGNAL("activated()"), self.close)
        self.connect(self.btn_cancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btn_guardar, SIGNAL("clicked()"), self._save)

    def install_section(self, obj):
        self.__sections.append(obj)

    def load_ui(self):
        container = QVBoxLayout(self)

        box = QHBoxLayout()
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)
        toolbar = QToolBar()
        toolbar.setToolButtonStyle(3)
        toolbar.setOrientation(Qt.Vertical)
        toolbar.setIconSize(QSize(30, 30))
        toolbar.setObjectName("preferencias")

        environment_section = toolbar.addAction(QIcon(":image/general-pref"),
                                                "Entorno")
        editor_section = toolbar.addAction(QIcon(":image/editor-pref"),
                                           "Editor")
        compiler_section = toolbar.addAction(QIcon(":image/compiler-pref"),
                                             "Compilador")
        self.connect(environment_section, SIGNAL("triggered()"),
                     lambda: self.change_widget(0))
        self.connect(editor_section, SIGNAL("triggered()"),
                     lambda: self.change_widget(1))
        self.connect(compiler_section, SIGNAL("triggered()"),
                     lambda: self.change_widget(2))

        # Set size
        for action in toolbar.actions():
            widget = toolbar.widgetForAction(action)
            widget.setFixedSize(80, 50)

        box.addWidget(toolbar)

        self.stack = QStackedWidget()
        box.addWidget(self.stack)

        # Load sections and subsections
        for section in self.__sections:
            for name, obj in list(section.get_tabs().items()):
                section.install_tab(obj, name)
            self.stack.addWidget(section)

        box_buttons = QHBoxLayout()
        box_buttons.setMargin(10)
        box_buttons.setSpacing(10)
        box_buttons.addStretch(1)
        self.btn_cancel = QPushButton(self.tr("Cancelar"))
        self.btn_guardar = QPushButton(self.tr("Guardar"))
        box_buttons.addWidget(self.btn_cancel)
        box_buttons.addWidget(self.btn_guardar)
        container.addLayout(box)
        container.addLayout(box_buttons)

    def change_widget(self, index):
        if not self.isVisible():
            self.show()
        self.stack.setCurrentIndex(index)

    def _save(self):
        for index in range(self.stack.count()):
            self.stack.widget(index).save()
        self.close()

    def close(self):
        super(Preferences, self).close()
        self.emit(SIGNAL("configurationsClose(PyQt_PyObject)"), self)

    def showEvent(self, event):
        super(Preferences, self).showEvent(event)
        self.animation.setDuration(400)
        self.animation.setStartValue(0)
        self.animation.setEndValue(1)
        self.animation.start()
コード例 #31
0
class EditorContainer(QWidget):

    # Señales
    closedFile = pyqtSignal(int)
    savedFile = pyqtSignal('QString')
    cursorPosition = pyqtSignal(int, int, int)
    updateSymbols = pyqtSignal('PyQt_PyObject')
    fileChanged = pyqtSignal('QString')
    openedFile = pyqtSignal('QString')

    def __init__(self, edis=None):
        QWidget.__init__(self, edis)
        self.setAcceptDrops(True)
        self.box = QVBoxLayout(self)
        self.box.setContentsMargins(0, 0, 0, 0)
        self.box.setSpacing(0)

        # Stacked
        self.stack = QStackedWidget()
        self.box.addWidget(self.stack)

        # Replace widget
        #FIXME: mover esto
        self._replace_widget = replace_widget.ReplaceWidget()
        self._replace_widget.hide()
        self.box.addWidget(self._replace_widget)

        # Editor widget
        self.editor_widget = editor_widget.EditorWidget()

        # Conexiones
        self.connect(self.editor_widget, SIGNAL("saveCurrentFile()"),
                     self.save_file)
        self.connect(self.editor_widget, SIGNAL("fileClosed(int)"),
                     self._file_closed)
        self.connect(self.editor_widget, SIGNAL("recentFile(QStringList)"),
                     self.update_recents_files)
        self.connect(self.editor_widget, SIGNAL("allFilesClosed()"),
                     self.add_start_page)
        self.connect(self.editor_widget, SIGNAL("currentWidgetChanged(int)"),
                     self.change_widget)

        Edis.load_component("principal", self)

    def update_recents_files(self, recents_files):
        """ Actualiza el submenú de archivos recientes """

        menu = Edis.get_component("menu_recent_file")
        self.connect(menu, SIGNAL("triggered(QAction*)"),
                     self._open_recent_file)
        menu.clear()
        for _file in recents_files:
            menu.addAction(_file)

    def _open_recent_file(self, accion):
        """ Abre el archivo desde el menú """

        self.open_file(accion.text())

    def get_recents_files(self):
        """ Devuelve una lista con los archivos recientes en el menú """

        menu = Edis.get_component('menu_recent_file')
        actions = menu.actions()
        recents_files = []
        for filename in actions:
            recents_files.append(filename.text())
        return recents_files

    def _file_closed(self, index):
        self.closedFile.emit(index)

    def _file_modified(self, value):
        self.editor_widget.editor_modified(value)

    def _file_saved(self, filename):
        self.editor_widget.editor_modified(False)
        self.emit(SIGNAL("updateSymbols(QString)"), filename)

    def change_widget(self, index):
        weditor = self.get_active_editor()
        self.editor_widget.combo.combo_file.setCurrentIndex(index)
        if weditor is not None and not weditor.obj_file.is_new:
            self.emit(SIGNAL("updateSymbols(QString)"), weditor.filename)
            self.emit(SIGNAL("fileChanged(QString)"), weditor.filename)
            weditor.setFocus()

    def create_editor(self, obj_file=None, filename=""):
        if obj_file is None:
            obj_file = object_file.EdisFile(filename)
        self.stack.addWidget(self.editor_widget)
        # Quito la página de inicio, si está
        _start_page = self.stack.widget(0)
        if isinstance(_start_page, start_page.StartPage):
            self.remove_widget(_start_page)
            # Detengo el tiimer
            _start_page.timer.stop()
        weditor = editor.Editor(obj_file)
        self.editor_widget.add_widget(weditor)
        self.editor_widget.add_item_combo(obj_file.filename)
        lateral = Edis.get_component("tab_container")
        if not lateral.isVisible():
            lateral.show()

        # Conexiones
        self.connect(obj_file, SIGNAL("fileChanged(PyQt_PyObject)"),
                     self._file_changed)
        self.connect(weditor, SIGNAL("cursorPositionChanged(int, int)"),
                     self.update_cursor)
        self.connect(weditor, SIGNAL("modificationChanged(bool)"),
                     self._file_modified)
        self.connect(weditor, SIGNAL("fileSaved(QString)"),
                     self._file_saved)
        self.connect(weditor, SIGNAL("linesChanged(int)"),
                     self.editor_widget.combo.move_to_symbol)
        self.connect(weditor, SIGNAL("dropEvent(PyQt_PyObject)"),
                     self._drop_editor)
        self.emit(SIGNAL("fileChanged(QString)"), obj_file.filename)

        weditor.setFocus()

        return weditor

    def _file_changed(self, obj_file):
        filename = obj_file.filename
        flags = QMessageBox.Yes
        flags |= QMessageBox.No
        result = QMessageBox.information(self, self.tr("Monitoreo de Archivo"),
                                         self.tr("El archivo <b>{0}</b> fué "
                                         "modificado fuera de Edis. "
                                         "<br><br> Quieres recar"
                                         "garlo?".format(filename)), flags)
        if result == QMessageBox.No:
            return
        self.reload_file(obj_file)

    def reload_file(self, obj_file=None):
        weditor = self.get_active_editor()
        if weditor is None:
            return
        if obj_file is None:
            obj_file = weditor.obj_file
        content = obj_file.read()
        if weditor.is_modified:
            result = QMessageBox.information(self, self.tr(
                "Archivo no guardado!"),
                self.tr("Seguro que quieres recargar el archivo <b>{0}</b>?"
                        "<br><br>"
                        "Se perderán los cambios no guardados.").format(
                            obj_file.filename),
                QMessageBox.Cancel | QMessageBox.Yes)
            if result == QMessageBox.Cancel:
                return
        weditor.setText(content)
        weditor.markerDeleteAll()
        weditor.setModified(False)

    def open_file(self, filename="", cursor_position=None):
        filter_files = "Archivos C(*.cpp *.c);;ASM(*.s);;HEADERS(*.h);;(*.*)"
        if not filename:
            working_directory = os.path.expanduser("~")
            weditor = self.get_active_editor()
            if weditor and weditor.filename:
                working_directory = self._last_folder(weditor.filename)
            filenames = QFileDialog.getOpenFileNames(self,
                                                     self.tr("Abrir Archivo"),
                                                     working_directory,
                                                     filter_files)
        else:
            filenames = [filename]
        try:
            for _file in filenames:
                if not self._is_open(_file):
                    #self.editor_widget.not_open = False
                    # Creo el objeto Edis File
                    obj_file = object_file.EdisFile(_file)
                    content = obj_file.read()
                    weditor = self.create_editor(obj_file, _file)
                    weditor.setText(content)
                    # Cuando se setea el contenido en el editor
                    # se emite la señal textChanged() por lo tanto se agrega
                    # el marker, entonces se procede a borrarlo
                    weditor.markerDelete(0, 3)
                    # FIXME: Cursor position not found
                    #if cursor_position is not None:
                        #line, row = cursor_position
                        #weditor.setCursorPosition(line, row)
                    weditor.setModified(False)
                    obj_file.run_system_watcher()
                else:
                    # Se cambia el índice del stacked
                    # para mostrar el archivo que ya fué abierto
                    for index in range(self.editor_widget.count()):
                        editor = self.editor_widget.widget(index)
                        if editor.filename == _file:
                            self.change_widget(index)

                self.emit(SIGNAL("fileChanged(QString)"), _file)
                self.emit(SIGNAL("openedFile(QString)"), _file)
                self.emit(SIGNAL("updateSymbols(QString)"), _file)
        except EdisIOError as error:
            ERROR('Error al intentar abrir archivo: %s', error)
            QMessageBox.critical(self, self.tr('No se pudo abrir el archivo'),
                                 str(error))
        #self.editor_widget.not_open = True

    def _last_folder(self, path):
        """ Devuelve la última carpeta a la que se accedió """

        return QFileInfo(path).absolutePath()

    def _is_open(self, archivo):
        """
        Retorna True si un archivo ya esta abierto,
        False en caso contrario

        """

        for index in range(self.editor_widget.count()):
            widget = self.editor_widget.widget(index)
            if widget.filename == archivo:
                return True
        return False

    def add_widget(self, widget):
        """ Agrega @widget al stacked """

        self.editor_widget.add_widget(widget)

    def add_start_page(self):
        """ Agrega la página de inicio al stack """

        if settings.get_setting('general/show-start-page'):
            _start_page = start_page.StartPage()
            self.stack.insertWidget(0, _start_page)
            self.stack.setCurrentIndex(0)
        else:
            self.editor_widget.combo.setVisible(False)

    def remove_widget(self, widget):
        """ Elimina el @widget del stacked """

        self.stack.removeWidget(widget)

    def current_widget(self):
        """ Widget actual """

        return self.editor_widget.current_widget()

    def current_index(self):
        return self.editor_widget.current_index()

    def get_active_editor(self):
        """ Devuelve el Editor si el widget actual es una instancia de él,
        de lo contrario devuelve None. """

        widget = self.current_widget()
        if isinstance(widget, editor.Editor):
            return widget
        return None

    def close_file(self):
        self.editor_widget.close_file()

    def close_file_from_project(self, filename):
        #FIXME: revisar
        for index in range(self.editor_widget.count()):
            widget = self.editor_widget.widget(index)
            if widget.filename == filename:
                editor, i = widget, index
        self.editor_widget.close_file_project(editor, i)

    def close_all(self):
        self.editor_widget.close_all()

    def show_selector(self):
        if self.get_active_editor() is not None:
            selector = file_selector.FileSelector(self)
            selector.show()

    def save_file(self, weditor=None):
        if weditor is None:
            weditor = self.get_active_editor()
            if weditor is None:
                return
        if weditor.obj_file.is_new:
            return self.save_file_as(weditor)
        source_code = weditor.text()
        weditor.obj_file.write(source_code)
        weditor.saved()
        # System watcher
        weditor.obj_file.run_system_watcher()
        self.savedFile.emit(weditor.filename)
        return weditor.filename

    def save_file_as(self, weditor=None):
        if weditor is None:
            weditor = self.get_active_editor()
            if weditor is None:
                return
        working_directory = os.path.expanduser("~")
        filename = QFileDialog.getSaveFileName(self, self.tr("Guardar Archivo"),
                                               working_directory)
        if not filename:
            return False
        content = weditor.text()
        weditor.obj_file.write(content, filename)
        weditor.saved()
        self.fileChanged.emit(weditor.filename)
        self.savedFile.emit(weditor.filename)
        return filename

    def save_selected(self, filename):
        for index in range(self.editor_widget.count()):
            if self.editor_widget.widget(index).filename == filename:
                self.save_file(self.editor_widget.widget(index))

    def files_not_saved(self):
        return self.editor_widget.files_not_saved()

    def check_files_not_saved(self):
        return self.editor_widget.check_files_not_saved()

    def find(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            dialog = find_popup.PopupBusqueda(self.get_active_editor())
            dialog.show()

    def find_and_replace(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            if self._replace_widget.isVisible():
                self._replace_widget.hide()
                weditor.setFocus()
            else:
                self._replace_widget.show()

    def action_undo(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.undo()

    def action_redo(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.redo()

    def action_cut(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.cut()

    def action_copy(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.copy()

    def action_paste(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.paste()

    def show_tabs_and_spaces(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            tabs_spaces = settings.get_setting('editor/show-tabs-spaces')
            settings.set_setting('editor/show-tabs-spaces', not tabs_spaces)
            weditor.update_options()

    def show_indentation_guides(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            guides = settings.get_setting('editor/show-guides')
            settings.set_setting('editor/show-guides', not guides)
            weditor.update_options()

    def delete_editor_markers(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.markerDeleteAll()

    def action_zoom_in(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.zoom_in()

    def action_zoom_out(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.zoom_out()

    def action_normal_size(self):
        """ Carga el tamaño por default de la fuente """

        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.zoomTo(0)

    def action_select_all(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.selectAll()

    def opened_files(self):
        return self.editor_widget.opened_files()

    def opened_files_for_selector(self):
        self.index_file_selector = 0
        files = []
        for index in range(self.editor_widget.count()):
            weditor = self.editor_widget.widget(index)
            path = weditor.filename
            if not path:
                path = weditor.display + ' (%s)' % self.index_file_selector
                self.index_file_selector += 1
            files.append(path)
        return files

    def get_open_projects(self):
        tree_projects = Edis.get_lateral("tree_projects")
        return tree_projects.get_open_projects()

    def file_properties(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            dialog = file_properties.FileProperty(weditor, self)
            dialog.show()

    def update_cursor(self, line, row):
        weditor = self.get_active_editor()
        lines = weditor.lines()
        self.editor_widget.combo.update_cursor_position(
            line + 1, row + 1, lines)
        self.cursorPosition.emit(line + 1, row + 1, lines)

    def build_source_code(self):
        output = Edis.get_component("output")
        project = Edis.get_lateral("tree_projects")
        weditor = self.get_active_editor()
        if weditor is not None:
            filename = self.save_file()
            if project.sources:
                output.build((filename, project.sources))
            else:
                if filename:
                    output.build((weditor.filename, []))

    def run_binary(self):
        """ Ejecuta el programa objeto """

        output = Edis.get_component("output")
        output.run()

    def build_and_run(self):
        output = Edis.get_component("output")
        weditor = self.get_active_editor()
        if weditor is not None:
            self.save_file()
            output.build_and_run(weditor.filename)

    def clean_construction(self):
        output = Edis.get_component("output")
        output.clean()

    def stop_program(self):
        output = Edis.get_component("output")
        output.stop()

    def action_comment(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.comment()

    def action_uncomment(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.uncomment()

    def action_indent(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.indent_more()

    def action_unindent(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.indent_less()

    def action_to_lowercase(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.to_lowercase()

    def action_to_uppercase(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.to_uppercase()

    def action_to_title(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.to_title()

    def action_duplicate_line(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.duplicate_line()

    def action_delete_line(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.delete_line()

    def action_move_down(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.move_down()

    def action_move_up(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.move_up()

    def reemplazar_tabs_por_espacios(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.reemplazar_tabs_por_espacios()

    def go_to_line(self, line):
        weditor = self.get_active_editor()
        if weditor is not None:
            weditor.setCursorPosition(line, 0)

    def show_go_to_line(self):
        weditor = self.get_active_editor()
        if weditor is not None:
            dialog = goto_line_widget.GoToLineDialog(weditor)
            dialog.show()

    def add_symbols_combo(self, symbols):
        self.editor_widget.add_symbols(symbols)

    def dragEnterEvent(self, event):
        data = event.mimeData()
        if data.hasText():
            # Se acepta el evento de arrastrado
            event.accept()

    def dropEvent(self, event):
        self._drop_event(event)

    def _drop_editor(self, event):
        self._drop_event(event)

    def _drop_event(self, event):
        data = event.mimeData()
        filename = data.urls()[0].toLocalFile()
        self.open_file(filename)

    def show_settings(self):
        preferences_widget = Edis.get_component("preferences")
        current_widget = self.stack.currentWidget()
        if isinstance(current_widget, preferences_widget.__class__):
            return
        self.connect(preferences_widget,
                     SIGNAL("configurationsClose(PyQt_PyObject)"),
                     lambda widget: self.remove_widget(widget))
        index = self.stack.addWidget(preferences_widget)
        self.stack.setCurrentIndex(index)

    def open_project(self, filename='', edis_project=True):
        if edis_project:
            if not filename:
                filename = QFileDialog.getOpenFileName(self,
                                                       self.tr("Cargar "
                                                       "Proyecto"),
                                                       paths.PROJECT_DIR,
                                                       "Archivo Edis(*.epf)")
                if not filename:
                    return
                project_file = json.load(open(filename))
                project_path = project_file.get('path', '')
            else:
                project_path = os.path.dirname(filename)
        else:
            result = QFileDialog.getExistingDirectory(self,
                                                      self.tr("Selecciona "
                                                      "la carpeta"))
            if not result:
                return
            project_path = result
        project_structure = {}
        filter_files = ['.c', '.h']
        for parent, dirs, files in os.walk(project_path):
            files = [fi for fi in files
                     if os.path.splitext(fi)[-1] in filter_files]
            project_structure[parent] = (files, dirs)
        self.emit(SIGNAL("projectOpened(PyQt_PyObject)"),
                  (project_structure, project_path, edis_project, filename))

    def open_directory(self):
        self.open_project(edis_project=False)

    def create_new_project(self):
        project_creator = new_project.NewProjectDialog(self)
        self.connect(project_creator, SIGNAL("projectReady(PyQt_PyObject)"),
                     self._update_data)
        project_creator.show()

    def _update_data(self, data):
        self.emit(SIGNAL("projectReady(PyQt_PyObject)"), data)

    def opened_projects(self):
        pass

    def code_pasting(self):
        if self.get_active_editor() is not None:
            code = self.get_active_editor().text()
            code_pasting = code_pasting_dialog.CodePastingDialog(self, code)
            code_pasting.exec_()

    def show_snake(self):
        from src.ui.widgets.pyborita import pyborita_widget
        w = pyborita_widget.PyboritaWidget(self)
        toolbar = Edis.get_component("toolbar")
        lateral = Edis.get_component("tab_container")
        status = Edis.get_component("status_bar")
        output = Edis.get_component("output")
        widgets = [toolbar, status, lateral, output]
        for widget in widgets:
            widget.hide()
        self.stack.insertWidget(0, w)
        self.stack.setCurrentIndex(0)
コード例 #32
0
ファイル: Gui.py プロジェクト: hackerj/Treasure-Hunting-Game
class GuiMain(object):
    def __init__(self, data):
        
        self.data = data
        self.loadSave = False
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        #Set size of window and make it non-resizeable
        MainWindow.resize(818, 665)
        MainWindow.setFixedHeight(665)
        MainWindow.setFixedWidth(818)
        
        MainWindow.setWindowTitle("Map Master: Search for the Lost City")
        MainWindow.setWindowIcon(QIcon("icon_medium.ico"))

        #Set window backgrounds
        self.background = QLabel(MainWindow)
        
        
        self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png"))
        self.backgroundPixmapSettings = QPixmap(normpath("images/gameMenuSettings2.png"))
        self.background.setPixmap(self.backgroundPixmapMenu)       
        
        self.background.setGeometry(QtCore.QRect(0, 0, 818, 665))
        
        #Stylesheet settings for labels and buttons
        self.fg = "QLabel {color:black}"
        self.fgb = "QPushButton {color:black}"

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        #Main Menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.startButton = QPushButton(self.menuPage)
        self.startButton.setStyleSheet(self.fgb)
        self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60))
        self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8))
        self.startButton.setObjectName("startButton")
        self.loadButton = QPushButton(self.menuPage)
        self.loadButton.setStyleSheet(self.fgb)
        self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60))
        self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8))
        self.loadButton.setObjectName("loadButton")
        self.settingsButton = QPushButton(self.menuPage)
        self.settingsButton.setStyleSheet(self.fgb)
        self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60))
        self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.settingsButton.setObjectName("settingsButton")
        self.quitButton = QPushButton(self.menuPage)
        self.quitButton.setStyleSheet(self.fgb)
        self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60))
        self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.quitButton.setObjectName("quitButton")
        self.instrButton = QPushButton(self.menuPage)
        self.instrButton.setStyleSheet(self.fgb)
        self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60))
        self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8))
        self.instrButton.setObjectName("instrButton")
        self.stackedWidget.addWidget(self.menuPage)
        
        #Settings page
        self.settingsPage = QWidget()
        self.settingsPage.setObjectName("settingsPage")
        self.volumeSlider = QSlider(self.settingsPage)
        self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30))
        self.volumeSlider.setProperty("value", 50)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.soundLabel = QLabel(self.settingsPage)
        self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.soundLabel.setFont(font)
        self.soundLabel.setStyleSheet(self.fg)
        self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8))
        self.soundLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.soundLabel.setObjectName("soundLabel")
        
        #Quiet Sound Graphic
        self.quietGraphic = QLabel(self.settingsPage)
        self.quietGraphic.setPixmap(QPixmap(normpath("images/speakerQuiet.png")))
        self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80))
        self.quietGraphic.setObjectName("quietGraphic")
        
        #Loud Sound Graphic
        self.loudGraphic = QLabel(self.settingsPage)
        self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png")))
        self.loudGraphic.setEnabled(True)
        self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80))
        self.loudGraphic.setObjectName("loudGraphic")
        
        self.settingsLabel = QLabel(self.settingsPage)
        self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.settingsLabel.setFont(font)
        self.settingsLabel.setStyleSheet(self.fg)
        self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.settingsLabel.setObjectName("settingsLabel")
        self.doneButton = QPushButton(self.settingsPage)
        self.doneButton.setStyleSheet(self.fgb)
        self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton.setObjectName("doneButton")
        self.stackedWidget.addWidget(self.settingsPage)
        
        self.soundManager = Sounds(self.volumeSlider.sliderPosition())
        
        #Main Game page
        self.mainPage = QWidget()
        self.mainPage.setObjectName("mainPage")
        
        #Person View
        self.personView = ViewGraphics(self.mainPage)
        self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500))
        self.personView.setObjectName("personView")
        
        #Map View
        self.mapView = ViewGraphics(self.mainPage)
        self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500))
        self.mapView.setObjectName("mapView")
        
        #ClueView
        self.clueView = QLabel(self.mainPage)
        self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91))
        self.clueView.setObjectName("clueView")
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.clueView.setFont(font)
        self.clueView.setStyleSheet(self.fg)
        
        #Map Toggles
        self.latLongCheck = QCheckBox(self.mainPage)
        self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 97, 41))
        self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n"
        "Longitude", None, QApplication.UnicodeUTF8))
        self.latLongCheck.setObjectName("latLongCheck")

        self.colorCheck = QCheckBox(self.mainPage)
        self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41))
        self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n"
        "Coding", None, QApplication.UnicodeUTF8))
        self.colorCheck.setObjectName("colorCheck")
        self.legendCheck = QCheckBox(self.mainPage)
        self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22))
        self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8))
        self.legendCheck.setObjectName("legendCheck")
        self.searchButton = QPushButton(self.mainPage)
        self.searchButton.setStyleSheet(self.fgb)
        self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 41))
        self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.searchButton.setObjectName("searchButton")
        
        #Score pieces
        self.scoreBox = QLabel(self.mainPage)
        self.scoreBox.setStyleSheet(self.fg)
        self.scoreBox.setGeometry(QtCore.QRect(720, 560, 71, 41))
        self.scoreBox.setObjectName("scoreBox")
        self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8))
        self.scoreLabel = QLabel(self.mainPage)
        self.scoreLabel.setStyleSheet(self.fg)
        self.scoreLabel.setGeometry(QtCore.QRect(660, 570, 51, 17))
        self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8))
        self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreLabel.setObjectName("scoreLabel")
        self.stackedWidget.addWidget(self.mainPage)
        
        #Help page
        self.helpPage = QWidget()
        self.helpPage.setObjectName("helpPage")
        self.HelpLabel = QLabel(self.helpPage)
        self.HelpLabel.setStyleSheet(self.fg)
        self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.HelpLabel.setFont(font)
        self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8))
        self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.HelpLabel.setObjectName("HelpLabel")
        self.wInstr = QLabel(self.helpPage)
        self.wInstr.setStyleSheet(self.fg)
        self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.wInstr.setFont(font)
        self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8))
        self.wInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr.setObjectName("wInstr")
        self.sInstr = QLabel(self.helpPage)
        self.sInstr.setStyleSheet(self.fg)
        self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.sInstr.setFont(font)
        self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8))
        self.sInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr.setObjectName("sInstr")
        self.aInstr = QLabel(self.helpPage)
        self.aInstr.setStyleSheet(self.fg)
        self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.aInstr.setFont(font)
        self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8))
        self.aInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr.setObjectName("aInstr")
        self.dInstr = QLabel(self.helpPage)
        self.dInstr.setStyleSheet(self.fg)
        self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr.setFont(font)
        self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8))
        self.dInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr.setObjectName("dInstr")
        self.wInstr2 = QLabel(self.helpPage)
        self.wInstr2.setStyleSheet(self.fg)
        self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.wInstr2.setFont(font)
        self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8))
        self.wInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr2.setObjectName("wInstr2")
        self.sInstr2 = QLabel(self.helpPage)
        self.sInstr2.setStyleSheet(self.fg)
        self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.sInstr2.setFont(font)
        self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8))
        self.sInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr2.setObjectName("sInstr2")
        self.aInstr2 = QLabel(self.helpPage)
        self.aInstr2.setStyleSheet(self.fg)
        self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.aInstr2.setFont(font)
        self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8))
        self.aInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr2.setObjectName("aInstr2")
        self.dInstr2 = QLabel(self.helpPage)
        self.dInstr2.setStyleSheet(self.fg)
        self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr2.setFont(font)
        self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8))
        self.dInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2.setObjectName("dInstr2")
        self.searchInstr = QPushButton(self.helpPage)
        self.searchInstr.setStyleSheet(self.fgb)
        self.searchInstr.setEnabled(True)
        self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30))
        self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.searchInstr.setAutoDefault(False)
        self.searchInstr.setDefault(False)
        self.searchInstr.setFlat(False)
        self.searchInstr.setObjectName("searchInstr")
        self.dInstr2_2 = QLabel(self.helpPage)
        self.dInstr2_2.setStyleSheet(self.fg)
        self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr2_2.setFont(font)
        self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8))
        self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2_2.setObjectName("dInstr2_2")
        self.doneButton2 = QPushButton(self.helpPage)
        self.doneButton2.setStyleSheet(self.fgb)
        self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton2.setObjectName("doneButton2")
        self.stackedWidget.addWidget(self.helpPage)
        
        #Credits page
        self.creditsPage = QWidget()
        self.creditsPage.setObjectName("creditsPage")
        self.creditsLabel = QLabel(self.creditsPage)
        self.creditsLabel.setStyleSheet(self.fg)
        self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.creditsLabel.setFont(font)
        self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8))
        self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.creditsLabel.setObjectName("creditsLabel")
        self.credits = QLabel(self.creditsPage)
        self.credits.setStyleSheet(self.fg)
        self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.credits.setFont(font)
        self.credits.setText(QApplication.translate("MainWindow", 
        "Gary Lent\n"
        "Grant Stafford\n"
        "Jessie Liu\n"
        "Peter Andrien\n"
        "Nokia (Qt4 framework)\n"
        "Riverbank Computing Ltd (PyQt)\n"
        "Celestial Aeon Project", None, QApplication.UnicodeUTF8))
        self.credits.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.credits.setObjectName("credits")
        self.doneButton3 = QPushButton(self.creditsPage)
        self.doneButton3.setStyleSheet(self.fgb)
        self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton3.setObjectName("doneButton3")
        self.stackedWidget.addWidget(self.creditsPage)
        
        #Story page
        self.storyPage = QWidget()
        self.storyPage.setObjectName("storyPage")
        self.storyLabel = QLabel(self.storyPage)
        self.storyLabel.setStyleSheet(self.fg)
        self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(25)
        self.storyLabel.setFont(font)
        self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently lost my job, but stumbled\n on a clue that may change my life \nforever. I've set off on a quest - a quest\n to find a lost city. I've found a clue,\n and believe there may be more.\n Help me find the lost city.  ", None, QApplication.UnicodeUTF8))
        self.storyLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.storyLabel.setObjectName("storyLabel")
        self.nextButton = QPushButton(self.storyPage)
        self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8))
        self.nextButton.setObjectName("nextButton")
        self.stackedWidget.addWidget(self.storyPage)
        
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #Menu bar
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QMenu(self.menubar)
        self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8))
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.actionSave_Game = QAction(MainWindow)
        self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8))
        self.actionSave_Game.setObjectName("actionSave_Game")
        self.actionCredits = QAction(MainWindow)
        self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8))
        self.actionCredits.setObjectName("actionCredits")
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.actionQuit.setObjectName("actionQuit")
        self.actionSettings = QAction(MainWindow)
        self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setObjectName("actionSettings")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8))
        self.actionHelp.setObjectName("actionHelp")
        self.actionMain_Menu = QAction(MainWindow)
        self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8))
        self.actionMain_Menu.setObjectName("actionMain_Menu")
        self.menuMenu.addAction(self.actionSettings)
        self.menuMenu.addAction(self.actionHelp)
        self.menuMenu.addAction(self.actionSave_Game)
        self.menuMenu.addAction(self.actionCredits)
        self.menuMenu.addAction(self.actionMain_Menu)
        self.menuMenu.addAction(self.actionQuit)
        self.menubar.addAction(self.menuMenu.menuAction())
        

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        #These are the slots and signals to connect buttons to other functions
        self.location = 0
        QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL("triggered()"), MainWindow.close)
        QtCore.QObject.connect(self.quitButton, QtCore.SIGNAL("released()"), MainWindow.close)
        QtCore.QObject.connect(self.settingsButton, QtCore.SIGNAL("released()"), self.setSettings)
        QtCore.QObject.connect(self.actionSettings, QtCore.SIGNAL("triggered()"), self.setSettings)
        QtCore.QObject.connect(self.loadButton, QtCore.SIGNAL("released()"), self.load_file_dialog)
        QtCore.QObject.connect(self.actionSave_Game, QtCore.SIGNAL("triggered()"),self.save_file_dialog)
        QtCore.QObject.connect(self.doneButton, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.startButton, QtCore.SIGNAL("released()"), self.newGame)
        QtCore.QObject.connect(self.actionMain_Menu, QtCore.SIGNAL("triggered()"), self.setMain)
        QtCore.QObject.connect(self.actionHelp, QtCore.SIGNAL("triggered()"), self.setInstructions)
        QtCore.QObject.connect(self.instrButton, QtCore.SIGNAL("released()"), self.setInstructions)
        QtCore.QObject.connect(self.doneButton2, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.doneButton3, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.actionCredits, QtCore.SIGNAL("triggered()"), self.setCredits)
        self.latLongCheck.stateChanged.connect(self.latLong)
        self.colorCheck.stateChanged.connect(self.colorize)
        self.legendCheck.stateChanged.connect(self.legend)
        QtCore.QObject.connect(self.searchButton, QtCore.SIGNAL("released()"), self.doSearch)
        QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL("released()"), self.storyButton)
        self.volumeSlider.sliderMoved.connect(self.setVol)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass

    #Custom signals are here        
    def setSettings(self):
        self.background.setPixmap(self.backgroundPixmapSettings)    
        self.stackedWidget.setCurrentIndex(1)
        
    def setInstructions(self):
        self.background.setPixmap(self.backgroundPixmapSettings)    
        self.stackedWidget.setCurrentIndex(3)
        
    def setCredits(self):
        self.background.setPixmap(self.backgroundPixmapSettings)       
        self.stackedWidget.setCurrentIndex(4)
        
    def goBack(self):
        self.stackedWidget.setCurrentIndex(self.location)
        if self.location == 0:
            self.background.setPixmap(self.backgroundPixmapMenu)
        else:
            None
            #Should be something here later.
        
    def load_file_dialog(self):
        fd = QFileDialog()
        self.filename = fd.getOpenFileName(None, "Load Saved Game", "saves", "MapMaster Save files (*.save)")
        if isfile(self.filename):
            self.loadSaved = True
            self.stackedWidget.setCurrentIndex(2)
            self.location = 2
            self.soundManager.switchSongs(self.location)
            
            
    def save_file_dialog(self):
        filename = QtGui.QFileDialog.getSaveFileName(None,"Save Game", "saves", "MapMaster Save files (*.save)")
        if filename == "":
            print "No file specified!"
        else:
           
            if ".save" in filename:
                self.fname = open(filename, "w")
            else:
                self.fname = open(filename + ".save",'w')
                
            score = str(self.data.score)
            numClues = str(len(self.data.clueStack))
            charX, charY = self.data.character.getCenter()
            whiteSpace = "       "
            toWriteList = whiteSpace + str(charX) + whiteSpace + str(charY) + whiteSpace + numClues + whiteSpace + score
            self.fname.write(toWriteList)     
            self.fname.close()
            
    
        
       
    def newGame(self):
        self.background.setPixmap(self.backgroundPixmapSettings)
        self.filename = None    
        self.stackedWidget.setCurrentIndex(5)
        self.location = 5
        
    def storyButton(self):
    
        self.stackedWidget.setCurrentIndex(2)
        self.location = 2
        self.soundManager.switchSongs(self.location)
       
    def setMain(self):
        self.save_file_dialog()
        self.background.setPixmap(self.backgroundPixmapMenu)
        self.stackedWidget.setCurrentIndex(0)
        self.location = 0
        self.soundManager.switchSongs(self.location)      
           
        
    def latLong(self):
        if self.latLongCheck.isChecked():
            print "Lat/long overlay on"
        else:
            print "Lat/long overlay off"
        self.data.overlays['latLongOverlay'].mViewObj.setVisible(self.latLongCheck.isChecked())
        
    def colorize(self):
        if self.colorCheck.isChecked():
            print "Color overlay on"
        else:
            print "Color overlay off"
        self.data.overlays['colorOverlay'].mViewObj.setVisible(self.colorCheck.isChecked())
        
    def legend(self):
        if self.legendCheck.isChecked():
            print "Legend overlay on"
        else:
            print "Legend overlay off"
        self.data.overlays['legendOverlay'].mViewObj.setVisible(self.legendCheck.isChecked())
    
    def setVol(self):
        self.soundManager.setVolume(self.volumeSlider.sliderPosition())
    
    def doSearch(self):
        searchLandmark(self.data)
コード例 #33
0
ファイル: Report.py プロジェクト: Introsys/fresh
class Ui_WidgetReport(QWidget):

  def __init__(self, parent = None):
    ''' '''
    super(Ui_WidgetReport, self).__init__()
    self.__parentWidget = parent
    self.helper = Ui_WidgetReportHelper(self)

    self.cosmos_cli = CosmosClient()
    
    #TODO: these should be in the app configuration tool
    webhdfs_url = 'http://130.206.80.46:14000/webhdfs/v1'
    auth_url = 'https://130.206.80.46:13000/cosmos-auth/v1'
    local_filepath = os.environ['HOME']+os.sep+'.fresh'+os.sep+'history'
    username = '******'
    password = '******'
    cosmos_user = '******'
    serv = 'NA'
    servpath = 'NA'
    #--------------------------
    
    #Tuple(sensor_type, sensor_name)
    self.sensor_list = [#'sensor', 'sensor_1'), 
                        #('sensor', 'sensor_2'), 
                        #('sensor', 'sensor_3'), 
                        #('sensor', 'sensor_4'), 
                        #('sensor', 'sensor_5'),
                        #('sensor', 'sensor_6'),
                        #('sensor', 'sensor_7'),
                        #('sensor', 'sensor_8'),
                        ('sensor', 'sensor_9'),
                        ('sensor', 'sensor_10')] 
    
    self.entity_list = dict()
    
    self.cosmos_cli.username = username
    self.cosmos_cli.password = password
    self.cosmos_cli.webhdfs_url = webhdfs_url
    self.cosmos_cli.auth_url = auth_url
    self.cosmos_cli.hdfs_username = cosmos_user
    self.cosmos_cli.hdfs_filepath = '/'+serv+'_serv/'+servpath+'_servpath/'
    self.cosmos_cli.local_filepath = local_filepath
    
    self.rep_template = preppy.getModule('reportTemplate.prep')
    
    self.setupUi(self)

  #----------------------------------------------------------------------------

  def setupUi(self, WidgetNetMang):
    
    #This view contains a stacked widget with two pages
    
    #1st page plots the graphic:
    
    layout_plot = QGridLayout()
    self.widget_page_plot = QWidget()
    self.widget_page_plot.setLayout(layout_plot)    
    self.axis = DateAxis(orientation='bottom')
    self.widget_plot = pg.PlotWidget(axisItems={'bottom': self.axis})
    self.combo_zone = QComboBox()
    for (_, sensor) in self.sensor_list: self.combo_zone.addItem(sensor)
    self.combo_sensor = QComboBox()
    self.button_refresh = QPushButton()
    self.button_refresh.setText('Refresh')
    self.button_report = QPushButton()
    self.button_report.setText('Report')
    
    #(QWidget, row, column, rowSpan, columnSpan)
    layout_plot.addWidget(self.widget_plot, 0, 0, 1, 5)      
    layout_plot.addWidget(self.combo_zone, 1, 0, 1, 1)
    layout_plot.addWidget(self.combo_sensor, 1, 1, 1, 1)
    layout_plot.addWidget(self.button_report, 1, 3, 1, 1)
    layout_plot.addWidget(self.button_refresh, 1, 4, 1, 1) 
    
    #2nd page shows the report form:
    
    label_requester_name = QLabel('Name:')
    label_requester_addr = QLabel('Address:')
    label_requester_mail = QLabel('Email:')
    self.edit_requester_name = QLineEdit()
    self.edit_requester_addr = QTextEdit()
    self.edit_requester_addr.setMaximumHeight(80)
    self.edit_requester_mail = QLineEdit()
    layout_requester = QGridLayout()
    layout_requester.addWidget(label_requester_name, 0, 0, 1, 1)
    layout_requester.addWidget(self.edit_requester_name, 0, 1, 4, 1)
    layout_requester.addWidget(label_requester_addr, 4, 0, 1, 1)
    layout_requester.addWidget(self.edit_requester_addr, 4, 1, 4, 1)
    layout_requester.addWidget(label_requester_mail, 8, 0, 1, 1)
    layout_requester.addWidget(self.edit_requester_mail, 8, 1, 4, 1)
    group_requester = QGroupBox('Requester')
    group_requester.setLayout(layout_requester)
    
    label_expert_name = QLabel('Name:')
    label_expert_addr = QLabel('Address:')
    label_expert_mail = QLabel('Email:')
    self.edit_expert_name = QLineEdit()
    self.edit_expert_addr = QTextEdit()
    self.edit_expert_addr.setMaximumHeight(80)
    self.edit_expert_mail = QLineEdit()
    layout_expert = QGridLayout()
    layout_expert.addWidget(label_expert_name, 0, 0, 1, 1)
    layout_expert.addWidget(self.edit_expert_name, 0, 1, 4, 1)
    layout_expert.addWidget(label_expert_addr, 4, 0, 1, 1)
    layout_expert.addWidget(self.edit_expert_addr, 4, 1, 4, 1)
    layout_expert.addWidget(label_expert_mail, 8, 0, 1, 1)
    layout_expert.addWidget(self.edit_expert_mail, 8, 1, 4, 1)
    group_expert = QGroupBox('Expert')
    group_expert.setLayout(layout_expert)
    
    self.edit_observations = QTextEdit()
    self.edit_observations.setMaximumHeight(80)
    layout_observations = QGridLayout()
    layout_observations.addWidget(self.edit_observations, 0, 0, 1, 1)
    group_observations = QGroupBox('Observations')
    group_observations.setLayout(layout_observations)
    
    self.label_plot = QLabel()
    self.label_plot.setFixedSize(700, 300)
    self.label_plot.setScaledContents(True)
    layout_group_plot = QGridLayout()
    layout_group_plot.addWidget(self.label_plot, 0, 0, 1, 1)
    group_plot = QGroupBox('Plot Preview')
    group_plot.setLayout(layout_group_plot)
    
    vertical_line = QFrame()
    vertical_line.setFrameShape(QFrame().VLine)
    vertical_line.setFrameShadow(QFrame().Sunken)
    
    layout_frame_form = QGridLayout()
    layout_frame_form.addWidget(group_requester, 0, 0, 1, 1)
    layout_frame_form.addWidget(vertical_line, 0, 1, 1, 1)
    layout_frame_form.addWidget(group_expert, 0, 2, 1, 1)
    layout_frame_form.addWidget(group_observations, 1, 0, 1, 3)
    layout_frame_form.addWidget(group_plot, 2, 0, 1, 3)
    
    frame_form = QFrame()
    frame_form.setLayout(layout_frame_form)
    
    scroll_area = QScrollArea()
    scroll_area.setWidget(frame_form)
    
    
    self.button_form_back = QPushButton()
    self.button_form_save = QPushButton()
    self.button_form_send = QPushButton()
    self.button_form_back.setText('Back')
    self.button_form_save.setText('Save')
    self.button_form_send.setText('Send')
    
    layout_form = QGridLayout()
    layout_form.addWidget(scroll_area, 0, 0, 1, 5)
    layout_form.addWidget(self.button_form_back, 1, 0, 1, 1)
    layout_form.addWidget(self.button_form_save, 1, 3, 1, 1)
    layout_form.addWidget(self.button_form_send, 1, 4, 1, 1)
    
    self.widget_page_form = QWidget()
    self.widget_page_form.setLayout(layout_form)
    
    self.widget_stacked = QStackedWidget(self)
    self.widget_stacked.addWidget(self.widget_page_plot)
    self.widget_stacked.addWidget(self.widget_page_form)
    
    layout_main = QGridLayout()
    layout_main.addWidget(self.widget_stacked)
    self.setLayout(layout_main)
    
    #---
    
    self.combo_zone.currentIndexChanged['QString'].\
      connect(self.handle_combo_zone_changed)
    self.combo_sensor.currentIndexChanged['QString'].\
      connect(self.handle_combo_sensor_changed)
    self.button_refresh.clicked.\
      connect(self.handle_button_refresh_clicked)
    self.button_report.clicked.\
      connect(self.handle_button_report_clicked)
    self.button_form_back.clicked.\
      connect(self.handle_button_form_back_clicked)
    self.button_form_save.clicked.\
      connect(self.handle_button_form_save_clicked)
    self.button_form_send.clicked.\
      connect(self.handle_button_form_send_clicked)
  
  #----------------------------------------------------------------------------
  
  @pyqtSlot('QString')
  def handle_combo_zone_changed(self, text):
    
    if str(text) == '':
      return
    
    self.combo_sensor.blockSignals(True)
    self.combo_sensor.clear()
    for e in self.entity_list[str(text)]:
      self.combo_sensor.addItem(e)
    self.combo_sensor.setCurrentIndex(0)
    self.combo_sensor.blockSignals(False)
    self.combo_sensor.currentIndexChanged['QString'].emit(self.combo_sensor.currentText())
  
  #----------------------------------------------------------------------------
  
  @pyqtSlot('QString')
  def handle_combo_sensor_changed(self, text):
    
    if str(text) == '':
      return
    
    print str(text)
    
    dates = []
    values = []
    
    found = False
    for (s_type,s_name) in self.sensor_list:
      if s_name == str(self.combo_zone.currentText()):
        self.cosmos_cli.local_filename = s_name+'_'+s_type+'.txt'
        found = True
        break;
    
    if not found:
      return
    
    self.cosmos_cli.readHistoryFromFile()
    
    for s in self.cosmos_cli.history.split('\n'):
      try:
        j = json.loads(s)
        try:
          value = j[str(text)]
          date = j['recvTime'].split('.')[0]
          values.append(float(value))
          print date
          print time.mktime(datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S").timetuple())
          dates.append(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S").timetuple()))
          #dates.append(date.split('T')[0]+'\n'+(date.split('T')[1]).split('.')[0])
        except:
          pass
      except:
        pass

    self.widget_plot.clear()
    #xdates = dict(zip(range(len(dates)),dates))
    #self.axis.set_dict(xdates)
    #self.widget_plot.plot(x=xdates.keys(), y=values, symbol='o')
    self.widget_plot.plot(x=dates, y=values, symbol='o')  
  #----------------------------------------------------------------------------
  
  
  
  @pyqtSlot()
  def handle_button_refresh_clicked(self):
    
    """get the files from cosmos and stores them locally"""
    
    
    self.entity_list.clear()
    
    for (s_type, s_name) in self.sensor_list:
      self.entity_list[s_name] = dict()
      self.cosmos_cli.hdfs_filename = s_name+'_'+s_type+'/'+s_name+'_'+s_type+'.txt'
      self.cosmos_cli.local_filename = s_name+'_'+s_type+'.txt'
      try:
        self.cosmos_cli.getFileContent()
      except NameError as e:
        print e
        return
      try:
        self.cosmos_cli.writeHistoryToFile()
      except NameError as e:
        print e
        return
      
      self.entity_list[s_name].clear()
      for s in self.cosmos_cli.history.split('\n'):
        try:
          for k in json.loads(s).keys():
            if 'md' not in k and 'recv' not in k and 'RTC' not in k:
              self.entity_list[s_name][k] = ''
        except Exception as e:
          print e
          pass
    
    self.combo_zone.clear()
    self.combo_sensor.clear()
    
    for e in self.entity_list:
      self.combo_zone.addItem(e)
      "print self.entity_list[e]"

    #self.combo_sensor.clear()
    #for e in self.entity_list:
    #  self.combo_sensor.addItem(e)

    print "refresh"
    
  #============================================================================

  @pyqtSlot()
  def handle_button_report_clicked(self):
    
    try:
      exporter = pyqtgraph.exporters.ImageExporter(self.widget_plot.plotItem)
      exporter.export(self.cosmos_cli.local_filepath + '/plot.png')
      self.label_plot.setPixmap(QPixmap(self.cosmos_cli.local_filepath + '/plot.png'))
    except Exception as e:
      print e
      return
    
    self.widget_stacked.setCurrentIndex(1)

  #============================================================================

  @pyqtSlot()
  def handle_button_form_back_clicked(self):
    
    self.widget_stacked.setCurrentIndex(0)
  
  #============================================================================

  @pyqtSlot()
  def handle_button_form_save_clicked(self):
 
    rmlText = self.rep_template.get(str(self.combo_zone.currentText())+' - '+
                                    str(self.combo_sensor.currentText()),
                                    datetime.datetime.now().strftime("%Y-%m-%d"),
                                    str(self.edit_requester_name.text()),
                                    str(self.edit_requester_addr.toPlainText()),
                                    '',
                                    str(self.edit_expert_name.text()),
                                    str(self.edit_expert_addr.toPlainText()),
                                    '',
                                    str(self.edit_observations.toPlainText()),
                                    self.cosmos_cli.local_filepath+'/plot.png')
    pdf = rml2pdf.parseString(rmlText)
    
    filename = QFileDialog().getSaveFileName()
    
    if str(filename == ''): return
    
    with open(str(filename), 'w+') as pdfFile:
      pdfFile.write(pdf.read())
 
  #============================================================================

  @pyqtSlot()
  def handle_button_form_send_clicked(self):
    
    rmlText = self.rep_template.get(str(self.combo_zone.currentText())+' - '+
                                    str(self.combo_sensor.currentText()),
                                    datetime.datetime.now().strftime("%Y-%m-%d"),
                                    str(self.edit_requester_name.text()),
                                    str(self.edit_requester_addr.toPlainText()),
                                    str(self.edit_requester_mail.text()),
                                    str(self.edit_expert_name.text()),
                                    str(self.edit_expert_addr.toPlainText()),
                                    str(self.edit_expert_mail.text()),
                                    str(self.edit_observations.toPlainText()),
                                    self.cosmos_cli.local_filepath+'/plot.png')
    pdf = rml2pdf.parseString(rmlText)
    
    with open(self.cosmos_cli.local_filepath+'/rmlReport.pdf', 'w+') as pdfFile:
      pdfFile.write(pdf.read())
    
    time.sleep(1)
    
    (password, ok) = QInputDialog().getText(self, 'password', 'password', mode=QLineEdit.Password)
    
    print str(self.edit_requester_mail.text())
    print str(password)
    
    email_cli = EmailClient(username = str(self.edit_requester_mail.text()),
                            password = str(password))
    
    email_cli.sendEmail(from_addr=str(self.edit_requester_mail.text()),
                        to_addr=str(self.edit_expert_mail.text()),
                        mail_subject='[FRESH Expert Service] Request for Advice',
                        mail_body=str(self.edit_observations.toPlainText()),
                        attachment=self.cosmos_cli.local_filepath+'/rmlReport.pdf')
コード例 #34
0
class QgsTextAnnotationDialog(QDialog):
    def __init__(self, item):
        QDialog.__init__(self)
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName(("gridLayout"))
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName(("horizontalLayout"))
        self.mFontComboBox = QFontComboBox(self)
        self.mFontComboBox.setObjectName(("mFontComboBox"))
        self.horizontalLayout.addWidget(self.mFontComboBox)
        spacerItem = QSpacerItem(38, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.mFontSizeSpinBox = QSpinBox(self)
        self.mFontSizeSpinBox.setObjectName(("mFontSizeSpinBox"))
        self.horizontalLayout.addWidget(self.mFontSizeSpinBox)
        self.mBoldPushButton = QPushButton(self)
        self.mBoldPushButton.setMinimumSize(QSize(50, 0))
        self.mBoldPushButton.setCheckable(True)
        self.mBoldPushButton.setObjectName(("mBoldPushButton"))
        self.horizontalLayout.addWidget(self.mBoldPushButton)
        self.mItalicsPushButton = QPushButton(self)
        self.mItalicsPushButton.setMinimumSize(QSize(50, 0))
        self.mItalicsPushButton.setCheckable(True)
        self.mItalicsPushButton.setObjectName(("mItalicsPushButton"))
        self.horizontalLayout.addWidget(self.mItalicsPushButton)
        self.mFontColorButton = QgsColorButton(self)
        self.mFontColorButton.setText((""))
        self.mFontColorButton.setAutoDefault(False)
        self.mFontColorButton.setObjectName(("mFontColorButton"))
        self.horizontalLayout.addWidget(self.mFontColorButton)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.mButtonBox = QDialogButtonBox(self)
        self.mButtonBox.setOrientation(Qt.Horizontal)
        self.mButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.mButtonBox.setObjectName(("mButtonBox"))
        self.gridLayout.addWidget(self.mButtonBox, 3, 0, 1, 1)
        self.mTextEdit = QTextEdit(self)
        self.mTextEdit.setObjectName(("mTextEdit"))
        self.gridLayout.addWidget(self.mTextEdit, 1, 0, 1, 1)
        self.mStackedWidget = QStackedWidget(self)
        self.mStackedWidget.setObjectName(("mStackedWidget"))
        self.page = QWidget()
        self.page.setObjectName(("page"))
        self.mStackedWidget.addWidget(self.page)
        self.page_2 = QWidget()
        self.page_2.setObjectName(("page_2"))
        self.mStackedWidget.addWidget(self.page_2)
        self.gridLayout.addWidget(self.mStackedWidget, 2, 0, 1, 1)
        self.setLayout(self.gridLayout)
        
        self.mStackedWidget.setCurrentIndex(0)
        QObject.connect(self.mButtonBox, SIGNAL(("accepted()")), self.accept)
        QObject.connect(self.mButtonBox, SIGNAL(("rejected()")), self.reject)
        
        self.setTabOrder(self.mFontComboBox, self.mFontSizeSpinBox)
        self.setTabOrder(self.mFontSizeSpinBox, self.mBoldPushButton)
        self.setTabOrder(self.mBoldPushButton, self.mItalicsPushButton)
        self.setTabOrder(self.mItalicsPushButton, self.mFontColorButton)
        self.setTabOrder(self.mFontColorButton, self.mTextEdit)
        self.setTabOrder(self.mTextEdit, self.mButtonBox)
        
        self.setWindowTitle("Annotation text")
        self.mBoldPushButton.setText("B")
        self.mItalicsPushButton.setText("I")
        
        self.mTextDocument = None
        self.mItem = item
        self.mEmbeddedWidget = QgsAnnotationWidget(self, self.mItem )
        self.mEmbeddedWidget.show()
        self.mStackedWidget.addWidget( self.mEmbeddedWidget )
        self.mStackedWidget.setCurrentWidget( self.mEmbeddedWidget )
        if ( self.mItem != None ):
            self.mTextDocument = self.mItem.document()
            self.mTextEdit.setDocument( self.mTextDocument )
        self.mFontColorButton.setColorDialogTitle(  "Select font color"  )
        self.mFontColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel )
        self.setCurrentFontPropertiesToGui()
        QObject.connect( self.mButtonBox, SIGNAL("accepted()"), self.applyTextToItem)
#         QObject.connect( self.mFontComboBox, SIGNAL( "currentFontChanged(QFont())"), self.changeCurrentFormat)
        self.mFontComboBox.currentFontChanged.connect(self.changeCurrentFormat)
        QObject.connect( self.mFontSizeSpinBox, SIGNAL( "valueChanged( int )" ), self.changeCurrentFormat ) 
        QObject.connect( self.mBoldPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mItalicsPushButton, SIGNAL( "toggled( bool )" ), self.changeCurrentFormat)
        QObject.connect( self.mTextEdit, SIGNAL( "cursorPositionChanged()" ), self.setCurrentFontPropertiesToGui )
        
#         QObject.connect( self.mButtonBox, SIGNAL( "accepted()" ), self.applySettingsToItem)
        deleteButton = QPushButton( "Delete" )
        QObject.connect( deleteButton, SIGNAL( "clicked()" ), self.deleteItem )
        self.mButtonBox.addButton( deleteButton, QDialogButtonBox.RejectRole )
    def applyTextToItem(self):
        if ( self.mItem  != None and self.mTextDocument !=None ):
            if ( self.mEmbeddedWidget != None):
                self.mEmbeddedWidget.apply()
            self.mItem.setDocument( self.mTextDocument )
            self.mItem.update()
    def changeCurrentFormat(self):
        newFont = QFont()
        newFont.setFamily( self.mFontComboBox.currentFont().family() )
        #bold
        if ( self.mBoldPushButton.isChecked() ):
            newFont.setBold( True )
        else:
            newFont.setBold( False )
        #italic
        if ( self.mItalicsPushButton.isChecked() ):
            newFont.setItalic( True )
        else:
            newFont.setItalic( False )
        #size
        newFont.setPointSize( self.mFontSizeSpinBox.value() )
        self.mTextEdit.setCurrentFont( newFont )
        #color
        self.mTextEdit.setTextColor( self.mFontColorButton.color() )
        
    def on_mFontColorButton_colorChanged(self, color ):
        self.changeCurrentFormat()
    def setCurrentFontPropertiesToGui(self):
        self.blockAllSignals( True )
        currentFont = self.mTextEdit.currentFont()
        self.mFontComboBox.setCurrentFont( currentFont )
        self.mFontSizeSpinBox.setValue( currentFont.pointSize() )
        self.mBoldPushButton.setChecked( currentFont.bold() )
        self.mItalicsPushButton.setChecked( currentFont.italic() )
        self.mFontColorButton.setColor( self.mTextEdit.textColor() )
        self.blockAllSignals( False )
        
    def blockAllSignals(self, block ):
        self.mFontComboBox.blockSignals( block )
        self.mFontSizeSpinBox.blockSignals( block )
        self.mBoldPushButton.blockSignals( block )
        self.mItalicsPushButton.blockSignals( block )
        self.mFontColorButton.blockSignals( block )
    
    def deleteItem(self):
        scene = self.mItem.scene()
        if ( scene != None ):
            scene.removeItem( self.mItem )
        self.mItem = None
コード例 #35
0
ファイル: table_widget.py プロジェクト: papablopo07/pireal
class TableWidget(QWidget):

    def __init__(self):
        super(TableWidget, self).__init__()

        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)

        self.relations = {}

        # Stack
        self.stacked = QStackedWidget()
        vbox.addWidget(self.stacked)

    def count(self):
        return self.stacked.count()

    def add_data_base(self, data):
        lateral = Pireal.get_service("lateral")
        rel = None
        for part in data.split('@'):
            for e, line in enumerate(part.splitlines()):
                if e == 0:
                    name = line.split(':')[0]
                    rel = relation.Relation()
                    rel.fields = line.split(':')[-1].split(',')
                else:
                    rel.insert(line.split(','))
            if rel is not None:
                table = Table()
                table.setRowCount(1)
                table.setColumnCount(0)
                self.relations[name] = rel

                for _tuple in rel.content:
                    row = table.rowCount()
                    table.setColumnCount(len(rel.fields))
                    for column, text in enumerate(_tuple):
                        item = Item()
                        item.setText(text)
                        table.setItem(row - 1, column, item)
                    table.insertRow(row)
                table.setHorizontalHeaderLabels(rel.fields)
                self.stacked.addWidget(table)
                table.removeRow(table.rowCount() - 1)
                lateral.add_item_list([name])

    def load_relation(self, filenames):
        lateral = Pireal.get_service("lateral")
        for filename in filenames:
            rel = relation.Relation(filename)
            rel_name = file_manager.get_basename(filename)
            self.relations[rel_name] = rel
            table = Table()
            table.setRowCount(1)
            table.setColumnCount(0)

            for _tuple in rel.content:
                row = table.rowCount()
                table.setColumnCount(len(rel.fields))
                for column, text in enumerate(_tuple):
                    item = Item()
                    item.setText(text)
                    table.setItem(row - 1, column, item)
                table.insertRow(row)
            table.removeRow(table.rowCount() - 1)
            table.setHorizontalHeaderLabels(rel.fields)
            self.stacked.addWidget(table)
            lateral.add_item_list([rel_name])

    def add_table(self, rows, columns, name, data, fields):
        table = Table()
        table.setRowCount(rows)
        table.setColumnCount(columns)
        table.setHorizontalHeaderLabels(fields)

        for k, v in list(data.items()):
            item = QTableWidgetItem()
            item.setText(v)
            table.setItem(k[0] - 1, k[1], item)

        self.stacked.addWidget(table)
        self.stacked.setCurrentIndex(self.stacked.count() - 1)
        lateral = Pireal.get_service("lateral")
        lateral.add_item_list([name])

    def add_new_table(self, rel, name):
        import itertools

        table = Table()
        table.setRowCount(0)
        table.setColumnCount(0)

        data = itertools.chain([rel.fields], rel.content)

        for row_data in data:
            row = table.rowCount()
            table.setColumnCount(len(row_data))
            for col, text in enumerate(row_data):
                item = QTableWidgetItem()
                item.setText(text)
                if row == 0:
                    table.setHorizontalHeaderItem(col, item)
                else:
                    table.setItem(row - 1, col, item)
            table.insertRow(row)
        table.removeRow(table.rowCount() - 1)
        self.stacked.addWidget(table)
        self.stacked.setCurrentIndex(self.stacked.count() - 1)
        lateral = Pireal.get_service("lateral")
        lateral.add_item_list([name])

    def remove_table(self, index):
        table = self.stacked.widget(index)
        self.stacked.removeWidget(table)

    def add_table_from_rdb_content(self, content):
        lateral = Pireal.get_service("lateral")
        lateral.show()
        for line in content.splitlines():
            if line.startswith('@'):
                table = Table()
                name = line.split(':')[0][1:]
                lateral.add_item_list([name])
                fields = line.split(':')[-1].split(',')[:-1]
                table.setColumnCount(len(fields))
                table.setHorizontalHeaderLabels(fields)
                self.stacked.addWidget(table)
            else:
                row = table.rowCount()
                for e, i in enumerate(line.split(',')):
                    item = QTableWidgetItem()
                    item.setText(i)
                    table.setItem(row - 1, e, item)
                table.insertRow(row)
コード例 #36
0
ファイル: player.py プロジェクト: jmechnich/qmpc
    def initGUI(self):
        self.setWindowTitle(QApplication.applicationName())
        self.fmt = QFontMetrics(QFont())
        layout = QVBoxLayout()
        
        toplayout = QHBoxLayout()
        currentLayout = QGridLayout()
        currentLayout.setContentsMargins(0,20,0,20)
        currentLayout.setHorizontalSpacing(100)
        currentLayout.setVerticalSpacing(20)
        # current song information
        currentLayout.addWidget(QLabel("<b>Artist</b>"),1,0)
        self.artist = QLabel()
        currentLayout.addWidget(self.artist,1,1)
        currentLayout.addWidget(QLabel("<b>Title</b>"),2,0)
        self.title  = QLabel()
        currentLayout.addWidget(self.title,2,1)
        currentLayout.addWidget(QLabel("<b>Albumartist</b>"),3,0)
        self.albumartist = QLabel()
        currentLayout.addWidget(self.albumartist,3,1)
        currentLayout.addWidget(QLabel("<b>Album</b>"),4,0)
        self.album  = QLabel()
        currentLayout.addWidget(self.album,4,1)
        # playlist and song position
        self.playlistposition = QLabel()
        currentLayout.addWidget(self.playlistposition,5,0)
        poslayout = QHBoxLayout()
        poslayout.setSpacing(10)
        self.time = QLabel("00:00")
        poslayout.addWidget(self.time)
        self.position = QSlider(Qt.Horizontal)
        self.position.setTracking(False)
        self.position.setSingleStep(10)
        self.position.sliderReleased.connect( self.seek)
        self.position.sliderMoved.connect(
            lambda x: self.time.setText(self.mpd.timeString(x)))
        poslayout.addWidget(self.position)
        self.length = QLabel("00:00")
        poslayout.addWidget(self.length)
        currentLayout.addLayout(poslayout,5,1)
        toplayout.addLayout(currentLayout)
        layout.addLayout(toplayout)
        layout.addStretch(1)
        
        self.settingsWidget = QMenu()
        self.consumeBtn = self.settingsWidget.addAction("Consume")
        self.consumeBtn.setCheckable(True)
        self.consumeBtn.triggered.connect( lambda x: self.mpd.consume(int(x)))
        self.singleBtn  = self.settingsWidget.addAction("Single")
        self.singleBtn.setCheckable(True)
        self.singleBtn.triggered.connect( lambda x: self.mpd.single(int(x)))
        
        toolLayout = QHBoxLayout()
        self.settingsBtn = QToolButton()
        self.settingsBtn.setFixedSize(64,64)
        self.settingsBtn.setIcon( self.ih.settingsButton)
        self.settingsBtn.clicked.connect(self.showAdditionalControls)
        toolLayout.addWidget(self.settingsBtn)

        
        toolWidget = QStackedWidget()
        transpWidget = QWidget()
        transpLayout = QHBoxLayout()
        self.prevBtn = self.createButton(
            self.ih.prevButton, self.ih.prevButtonPressed)
        self.prevBtn.clicked.connect( lambda x: self.mpd.previous())
        transpLayout.addWidget(self.prevBtn)
        self.playBtn = self.createCheckButton(
            self.ih.playButton, self.ih.pauseButton)
        self.playBtn.clicked.connect( self.playPressed)
        transpLayout.addWidget(self.playBtn)
        self.stopBtn = self.createButton(
            self.ih.stopButton, self.ih.stopButtonPressed)
        self.stopBtn.clicked.connect( lambda x: self.mpd.stop())
        transpLayout.addWidget(self.stopBtn)
        self.nextBtn = self.createButton(
            self.ih.nextButton, self.ih.nextButtonPressed)
        self.nextBtn.clicked.connect( lambda x: self.mpd.next())
        transpLayout.addWidget(self.nextBtn)
        self.shuffleBtn = self.createCheckButton(
            self.ih.shuffleButton, self.ih.shuffleButtonPressed)
        self.shuffleBtn.toggled.connect(
            lambda x: self.mpd.random(1) if x else self.mpd.random(0))
        transpLayout.addWidget(self.shuffleBtn)
        self.repeatBtn = self.createCheckButton(
            self.ih.repeatButton, self.ih.repeatButtonPressed)
        self.repeatBtn.toggled.connect(
            lambda x: self.mpd.repeat(1) if x else self.mpd.repeat(0))
        transpLayout.addWidget(self.repeatBtn)
        transpLayout.addSpacing(64)
        transpWidget.setLayout(transpLayout)
        toolWidget.addWidget( transpWidget)
        
        self.volume = QSlider(Qt.Horizontal)
        self.volume.valueChanged.connect(self.mpd.setvol)
        toolWidget.addWidget(self.volume)
        
        toolLayout.addWidget(toolWidget)
        self.volumeBtn = QToolButton()
        self.volumeBtn.setFixedSize(64,64)
        self.volumeBtn.setCheckable(True)
        self.volumeBtn.setIcon( self.ih.volumeButton)
        self.volumeBtn.toggled.connect(
            lambda x: toolWidget.setCurrentIndex(x))
        toolLayout.addWidget(self.volumeBtn)
        layout.addLayout(toolLayout)
        self.setLayout(layout)
コード例 #37
0
ファイル: roboter.py プロジェクト: syedemz/AdminShell2
class DigitalerRoboter(QWidget):

    'Signale definieren'
    signal_animation_aktiv = Signal(bool)
    signal_koordinaten = Signal(int, int, int)

    'Methode __init__ '

    def __init__(self, parent=None):

        'Vererbung aller Attribute und Methoden von QWidget'
        super(DigitalerRoboter, self).__init__(parent)

        'Zeichenflächen mit Koordinatensystem instanziieren'

        'Hintergrundfarbe der Zeichenflächen festlegen'
        farbe_zeichenflaeche = '#b5afb5'

        'Zeichenfläche mit Koordinatensystem instanziieren - Draufsicht'
        self.zeichenflaeche_draufsicht = QPlotWidget()

        #Hintergrundfarbe festlegen
        self.zeichenflaeche_draufsicht.figure.set_facecolor( \
        farbe_zeichenflaeche)

        #Koordinatensystem an die Zeichenfläche anpassen
        self.zeichenflaeche_draufsicht.figure.tight_layout()

        #gleiche Skalierung der Achsen des Koordinatensystems
        self.zeichenflaeche_draufsicht.axes.set_aspect('equal')

        #Grenzen des Koordinatensystems festlegen
        self.zeichenflaeche_draufsicht.axes.set_xlim([-650, 650])
        self.zeichenflaeche_draufsicht.axes.set_ylim([-225, 625])

        #Achsen des Koordinatensystems und Beschriftung ausblenden
        self.zeichenflaeche_draufsicht.axes.axis('off')

        #Zeichenfläche deaktivieren
        self.zeichenflaeche_draufsicht.setEnabled(False)

        'Zeichenfläche mit Koordinatensystem instanziieren - Seitenansicht'
        self.zeichenflaeche_seitenansicht = QPlotWidget()

        #Hintergrundfarbe festlegen
        self.zeichenflaeche_seitenansicht.figure.set_facecolor( \
        farbe_zeichenflaeche)

        #Koordinatensystem an die Zeichenfläche anpassen
        self.zeichenflaeche_seitenansicht.figure.tight_layout()

        #gleiche Skalierung der Achsen des Koordinatensystems
        self.zeichenflaeche_seitenansicht.axes.set_aspect('equal')

        #Grenzen des Koordinatensystems festlegen
        self.zeichenflaeche_seitenansicht.axes.set_xlim(-250, 650)
        self.zeichenflaeche_seitenansicht.axes.set_ylim([-225, 625])

        #Achsen des Koordinatensystems und Beschriftung ausblenden
        self.zeichenflaeche_seitenansicht.axes.axis('off')

        #Zeichenfläche deaktivieren
        self.zeichenflaeche_seitenansicht.setEnabled(False)

        'Zeichenfläche mit Koordinatensystem instanziieren - Greifer'
        self.zeichenflaeche_ansicht_greifer = QPlotWidget()

        #Hintergrundfarbe festlegen
        self.zeichenflaeche_ansicht_greifer.figure.set_facecolor( \
        farbe_zeichenflaeche)

        #Koordinatensystem an die Zeichenfläche anpassen
        self.zeichenflaeche_ansicht_greifer.figure.tight_layout()

        #gleiche Skalierung der Achsen des Koordinatensystems
        self.zeichenflaeche_ansicht_greifer.axes.set_aspect('equal')

        #Grenzen des Koordinatensystems festlegen
        self.zeichenflaeche_ansicht_greifer.axes.set_xlim([-350, 350])
        self.zeichenflaeche_ansicht_greifer.axes.set_ylim([-350, 350])

        #Achsen des Koordinatensystems und Beschriftung ausblenden
        self.zeichenflaeche_ansicht_greifer.axes.axis('off')

        #Zeichenfläche deaktivieren
        self.zeichenflaeche_ansicht_greifer.setEnabled(False)
        '''Die Zeichenflächen werden gestapelt, da immer nur eine
        Ansicht angezeigt werden kann.'''

        'QStackedWidget-Objekt instanziieren'
        self.ansicht = QStackedWidget()
        #Draufischt: CurrentIndex(0)
        self.ansicht.addWidget(self.zeichenflaeche_draufsicht)
        #Seitenansicht: CurrentIndex(1)
        self.ansicht.addWidget(self.zeichenflaeche_seitenansicht)
        #Greifer: CurrentIndex(2)
        self.ansicht.addWidget(self.zeichenflaeche_ansicht_greifer)

        'Layout festlegen'
        layout = QHBoxLayout()
        layout.addWidget(self.ansicht)
        self.setLayout(layout)
        '''Lage und Orientierung des Werkzeugkoordinatensystem sowie die
        Öffnungsradien des Greifers in Ausgangsposition laden'''

        'Denavit-Hartenberg-Parameter laden'
        (d1, d2, d3, d4, d5, a1, a2, a3, a4, a5, \
        alpha1, alpha2, alpha3, alpha4, alpha5) = denavit_hartenberg()
        self.a3 = a3

        'Orientierung des Werkzeugkoordinatensystems laden'
        self.x5in0, self.y5in0, self.z5in0 = \
        self.orientierung_laden('programmEin')

        'Lagevektor des Werkzeugkoordinatensystems laden'
        self.P05in0 = self.lage_laden('programmEin')

        'Öffnungsradien des Greifers laden'
        self.r6, self.r7 = self.greifer_laden('programmEin')

        'Mittelpunktkoordinaten der Punkte berechnen'
        self.modellrechnung()

        'Methode animation_anzeigen aufrufen'
        self.animation_anzeigen()

    '''Methode animation_anzeigen - Die Methode dient dem Instanziieren
    der drei Ansichten. Jeder Animation wird die entsprechenden Zeichen-
    fläche als Parent und die Mittelpunktkoordinaten der Circle-Objekte
    übergeben. Weiter werden die Signale mit den Slots verbunden.'''

    def animation_anzeigen(self):

        'DraufsichtRoboter-Objekt instanziieren'
        self.animation_draufsicht = DraufsichtRoboter( \
        self.zeichenflaeche_draufsicht, \
        self.xP1in0, self.yP1in0, self.xP2in0, self.yP2in0, \
        self.xP4in0, self.yP4in0, self.xP5in0, self.yP5in0)

        'Signal und Slot verbinden'
        self.animation_draufsicht.xy_neu.connect( \
        self.koordinaten_draufsicht)

        'SeitenansichtRoboter-Objekt instanziieren'
        self.animation_seitenansicht = SeitenansichtRoboter( \
        self.zeichenflaeche_seitenansicht, \
        self.xP1in1, self.yP1in1, self.xP2in1, self.yP2in1, self.xP3in1, \
        self.yP3in1, self.xP4in1, self.yP4in1, self.xP5in1, self.yP5in1)

        'Signal und Slot verbinden'
        self.animation_seitenansicht.xy_neu.connect( \
        self.koordinaten_seitenansicht)

        'RueckansichtGreifer-Objekt instanziieren'
        self.animation_greifer = RueckansichtGreifer( \
        self.zeichenflaeche_ansicht_greifer, \
        self.xP6in4z, self.yP6in4z, self.xP7in4z, self.yP7in4z)

        'Signal und Slot verbinden'
        self.animation_greifer.xy_neu.connect( \
        self.koordinaten_greifer)

    '''Methode animation_aktivieren - Die Methode aktiviert die Zeichen-
    flächen. In Folge kann der digitale Roboter durch Verschieben der 
    Punkte bewegt werden. Die bewegbaren Punkte erscheinen in Farbe.'''

    def animation_aktivieren(self, b):

        'Zeichenflächen aktivieren'
        self.zeichenflaeche_draufsicht.setEnabled(b)
        self.zeichenflaeche_seitenansicht.setEnabled(b)
        self.zeichenflaeche_ansicht_greifer.setEnabled(b)

        'Einfärben der bewegbaren Punkte'
        self.animation_draufsicht.punkte_faerben(b)
        self.animation_seitenansicht.punkte_faerben(b)
        self.animation_greifer.punkte_faerben(b)

    '''Methode animation_aktualisieren - Die Methode ermöglicht das
    Aktualisieren des digitalen Roboters. Dabei sind die Lage (Zeilenvektor
    vom Format 1x3) und Orientierung (Zeilenvektor Format 1x9) des Werkzeug-
    koordinatensystems in 0-Koordinaten sowie der Öffnungsradius des Greifers 
    (Zeilenvektor vom Format 1x1) zu übergeben.'''

    def animation_aktualisieren(self, orientierung, lage, greifer):

        'Orientierung des Werkzeugkoordinatensystems'

        'Einheitsvektoren zuordnen'
        x5in0, y5in0, z5in0 = hsplit(orientierung, 3)  #Format 1x3

        'Format anpassen'
        x5in0 = x5in0.transpose()  #Format 3x1
        self.x5in0 = vstack((x5in0, array([[0]])))  #Format 4x1
        y5in0 = y5in0.transpose()  #Format 3x1
        self.y5in0 = vstack((y5in0, array([[0]])))  #Format 4x1
        z5in0 = z5in0.transpose()  #Format 3x1
        self.z5in0 = vstack((z5in0, array([[0]])))  #Format 4x1

        'Lage des Werkzeugkoordinatensystems'

        'Lagevektor zuordnen und Format anpassen'
        P05in0 = lage  #Format 1x3
        P05in0 = P05in0.transpose()  #Format 3x1
        self.P05in0 = vstack((P05in0, array([[1]])))  #Format 4x1

        'Öffnungsradien des Greifers zuordnen und Datentyp ändern'
        self.r6 = float(greifer)
        self.r7 = self.r6

        'Mittelpunktkoordinaten der Circle-Objekte berechnen'
        self.modellrechnung()

        'Draufsicht aktualisieren'
        self.animation_draufsicht.ansicht_aktualisieren( \
        self.xP2in0, self.yP2in0, self.xP4in0, \
        self.yP4in0, self.xP5in0, self.yP5in0)

        'Seitenansicht aktualisieren'
        self.animation_seitenansicht.ansicht_aktualisieren(
        self.xP2in1, self.yP2in1, self.xP3in1, self.yP3in1, \
        self.xP4in1, self.yP4in1, self.xP5in1, self.yP5in1)

        'Greifer aktualisieren'
        self.animation_greifer.ansicht_aktualisieren( \
        self.xP6in4z, self.yP6in4z, self.xP7in4z, self.yP7in4z)

        'Lagekoordinaten des Werkzeugkoordinatensystems'
        x5in0 = int(self.xP5in0)
        y5in0 = int(self.yP5in0)
        z5in0 = int(self.zP5in0)

        'Signal zum Aktualisieren der Lagekoordinaten senden'
        self.signal_koordinaten.emit(x5in0, y5in0, z5in0)

    '''Methode animation_zuruecksetzen - Die Methode setzt den digitalen 
    Roboter auf die Ausgangsposition zurück. Weiter werden die Bewegungs-
    möglichkeit deaktiviert und die Punkte entfärbt.'''

    def animation_zuruecksetzen(self, b):

        if b == True:

            'Orientierung des Werkzeugkoordinatensystems laden'
            self.x5in0, self.y5in0, self.z5in0 = self.orientierung_laden( \
            'programmEin')

            'Lagevektor des Werkzeugkoordinatensystems laden'
            self.P05in0 = self.lage_laden('programmEin')

            'Öffnungsradien des Greifers laden'
            self.r6, self.r7 = self.greifer_laden('programmEin')

            'Mittelpunktkoordinaten der Punkte berechnen'
            self.modellrechnung()

            'Draufsicht aktualisieren'
            self.animation_draufsicht.ansicht_aktualisieren( \
            self.xP2in0, self.yP2in0, self.xP4in0, \
            self.yP4in0, self.xP5in0, self.yP5in0)

            'Seitenansicht aktualisieren'
            self.animation_seitenansicht.ansicht_aktualisieren(
            self.xP2in1, self.yP2in1, self.xP3in1, self.yP3in1, \
            self.xP4in1, self.yP4in1, self.xP5in1, self.yP5in1)

            'Greifer aktualisieren'
            self.animation_greifer.ansicht_aktualisieren( \
            self.xP6in4z, self.yP6in4z, self.xP7in4z, self.yP7in4z)

            'Geist ausblenden und Koordinaten aktualisieren'
            self.geisterstunde(False)

            'Entfärben der bewegbaren Punkte'
            self.animation_draufsicht.punkte_faerben(False)
            self.animation_seitenansicht.punkte_faerben(False)
            self.animation_greifer.punkte_faerben(False)

            'Lagekoordinaten des Werkzeugkoordinatensystems'
            x5in0 = int(self.xP5in0)
            y5in0 = int(self.yP5in0)
            z5in0 = int(self.zP5in0)

            'Signal zum Aktualisieren der Lagekoordinaten senden'
            self.signal_koordinaten.emit(x5in0, y5in0, z5in0)

    '''Methode ansicht_wechseln - Die Methode ermöglicht den Wechsel 
    zwischen den drei Ansichten.'''

    def ansicht_wechseln(self, index):

        self.ansicht.setCurrentIndex(index)

    '''Methode bilder_aufnehmen - Die Methode ermöglicht die Aufnahme und
    das Abspeichern von Bildern der Drauf- und Seitenansicht.'''

    def bilder_aufnehmen(self):

        'Ansichten zentrieren'
        self.zeichenflaeche_draufsicht.axes.set_xlim([-625, 625])
        self.zeichenflaeche_draufsicht.axes.set_ylim([-325, 525])
        self.zeichenflaeche_seitenansicht.axes.set_xlim(-525, 725)
        self.zeichenflaeche_seitenansicht.axes.set_ylim([-325, 525])

        'Arbeitsverzeichnis'
        workdir = getcwd()

        'Dateiname und Pfad'
        dateiname = 'bild_draufsicht.svg'
        dir = path.join(workdir, 'speicher', 'bildspeicher', dateiname)

        'Draufsicht als Bild speichern'
        self.zeichenflaeche_draufsicht.figure.savefig(dir, \
        dpi = 1200, facecolor = self.farbe_zeichenflaeche)

        'Dateiname und Pfad'
        dateiname = 'bild_seitenansicht.svg'
        dir = path.join(workdir, 'speicher', 'bildspeicher', dateiname)

        'Seitenansicht als Bild speichern'
        self.zeichenflaeche_seitenansicht.figure.savefig(dir, \
        dpi = 1200, facecolor = self.farbe_zeichenflaeche)

    '''Methode geisterstunde - Bei der Bewegung des digitalen Roboters wird
    die zuletzt gespeicherte Position als Schatten eingeblendet. Die Methode
    ermöglicht das Ein- oder Ausblenden des Geistes.'''

    def geisterstunde(self, b):

        self.animation_draufsicht.geisterstunde(b)
        self.animation_seitenansicht.geisterstunde(b)
        self.animation_greifer.geisterstunde(b)

    '''Methode greifer_laden - Die Methode lädt den Öffnungsradius des
    Greifers (Zeilenvektor vom Format 1x1) und gibt diesen als Gleit-
    kommazahl zurück. Da sich der Greifer synchron öffnet und schließt 
    sind die Radien von Punkt6 und Punkt 7 gleich.'''

    def greifer_laden(self, name):

        'Arbeitsverzeichnis'
        workdir = getcwd()

        'Dateiname und Pfad'
        dateiname = name + '_greifer.npy'
        dir = path.join(workdir, 'speicher', 'programmspeicher', dateiname)

        'Öffnungsradius laden'
        greifer = load(dir)

        'Datentyp ändern'
        r6 = float(greifer)
        r7 = r6

        return r6, r7

    '''Methode koordinaten - Die Methode zerlegt einen Spaltenvektor 
    in die Koordinaten und gibt diese als Gleitkommazahl zurück.'''

    def koordinaten(self, r):

        'Format des Vektors'
        zeilenzahl, spaltenzahl = r.shape

        'Vektor in Zeilen zerlegen'
        zeilen = vsplit(r, zeilenzahl)

        'Koordinaten zuordnen'
        x = float(zeilen[0])
        y = float(zeilen[1])
        z = float(zeilen[2])

        return x, y, z

    '''Methode koordinaten_draufsicht - Die Bewegung des digitalen 
    Roboters ändert die x0,y0-Koordinaten der Punkte 2, 4 und 5. Diese 
    werden der Methode übergeben. Die z0-Koordinaten der Punkte 2, 4 und 5, 
    die 1-Koordinaten der Punkte 2, 3, 4, und 5 sowie die die 4z-Koordinaten 
    der Punkte 6 und 7 bleiben unverändert. In Folge sind die x0,y0-Koord-
    inaten der drei Punkte und der Winkel theta1 zu aktualisieren sowie die 
    von theta1 abhängigen Transformationsvorschriften und die 0-Koordinaten 
    von Punkt3 neu zu berechnen.'''

    def koordinaten_draufsicht(self, xP2, yP2, xP4, yP4, xP5, yP5):

        'Mittelpunktkoordinaten aktualisieren'
        self.xP2in0 = xP2
        self.yP2in0 = yP2
        self.xP4in0 = xP4
        self.yP4in0 = yP4
        self.xP5in0 = xP5
        self.yP5in0 = yP5

        'Theta1 (Denavit-Hartenberg-Parameter) aktualisieren'
        self.theta1 = self.animation_draufsicht.theta1

        'Transformation = f(theta1)'

        'Neuberechnung der Transformtionsmatrizen Aij'
        self.A01 = A01(self.theta1)
        self.A02 = A02(self.theta1, self.theta2)
        self.A03 = A03(self.theta1, self.theta2, self.theta3)
        self.A04 = A04(self.theta1, self.theta2, self.theta3, self.theta4)
        self.A05 = A05(self.theta1, self.theta2, self.theta3, self.theta4, \
        self.theta5)

        'Neuberechnung der Mittelpunktkoordinaten'

        'Ortsvektor von Punkt3'
        #in 1-Koordinaten
        rP3in1 = array([[self.xP3in1], [self.yP3in1], [self.zP3in1], [1]])
        #in 0-Koordinaten
        rP3in0 = around(dot(self.A01, rP3in1), 3)

        'Koordinaten von Punkt3'
        #in 0-Koordinaten
        self.xP3in0, self.yP3in0, self.zP3in0 = self.koordinaten(rP3in0)

        'Lagekoordinaten des Werkzeugkoordinatensystems'
        x5in0 = int(self.xP5in0)
        y5in0 = int(self.yP5in0)
        z5in0 = int(self.zP5in0)

        'Signal zum Aktualisieren der Lagekoordinaten senden'
        self.signal_koordinaten.emit(x5in0, y5in0, z5in0)

        'Signal, das die Bewegung des digitalen Roboters signalisiert, senden'
        self.signal_animation_aktiv.emit(True)

    '''Methode koordinaten_greifer - Die Bewegung des Greifers ändert 
    die x4z,y4z-Koordinaten der Punkte 6 und 7. Diese werden der Methode 
    übergeben. Die 4z-Koordinaten der Punkte 6 und 7 bleiben unverändert. 
    In Folge sind die x4z,y4z-Koordinaten der beiden Punkte und der Winkel 
    theta5 zu aktualisieren sowie die von theta5 abhängigen Transformations-
    vorschriften neu zu berechnen.'''

    def koordinaten_greifer(self, xP6in4z, yP6in4z, xP7in4z, yP7in4z):

        'Mittelpunktkoordinaten aktualisieren'
        self.xP6in4z = xP6in4z
        self.yP6in4z = yP6in4z
        self.xP7in4z = xP7in4z
        self.yP7in4z = yP7in4z

        'Theta5 (Denavit-Hartenberg-Parameter) aktualisieren'
        self.theta5 = self.animation_greifer.theta5

        'Radien aktualisieren'
        self.r6 = self.animation_greifer.r6
        self.r7 = self.r6

        'Transformation = f(theta5)'

        'Neuberechnung der Transformtionsmatrizen Aij'
        self.A05 = A05(self.theta1, self.theta2, self.theta3, self.theta4, \
        self.theta5)

        self.A15 = A15(self.theta2, self.theta3, self.theta4, self.theta5)

        self.A45 = A45(self.theta5)

        'Signal, das die Bewegung des digitalen Roboters signalisiert, senden'
        self.signal_animation_aktiv.emit(True)

    '''Methode koordinaten_seitenansicht - Die Bewegung des digitalen 
    Roboters ändert die x1,y1-Koordinaten der Punkte 2, 3, 4, und 5. Diese 
    werden der Methode übergeben. Die z1-Koordinaten der Punkte 2, 3, 4 und
    5 und die 4z-Koordinaten der Punkte 6 und 7 bleiben erhalten. In Folge 
    sind die x1,y1-Koordinaten der vier Punkte und die Winkel theta2, theta3 
    und theta4 zu aktualisieren sowie die von den Winkeln abhängigen 
    Transformationsvorschriften und die 0-Koordinaten der vier Punkte neu
    zu berechnen.'''
    def koordinaten_seitenansicht(self, xP2in1, yP2in1, xP3in1, yP3in1, \
    xP4in1, yP4in1, xP5in1, yP5in1):

        'Mittelpunktkoordinaten aktualisieren'
        self.xP2in1 = xP2in1
        self.yP2in1 = yP2in1
        self.xP3in1 = xP3in1
        self.yP3in1 = yP3in1
        self.xP4in1 = xP4in1
        self.yP4in1 = yP4in1
        self.xP5in1 = xP5in1
        self.yP5in1 = yP5in1

        'Theta2, Theta3 und Theta4 (Denavit-Hartenberg-P.) aktualisieren'
        self.theta2 = self.animation_seitenansicht.theta2
        self.theta3 = self.animation_seitenansicht.theta3
        self.theta4 = self.animation_seitenansicht.theta4

        'Transformation = f(theta2, theta3, theta4)'

        'Neuberechnung der Transformationsmatrizen Aij'
        self.A02 = A02(self.theta1, self.theta2)
        self.A03 = A03(self.theta1, self.theta2, self.theta3)
        self.A04 = A04(self.theta1, self.theta2, self.theta3, self.theta4)
        self.A05 = A05(self.theta1, self.theta2, self.theta3, self.theta4, \
        self.theta5)

        self.A12 = A12(self.theta2)
        self.A13 = A13(self.theta2, self.theta3)
        self.A14 = A14(self.theta2, self.theta3, self.theta4)
        self.A15 = A15(self.theta2, self.theta3, self.theta4, self.theta5)

        'Neuberechnung der Mittelpunktkoordinaten'

        'Ortsvektor von Punkt2'
        #in 1-Koordinaten
        rP2in1 = array([[self.xP2in1], [self.yP2in1], [self.zP2in1], [1]])
        #in 0-Koordinaten
        rP2in0 = around(dot(self.A01, rP2in1), 3)

        'Ortsvektor von Punkt3'
        #in 1-Koordinaten
        rP3in1 = array([[self.xP3in1], [self.yP3in1], [self.zP3in1], [1]])
        #in 0-Koordinaten
        rP3in0 = around(dot(self.A01, rP3in1), 3)

        'Ortsvektor von Punkt4'
        #in 1-Koordinaten
        rP4in1 = array([[self.xP4in1], [self.yP4in1], [self.zP4in1], [1]])
        #in 0-Koordinaten
        rP4in0 = around(dot(self.A01, rP4in1), 3)

        'Ortsvektor von Punkt5'
        #in 1-Koordinaten
        rP5in1 = array([[self.xP5in1], [self.yP5in1], [self.zP5in1], [1]])
        #in 0-Koordinaten
        rP5in0 = around(dot(self.A01, rP5in1), 3)

        'Koordinaten von Punkt2'
        #in 0-Koordinaten
        self.xP2in0, self.yP2in0, self.zP2in0 = self.koordinaten(rP2in0)

        'Koordinaten von Punkt3'
        #in 0-Koordinaten
        self.xP3in0, self.yP3in0, self.zP3in0 = self.koordinaten(rP3in0)

        'Koordinaten von Punkt4'
        #in 0-Koordinaten
        self.xP4in0, self.yP4in0, self.zP4in0 = self.koordinaten(rP4in0)

        'Koordinaten von Punkt5'
        #in 0-Koordinaten
        self.xP5in0, self.yP5in0, self.zP5in0 = self.koordinaten(rP5in0)

        'Bewegungen des digitalen Roboters synchronisieren'
        self.animation_draufsicht.pointG2.set_visible(True)
        self.animation_draufsicht.pointG4.set_visible(True)
        self.animation_draufsicht.pointG5.set_visible(True)
        self.animation_draufsicht.lineG1.set_visible(True)
        self.animation_draufsicht.lineG2.set_visible(True)
        self.animation_draufsicht.lineG3.set_visible(True)

        'Draufsicht aktualisieren'
        self.animation_draufsicht.ansicht_aktualisieren( \
        self.xP2in0, self.yP2in0, self.xP4in0, \
        self.yP4in0, self.xP5in0, self.yP5in0)

        'Lagekoordinaten des Werkzeugkoordinatensystems'
        x5in0 = int(self.xP5in0)
        y5in0 = int(self.yP5in0)
        z5in0 = int(self.zP5in0)

        'Signal zum Aktualisieren der Lagekoordinaten senden'
        self.signal_koordinaten.emit(x5in0, y5in0, z5in0)

        'Signal, das die Bewegung des digitalen Roboters signalisiert, senden'
        self.signal_animation_aktiv.emit(True)

    '''Methode koordinaten_abfragen - Die Methode gibt die aktuellen 
    Lagekoordinaten des Werkzeugkoordinatensystems zurück.'''

    def koordinaten_abfragen(self):

        xP5in0 = self.xP5in0
        yP5in0 = self.yP5in0
        zP5in0 = self.zP5in0

        return xP5in0, yP5in0, zP5in0

    '''Methode lage_berechnen - Die Methode gibt die Lage (Zeilenvektor 
    vom Format 1x3) und Orientierung (Zeilenvektor vom Format 1x9) des
    Werkzeugkoordinatensystems in 0-Koordinaten, die Winkel (Denavit-
    Hartenberg-Parameter) (Zeilenvektor vom Format 1x5) und den 
    Öffnungsradius des Greifers (Zeilenvektor vom Format 1x1) zurück.'''

    def lage_berechnen(self):

        'Geist ausblenden'
        self.geisterstunde(False)
        '''Kinematische Vorwärtstransformation zur Berechnung von Lage
        und Orientierung des Werkzeugkoordinatensystems in 0-Koordinaten.
        Die Vektoren werden im Format 3x1 zurückgegeben.'''
        x5in0, y5in0, z5in0, P05in0 = kinematik_vor(self.theta1, \
        self.theta2, self.theta3, self.theta4, self.theta5)

        'Orientierung des Werkzeugkoordinatensystems'

        'Format der Einheitsvektoren anpassen'
        x5in0 = x5in0.transpose()  #Format 1x3
        y5in0 = y5in0.transpose()  #Format 1x3
        z5in0 = z5in0.transpose()  #Format 1x3

        'Orientierungsvektor erstellen'
        orientierung = hstack((x5in0, y5in0, z5in0))  #Format 1x9
        orientierung = around(orientierung, 3)

        'Lage des Werkzeugkoordinatensystems'

        'Format des Lagevektors anpassen und Vektor zuweisen'
        lage = P05in0.transpose()  #Format 1x3
        lage = around(lage, 3)

        'Winkelvektor erstellen'
        winkel = array([[self.theta1, self.theta2, \
        self.theta3, self.theta4, self.theta5]]) #Format 1x5
        winkel = around(winkel, 3)

        'Öffnungsradius des Greifers'
        greifer = array([[self.r6]])  #Format 1x1

        return orientierung, lage, winkel, greifer

    '''Methode modellrechnung - Die Methode berechnet aus der Lage und 
    Orientierung des Werkzeugkoordinatensystems in 0-Koordinaten sowie 
    dem Öffnungsradius des Greifers die Mittelpunktkoordinaten der Circle-
    Objekte. Insgesamt gibt es sieben Circle-Objekte und drei Ansichten. Die 
    Draufsicht ist die Projektion des digitalen Roboters auf die x0,y0-Ebene. 
    Dargestellt werden Punkt1, Punkt2, Punkt4 und Punkt5. Die Seitenansicht 
    ist die Projektion des digitalen Roboters auf die x1,y1-Ebene. Dargestellt 
    werden Punkt1, Punkt2, Punkt3, Punkt4 und Punkt5. Die Ansicht des Greifers
    ist die Projektion auf eine Zeichenebene parallel zur x4,y4-Ebene.
    Dargestellt werden Punkt6 und Punkt7. Während die Mittelpunktkoordinaten
    von Punkt6 und Punkt 7 nur in Zeichenkoordinaten berechnet werden, werden
    die Koordinaten der Punkte 1 bis 5 auch in 0-Koordinaten berechnet.'''

    def modellrechnung(self):
        '''Kinematische Rückwärtstransformation zur Berechnung der 
        Winkel (Denavit-Hartenberg-Parameter) bei gegebener Lage und
        Orientierung des Werkzeugkoordinatensystems'''
        theta = kinematik_inv(self.x5in0, self.y5in0, self.z5in0, self.P05in0)

        'Drehwinkel zuordnen'
        self.theta1 = theta[0]
        self.theta2 = theta[1]
        self.theta3 = theta[2]
        self.theta4 = theta[3]
        self.theta5 = theta[4]

        'Transformationsmatrizen Aij zur Überführung von Ki in Kj'
        self.A01 = A01(self.theta1)
        self.A02 = A02(self.theta1, self.theta2)
        self.A03 = A03(self.theta1, self.theta2, self.theta3)
        self.A04 = A04(self.theta1, self.theta2, self.theta3, self.theta4)
        self.A05 = A05(self.theta1, self.theta2, self.theta3, self.theta4, \
        self.theta5)

        self.A12 = A12(self.theta2)
        self.A13 = A13(self.theta2, self.theta3)
        self.A14 = A14(self.theta2, self.theta3, self.theta4)
        self.A15 = A15(self.theta2, self.theta3, self.theta4, self.theta5)

        self.A45 = A45(self.theta5)

        'Ortsvektor von Punkt2'
        #in 2-Koordinaten
        rP2in2 = array([[0], [0], [0], [1]])
        #in 1-Koordinaten
        rP2in1 = around(dot(self.A12, rP2in2), 3)
        #in 0-Koordinaten
        rP2in0 = around(dot(self.A02, rP2in2), 3)

        'Ortsvektor von Punkt3'
        l = self.a3 * (cos(8 * pi / 180) - sin(8 * pi / 180))
        #in 3-Koordinaten
        rP3in3 = array([[-l * cos(8 * pi / 180)], [l * sin(8 * pi / 180)], [0],
                        [1]])
        #in 1-Koordinaten
        rP3in1 = around(dot(self.A13, rP3in3), 3)
        #in 0-Koordinaten
        rP3in0 = around(dot(self.A03, rP3in3), 3)

        'Ortsvektor von Punk4'
        #in 4-Koordinaten
        rP4in4 = array([[0], [0], [0], [1]])
        #in 1-Koordinaten
        rP4in1 = around(dot(self.A14, rP4in4), 3)
        #in 0-Koordinaten
        rP4in0 = around(dot(self.A04, rP4in4), 3)

        'Ortsvektor von Punk5'
        #in 5-Koordinaten
        rP5in5 = array([[0], [0], [0], [1]])
        #in 1-Koordinaten
        rP5in1 = around(dot(self.A15, rP5in5), 3)
        #in 0-Koordinaten
        rP5in0 = self.P05in0

        phi6 = pi - self.theta5
        phi7 = phi6 + pi

        'Ortsvektor von Punkt6'
        #in 4z-Koordinaten
        rP6in4z = array([[self.r6 * cos(phi6)], [self.r6 * sin(phi6)], [0],
                         [1]])

        'Ortsvektor von Punkt7'
        #in 4z-Koordinaten
        rP7in4z = array([[self.r7 * cos(phi7)], [self.r7 * sin(phi7)], [0],
                         [1]])

        'Koordinaten von Punkt1'
        #in 1-Koordinaten
        self.xP1in1, self.yP1in1, self.zP1in1 = (0, 0, 0)
        #in 0-Koordinaten
        self.xP1in0, self.yP1in0, self.zP1in0 = (0, 0, 0)

        'Koordinaten von Punkt2'
        #in 1-Koordinaten
        self.xP2in1, self.yP2in1, self.zP2in1 = self.koordinaten(rP2in1)
        #in 0-Koordinaten
        self.xP2in0, self.yP2in0, self.zP2in0 = self.koordinaten(rP2in0)

        'Koordinaten von Punkt3'
        #in 1-Koordinaten
        self.xP3in1, self.yP3in1, self.zP3in1 = self.koordinaten(rP3in1)
        #in 0-Koordinaten
        self.xP3in0, self.yP3in0, self.zP3in0 = self.koordinaten(rP3in0)

        'Koordinaten von Punkt4'
        #in 1-Koordinaten
        self.xP4in1, self.yP4in1, self.zP4in1 = self.koordinaten(rP4in1)
        #in 0-Koordinaten
        self.xP4in0, self.yP4in0, self.zP4in0 = self.koordinaten(rP4in0)

        'Koordinaten von Punkt5'
        #in 1-Koordinaten
        self.xP5in1, self.yP5in1, self.zP5in1 = self.koordinaten(rP5in1)
        #in 0-Koordinaten
        self.xP5in0, self.yP5in0, self.zP5in0 = self.koordinaten(rP5in0)

        'Zeichenkoordinaten von Punkt6'
        #in 4z-Koordinaten
        self.xP6in4z, self.yP6in4z, self.zP6in4z = self.koordinaten(rP6in4z)

        'Zeichenkoordinaten von Punkt7'
        #in 4z-Koordinaten
        self.xP7in4z, self.yP7in4z, self.zP7in4z = self.koordinaten(rP7in4z)

    '''Methode orientierung_laden - Die Methode lädt die Orientierung des
    Werkzeugkoordinatensystems in 0-Koordinaten (Zeilenvektor vom Format 
    1x9) und gibt die Einheitsvektoren des Werkzeugkoordinatensystems als 
    Spaltenvektoren vom Format 4x1 zurück.'''

    def orientierung_laden(self, name):

        'Arbeitsverzeichnis'
        workdir = getcwd()

        'Dateiname und Pfad'
        dateiname = name + '_orientierung.npy'
        dir = path.join(workdir, 'speicher', 'programmspeicher', dateiname)

        'Orientierung laden'
        orientierung = load(dir)

        'Einheitsvektoren zuordnen'
        x5in0, y5in0, z5in0 = hsplit(orientierung, 3)  #Format 1x3

        'Format anpassen'
        x5in0 = x5in0.transpose()  #Format 3x1
        x5in0 = vstack((x5in0, array([[0]])))  #Format 4x1
        y5in0 = y5in0.transpose()  #Format 3x1
        y5in0 = vstack((y5in0, array([[0]])))  #Format 4x1
        z5in0 = z5in0.transpose()  #Format 3x1
        z5in0 = vstack((z5in0, array([[0]])))  #Format 4x1

        return x5in0, y5in0, z5in0

    '''Methode lage_laden - Die Methode lädt den Lagevektor des
    Werkzeugkoordinatensystems in 0-Koordinaten (Zeilenvektor vom Format 
    1x3) und gibt diese als Spaltenvektor vom Format 4x1 zurück.'''

    def lage_laden(self, name):

        'Arbeitsverzeichnis'
        workdir = getcwd()

        'Dateiname und Pfad'
        dateiname = name + '_lage.npy'
        dir = path.join(workdir, 'speicher', 'programmspeicher', dateiname)

        'Lagevektor laden'
        lage = load(dir)

        'Format anpassen'
        P05in0 = lage  #Format 1x3
        P05in0 = P05in0.transpose()  #Format 3x1
        P05in0 = vstack((P05in0, array([[1]])))  #Format 4x1

        return P05in0
コード例 #38
0
class LunchMenuWidget(QWidget):
    textViewIndex = 0
    textViewAdditivesMap = {}

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

        box = QVBoxLayout(self)
        box.addWidget(QLabel(u"Initializing...", self))

    def initializeLayout(self):
        layout = self.layout()

        child = layout.takeAt(0)
        while child != None:
            child.widget().deleteLater()
            child = layout.takeAt(0)

        self.messages = LunchMenu.messages()
        self.toggleMessages = LunchMenu.toggleMessages()

        self.additives = LunchMenu.additives()
        self.toggleAdditives = LunchMenu.toggleAdditives()

        buttonBar = self.createButtonBar(self)

        layout.addLayout(buttonBar)

        self.menuNotebook = QStackedWidget(self)
        self.createNotebook()
        layout.addWidget(self.menuNotebook)

        self.setSizePolicy(QSizePolicy.MinimumExpanding,
                           QSizePolicy.MinimumExpanding)

    def create_arrow_button(self, parent, arrow_type):
        button = QToolButton(parent)
        button.setArrowType(arrow_type)
        return button

    def goLeft(self):
        curIndex = self.combobox.currentIndex()
        if curIndex > 0:
            self.combobox.setCurrentIndex(curIndex - 1)

    def goRight(self):
        curIndex = self.combobox.currentIndex()
        if curIndex < 4:
            self.combobox.setCurrentIndex(curIndex + 1)

    def goToday(self):
        now = LunchMenu.today()

        minDelta = sys.maxint
        minDeltaI = 0
        i = 0
        for aLunchMenu in LunchMenu.allLunchMenus():
            if aLunchMenu == None or isinstance(aLunchMenu, Exception):
                # parse error, use current day of week
                if now.weekday() < 5:
                    minDeltaI = now.weekday()
                else:
                    minDeltaI = 4
                break
            td = now - aLunchMenu.lunchDate
            delta = abs((td.microseconds +
                         (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)
            if delta < minDelta:
                minDelta = delta
                minDeltaI = i
            i = i + 1

        self.combobox.setCurrentIndex(minDeltaI)

    def goTodayClicked(self):
        self.goToday()

    def isToggled(self):
        index = self.menuNotebook.currentIndex()
        return (index >= 5)

    def changed_combo(self, index):
        if self.isToggled():
            self.menuNotebook.setCurrentIndex(index + 5)
        else:
            self.menuNotebook.setCurrentIndex(index)
        self.leftButton.setEnabled(index != 0)
        self.rightButton.setEnabled(index != 4)

    def toggleLanguage(self):
        index = self.menuNotebook.currentIndex()
        isToggle = (index >= 5)
        if isToggle:
            self.switchLanguageButton.setText(self.messages["toggleLanguage"])
            index = index - 5
        else:
            self.switchLanguageButton.setText(self.messages["toggleLanguage2"])
            index = index + 5
        self.menuNotebook.setCurrentIndex(index)

    def createButtonBar(self, parent):
        self.combobox = QComboBox(parent)
        self.combobox.addItem(self.messages['monday'])
        self.combobox.addItem(self.messages['tuesday'])
        self.combobox.addItem(self.messages['wednesday'])
        self.combobox.addItem(self.messages['thursday'])
        self.combobox.addItem(self.messages['friday'])
        self.combobox.currentIndexChanged.connect(self.changed_combo)
        comboBoxHeight = self.combobox.sizeHint().height()

        self.leftButton = self.create_arrow_button(parent, Qt.LeftArrow)
        self.leftButton.clicked.connect(self.goLeft)
        self.leftButton.setMinimumSize(comboBoxHeight, comboBoxHeight)

        self.rightButton = self.create_arrow_button(parent, Qt.RightArrow)
        self.rightButton.clicked.connect(self.goRight)
        self.rightButton.setMinimumSize(comboBoxHeight, comboBoxHeight)

        navButtons = QHBoxLayout()
        navButtons.addWidget(self.leftButton, 0, Qt.AlignRight)
        navButtons.addWidget(self.combobox, 0, Qt.AlignCenter)
        navButtons.addWidget(self.rightButton, 0, Qt.AlignLeft)

        buttonBar = QHBoxLayout()
        todayButton = QPushButton(self.messages['today'], parent)
        todayButton.clicked.connect(self.goTodayClicked)
        todayButton.setMinimumHeight(comboBoxHeight)
        buttonBar.addWidget(todayButton)

        buttonBar.addWidget(QWidget(parent), 1)
        buttonBar.addLayout(navButtons, 1)
        buttonBar.addWidget(QWidget(parent), 1)

        self.switchLanguageButton = QPushButton(
            self.messages["toggleLanguage"], parent)
        self.switchLanguageButton.clicked.connect(self.toggleLanguage)
        self.switchLanguageButton.setMinimumHeight(comboBoxHeight)
        buttonBar.addWidget(self.switchLanguageButton, 0, Qt.AlignRight)

        return buttonBar

    def addMenuLine(self, parent, text, box, header=False):
        aLabel = QLabel(text, parent)
        if header:
            aLabel.setAlignment(Qt.AlignCenter)
            oldFont = aLabel.font()
            aLabel.setFont(QFont(oldFont.family(), 13, QFont.Bold))
        box.addWidget(aLabel, 0, Qt.AlignBottom)

    def addLocaleErrorPage(self, parent, box, toggle):
        aLabel = QLabel(self.messages['parseLocaleError'], parent)
        aLabel.setWordWrap(True)
        box.addWidget(aLabel)

        aButton = QPushButton(self.messages['installLocaleButton'], parent)
        if toggle:
            aButton.clicked.connect(self.installLanguageSupportToggle)
        else:
            aButton.clicked.connect(self.installLanguageSupport)
        box.addWidget(aButton)

    def addExceptionPage(self, parent, box, error, _toggle):
        aLabel = QLabel(
            self.messages['otherException'] + u" " + unicode(error), parent)
        aLabel.setWordWrap(True)
        box.addWidget(aLabel)

    def installLanguageSupportForLocale(self, locale):
        locale = locale.partition("_")[0]
        if subprocess.call(
            ['gksu', "apt-get -q -y install language-pack-%s" % locale]) != 0:
            QMessageBox().critical(self.menuNotebook,
                                   "Installation Error",
                                   self.messages['installLocaleError'],
                                   buttons=QMessageBox.Ok,
                                   defaultButton=QMessageBox.Ok)
        else:
            QMessageBox().information(self.menuNotebook,
                                      "Success",
                                      self.messages['installLocaleSuccess'],
                                      buttons=QMessageBox.Ok,
                                      defaultButton=QMessageBox.Ok)

    def installLanguageSupport(self):
        self.installLanguageSupportForLocale(self.defaultLocaleString)

    def installLanguageSupportToggle(self):
        self.installLanguageSupportForLocale(self.messages['toggleLocale'])

    def formatTitleAndDescription(self, title, description, keyInfo):
        if title and description:
            result = "%s, %s" % (title, description)
        elif title:
            result = title
        else:
            result = description

        if keyInfo:
            return "%s: %s" % (keyInfo.title(), result)
        return result

    def addMenuContent(self, parent, desc, menuContents, box, messages,
                       additivesDict):
        self.addMenuLine(parent, desc, box)
        if desc in menuContents:
            contentList = menuContents[desc]
        else:
            contentList = [(messages[u'noContents'], None, [], None)]
            log_debug("lunch menu does not contain key '%s'" % desc)

        textview = GrowingTextEdit(parent, messages, additivesDict)
        textview.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        textview.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        textview.setLineWrapMode(QTextEdit.WidgetWidth)
        textview.setReadOnly(True)
        textview.document().setIndentWidth(10)

        if len(contentList) == 1:
            title, description, additives, keyInfo = contentList[0]
            textview.append(
                self.formatTitleAndDescription(title, description, keyInfo),
                additives)
        elif len(contentList) > 1:
            cursor = textview.textCursor()
            listFormat = QTextListFormat()
            listFormat.setStyle(QTextListFormat.ListDisc)
            listFormat.setIndent(1)
            cursor.createList(listFormat)
            for title, description, additives, keyInfo in contentList:
                textview.append(
                    self.formatTitleAndDescription(title, description,
                                                   keyInfo), additives)

        box.addWidget(textview, 0)

    def createNotebook(self):
        self.combobox.setCurrentIndex(0)
        for _ in range(self.menuNotebook.count()):
            self.menuNotebook.removeWidget(self.menuNotebook.widget(0))
        curMessages = self.messages
        curAdditives = self.additives
        for index in range(10):
            if index == 5:
                try:
                    if getPlatform() != PLATFORM_WINDOWS:
                        locale.setlocale(
                            locale.LC_TIME,
                            (self.messages["toggleLocale"], "UTF-8"))
                except:
                    log_exception("error setting locale")
                curMessages = self.toggleMessages
                curAdditives = self.toggleAdditives
            pageWidget = QWidget(self.menuNotebook)
            page = QVBoxLayout(pageWidget)
            thisLunchMenu = LunchMenu.allLunchMenus()[index]
            if thisLunchMenu != None and type(thisLunchMenu) == LunchMenu:
                title = curMessages[
                    'lunchMenuFor'] + u" " + thisLunchMenu.lunchDate.strftime(
                        curMessages['dateFormatDisplayed']).decode("utf-8")
                self.addMenuLine(pageWidget, title, page, True)
                if thisLunchMenu.isValid():
                    self.addMenuContent(pageWidget,
                                        curMessages['soupDisplayed'],
                                        thisLunchMenu.contents, page,
                                        curMessages, curAdditives)
                    self.addMenuContent(pageWidget,
                                        curMessages['mainDishesDisplayed'],
                                        thisLunchMenu.contents, page,
                                        curMessages, curAdditives)
                    self.addMenuContent(pageWidget,
                                        curMessages['supplementsDisplayed'],
                                        thisLunchMenu.contents, page,
                                        curMessages, curAdditives)
                    self.addMenuContent(pageWidget,
                                        curMessages['dessertsDisplayed'],
                                        thisLunchMenu.contents, page,
                                        curMessages, curAdditives)
                else:
                    self.addMenuLine(pageWidget, curMessages['noLunchToday'],
                                     page)
            elif type(thisLunchMenu) == locale.Error:
                self.addLocaleErrorPage(pageWidget, page, index >= 5)
                pass
            elif isinstance(thisLunchMenu, Exception):
                self.addExceptionPage(pageWidget, page, thisLunchMenu,
                                      index >= 5)

            self.menuNotebook.addWidget(pageWidget)
        try:
            if getPlatform() != PLATFORM_WINDOWS:
                locale.setlocale(locale.LC_TIME,
                                 (LunchMenu.defaultLocaleString, "UTF-8"))
        except:
            log_exception("error setting locale")

        self.goToday()
コード例 #39
0
class EditorWidget(QWidget):

    # Señales
    allFilesClosed = pyqtSignal()

    def __init__(self):
        super(EditorWidget, self).__init__()
        self._recents_files = []

        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)

        # Combo container
        self.combo = ComboContainer(self)
        box.addWidget(self.combo)

        # Stacked
        self.stack = QStackedWidget()
        box.addWidget(self.stack)

        self.connect(self.combo.combo_file,
                     SIGNAL("currentIndexChanged(int)"), self.change_item)

    def add_widget(self, widget):
        index = self.stack.addWidget(widget)
        if not self.combo.isVisible():
            self.combo.setVisible(True)
        self.stack.setCurrentIndex(index)

    def add_item_combo(self, text):
        self.combo.combo_file.addItem(text)
        self.combo.combo_file.setCurrentIndex(
            self.combo.combo_file.count() - 1)

    def remove_item_combo(self, index):
        self.combo.combo_file.removeItem(index)

    def change_item(self, index):
        self.stack.setCurrentIndex(index)
        self.emit(SIGNAL("currentWidgetChanged(int)"), index)

    def current_widget(self):
        return self.stack.currentWidget()

    def current_index(self):
        return self.stack.currentIndex()

    def widget(self, index):
        return self.stack.widget(index)

    def count(self):
        return self.stack.count()

    def close_file(self):
        self.remove_widget(self.current_widget(), self.current_index())

    def close_file_project(self, widget, index):
        #FIXME: unir con close file
        self.remove_widget(widget, index)

    def close_all(self):
        for index in range(self.count()):
            self.remove_widget(self.current_widget(), 0)

    def editor_modified(self, value):
        weditor = self.current_widget()
        index = self.current_index()
        self.combo.set_modified(weditor, index, value)

    def _add_to_recent(self, filename):
        if filename == 'Untitled':
            return
        if filename not in self._recents_files:
            self._recents_files.append(filename)
            self.emit(SIGNAL("recentFile(QStringList)"), self._recents_files)

    def check_files_not_saved(self):
        value = False
        for index in range(self.count()):
            weditor = self.widget(index)
            value = value or weditor.is_modified
        return value

    def files_not_saved(self):
        files = []
        for index in range(self.count()):
            weditor = self.widget(index)
            if weditor.is_modified:
                files.append(weditor.filename)
        return files

    def opened_files(self):
        files = []
        for index in range(self.count()):
            weditor = self.widget(index)
            path = weditor.filename
            if path == 'Untitled':
                continue
            files.append(path)
        return files

    def remove_widget(self, widget, index):
        if not isinstance(widget, editor.Editor):
            return
        if index != -1:
            self.stack.setCurrentIndex(index)

            flags = QMessageBox.Yes
            flags |= QMessageBox.No
            flags |= QMessageBox.Cancel

            result = QMessageBox.No
            if widget.is_modified:
                result = QMessageBox.question(self, self.tr(
                    "Archivo no guardado!"),
                    self.tr("El archivo <b>{0}</b> "
                            "tiene cambios sin guardar. "
                            "Quieres guardarlos?").format(widget.filename),
                    QMessageBox.Yes, QMessageBox.No, QMessageBox.Cancel)
                if result == QMessageBox.Cancel:
                    return
                elif result == QMessageBox.Yes:
                    self.emit(SIGNAL("saveCurrentFile()"))
            self._add_to_recent(widget.filename)
            self.stack.removeWidget(widget)
            self.emit(SIGNAL("fileClosed(int)"), index)
            self.remove_item_combo(index)
            widget.obj_file.stop_system_watcher()
            if self.current_widget() is not None:
                self.current_widget().setFocus()
            else:
                self.allFilesClosed.emit()

    def add_symbols(self, symbols):
        self.combo.add_symbols_combo(symbols)
コード例 #40
0
ファイル: GUI.py プロジェクト: fimad/TextToKill
class GUI(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        # Set size of window
        MainWindow.resize(800, 589)
        MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)
        MainWindow.setWindowTitle("Text to Kill")
        
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        font = QFont()
        font.setFamily("Times New Roman")
        
        # Main menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.titleLabel = QLabel(self.menuPage)
        self.titleLabel.setGeometry(QtCore.QRect(250, 60, 300, 50))
        font.setPointSize(45)
        self.titleLabel.setFont(font)
        self.titleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.titleLabel.setObjectName("titleLabel")
        self.titleLabel.setText("Text to Kill")
        self.subtitleLabel = QLabel(self.menuPage)
        self.subtitleLabel.setGeometry(QtCore.QRect(100, 140, 600, 40))
        font.setPointSize(25)
        self.subtitleLabel.setFont(font)
        self.subtitleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.subtitleLabel.setObjectName("subtitleLabel")
        self.subtitleLabel.setText("The Murder Mystery Automation System")
        self.createButton = QPushButton(self.menuPage)
        self.createButton.setGeometry(QtCore.QRect(310, 260, 180, 60))
        self.createButton.setObjectName("createButton")
        self.createButton.setText("Create Game")
        self.runButton = QPushButton(self.menuPage)
        self.runButton.setGeometry(QtCore.QRect(310, 350, 180, 60))
        self.runButton.setObjectName("runButton")
        self.runButton.setText("Run Game")
        self.stackedWidget.addWidget(self.menuPage)
        
        # Create page
        self.createPage = QWidget()
        self.createPage.setObjectName("createPage")
        self.createTabWidget = QTabWidget(self.createPage)
        self.createTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))

        self.createTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.createTabWidget.setObjectName("createTabWidget")
        
        # Create game tab
        self.createTab = QWidget()
        self.createTab.setObjectName("createTab")
        self.createDoneButton = QPushButton(self.createTab)
        self.createDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.createDoneButton.setObjectName("createDoneButton")
        self.createDoneButton.setText("Done")
        self.gameNameEdit = QLineEdit(self.createTab)
        self.gameNameEdit.setGeometry(QtCore.QRect(140, 20, 160, 30))
        self.gameNameEdit.setObjectName("gameNameEdit")
        self.gameNameLabel = QLabel(self.createTab)
        self.gameNameLabel.setGeometry(QtCore.QRect(20, 25, 110, 20))

        font.setPointSize(15)
        self.gameNameLabel.setFont(font)
        self.gameNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.gameNameLabel.setObjectName("gameNameLabel")
        self.gameNameLabel.setText("Game name")
        self.line = QFrame(self.createTab)
        self.line.setGeometry(QtCore.QRect(20, 150, 311, 20))
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.addCharLabel = QLabel(self.createTab)
        self.addCharLabel.setGeometry(QtCore.QRect(20, 180, 160, 20))
        
        font.setPointSize(20)
        self.addCharLabel.setFont(font)
        self.addCharLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.addCharLabel.setObjectName("addCharLabel")
        self.addCharLabel.setText("Add Character")
        self.charNameLabel = QLabel(self.createTab)
        self.charNameLabel.setGeometry(QtCore.QRect(20, 230, 66, 20))

        font.setPointSize(15)
        self.charNameLabel.setFont(font)
        self.charNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.charNameLabel.setObjectName("charNameLabel")
        self.charNameLabel.setText("Name")
        self.charNameEdit = QLineEdit(self.createTab)
        self.charNameEdit.setGeometry(QtCore.QRect(140, 220, 160, 30))
        self.charNameEdit.setObjectName("charNameEdit")
        self.charAbilScroll = QListWidget(self.createTab)
        self.charAbilScroll.setGeometry(QtCore.QRect(140, 260, 161, 51))
        self.charAbilScroll.setObjectName("charAbilScroll")
        self.characterTable = QTableWidget(self.createTab)
        self.characterTable.setGeometry(QtCore.QRect(405, 20, 381, 401))
        self.characterTable.setFocusPolicy(QtCore.Qt.NoFocus)
        self.characterTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.characterTable.setRowCount(1)
        self.characterTable.setColumnCount(2)
        self.characterTable.setObjectName("characterTable")
        self.characterTable.horizontalHeader().setVisible(False)
        self.characterTable.horizontalHeader().setCascadingSectionResizes(False)
        self.characterTable.horizontalHeader().setMinimumSectionSize(50)
        self.characterTable.horizontalHeader().setStretchLastSection(True)
        self.characterTable.verticalHeader().setVisible(False)
        self.characterTable.verticalHeader().setDefaultSectionSize(30)
        self.scrollArea = QListWidget(self.createTab)
        self.scrollArea.setGeometry(QtCore.QRect(140, 60, 161, 71))
        self.scrollArea.setObjectName("scrollArea")
        self.scrollArea.setSelectionMode(3)
        self.createSaveButton = QPushButton(self.createTab)
        self.createSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.createSaveButton.setObjectName("createSaveButton")
        self.createSaveButton.setText("Save")
        self.charAbilitiesLabel = QLabel(self.createTab)
        self.charAbilitiesLabel.setGeometry(QtCore.QRect(30, 280, 71, 20))

        font.setPointSize(15)
        self.charAbilitiesLabel.setFont(font)
        self.charAbilitiesLabel.setObjectName("charAbilitiesLabel")
        self.charAbilitiesLabel.setText("Abilities")
        self.abilitiesDropdown = QComboBox(self.createTab)
        self.abilitiesDropdown.setGeometry(QtCore.QRect(140, 330, 151, 25))
        self.abilitiesDropdown.setObjectName("abilitiesDropdown")
        
        self.addCharButton = QPushButton(self.createTab)
        self.addCharButton.setGeometry(QtCore.QRect(30, 370, 98, 27))
        self.addCharButton.setObjectName("addCharButton")
        self.addCharButton.setText("Add")
        self.gameAbilitiesLabel = QLabel(self.createTab)
        self.gameAbilitiesLabel.setGeometry(QtCore.QRect(30, 80, 71, 20))
        
        self.setGameAbilButton = QPushButton(self.createTab)
        self.setGameAbilButton.setGeometry(QtCore.QRect(30, 110, 71, 27))
        self.setGameAbilButton.setObjectName("setGameAbilButton")
        self.setGameAbilButton.setText("Set")
        
        self.saveCharButton = QPushButton(self.createTab)
        self.saveCharButton.setGeometry(QtCore.QRect(70, 430, 180, 60))
        self.saveCharButton.setObjectName("saveCharButton")
        self.saveCharButton.setText("Save Character")

        font.setPointSize(15)
        self.gameAbilitiesLabel.setFont(font)
        self.gameAbilitiesLabel.setObjectName("gameAbilitiesLabel")
        self.gameAbilitiesLabel.setText("Abilities")
        self.createTabWidget.addTab(self.createTab, "")
        
        # Setup tab widget
        self.setupTab = QWidget()
        self.setupTab.setObjectName("setupTab")
        self.setupDoneButton = QPushButton(self.setupTab)
        self.setupDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.setupDoneButton.setObjectName("setupDoneButton")
        self.setupDoneButton.setText("Done")
        self.setupTable = QTableWidget(self.setupTab)
        self.setupTable.setGeometry(QtCore.QRect(20, 20, 750, 400))
        self.setupTable.setFocusPolicy(QtCore.Qt.TabFocus)
        self.setupTable.setRowCount(1)
        self.setupTable.setColumnCount(3)
        self.setupTable.setObjectName("setupTable")
        self.setupTable.horizontalHeader().setVisible(False)
        self.setupTable.horizontalHeader().setCascadingSectionResizes(False)
        self.setupTable.horizontalHeader().setDefaultSectionSize(187)
        self.setupTable.horizontalHeader().setHighlightSections(False)
        self.setupTable.horizontalHeader().setStretchLastSection(True)
        self.setupTable.verticalHeader().setVisible(False)
        self.setupTable.verticalHeader().setHighlightSections(False)
        self.setupSaveButton = QPushButton(self.setupTab)
        self.setupSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.setupSaveButton.setObjectName("setupSaveButton")
        self.setupSaveButton.setText("Save")
        self.createTabWidget.addTab(self.setupTab, "")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.createTab), "Create New Game")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.setupTab), "Set Up Game")
        self.stackedWidget.addWidget(self.createPage)
        
        # Game page
        self.gamePage = QWidget()
        self.gamePage.setObjectName("gamePage")
        self.gameTabWidget = QTabWidget(self.gamePage)
        self.gameTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))
        self.gameTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.gameTabWidget.setObjectName("gameTabWidget")
        self.statusTab = QWidget()
        self.statusTab.setObjectName("statusTab")
        self.startGameButton = QPushButton(self.statusTab)
        self.startGameButton.setGeometry(QtCore.QRect(60, 180, 180, 60))
        self.startGameButton.setObjectName("startGameButton")
        self.startGameButton.setText("Start Game")
        self.endGameButton = QPushButton(self.statusTab)
        self.endGameButton.setGeometry(QtCore.QRect(60, 260, 180, 60))
        self.endGameButton.setObjectName("endGameButton")
        self.endGameButton.setText("End Game")
        self.loadGameLabel = QLabel(self.statusTab)
        self.loadGameLabel.setGeometry(QtCore.QRect(20, 65, 101, 21))

        font.setPointSize(15)
        self.loadGameLabel.setFont(font)
        self.loadGameLabel.setObjectName("loadGameLabel")
        self.loadGameLabel.setText("Load Game")
        self.gameTabWidget.addTab(self.statusTab, "")
        self.logTab = QWidget()
        self.logTab.setObjectName("logTab")
        self.logList = QListWidget(self.logTab)
        self.logList.setGeometry(QtCore.QRect(30, 30, 730, 500))
        self.logList.setObjectName("logList")
        self.gameTabWidget.addTab(self.logTab, "")
        self.inputTab = QWidget()
        self.inputTab.setObjectName("inputTab")
        self.gameTabWidget.addTab(self.inputTab, "")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.statusTab), "Game Status")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.logTab), "Game Log")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.inputTab), "Input")
        self.stackedWidget.addWidget(self.gamePage)
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        self.createTabWidget.setCurrentIndex(0)
        self.gameTabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass
コード例 #41
0
class OWImportImages(widget.OWWidget):
    name = "Import Images"
    description = "Import images from a directory(s)"
    icon = "icons/ImportImages.svg"
    priority = 110

    outputs = [("Data", Orange.data.Table)]

    #: list of recent paths
    recent_paths = settings.Setting([])  # type: List[RecentPath]
    currentPath = settings.Setting(None)

    want_main_area = False
    resizing_enabled = False

    Modality = Qt.ApplicationModal
    # Modality = Qt.WindowModal

    MaxRecentItems = 20

    def __init__(self):
        super().__init__()
        #: widget's runtime state
        self.__state = State.NoState
        self._imageMeta = []
        self._imageCategories = {}

        self.__invalidated = False
        self.__pendingTask = None

        vbox = gui.vBox(self.controlArea)
        hbox = gui.hBox(vbox)
        self.recent_cb = QComboBox(
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
            minimumContentsLength=16,
        )
        self.recent_cb.activated[int].connect(self.__onRecentActivated)
        icons = standard_icons(self)

        browseaction = QAction(
            "Open/Load Images",
            self,
            iconText="\N{HORIZONTAL ELLIPSIS}",
            icon=icons.dir_open_icon,
            toolTip="Select a directory from which to load the images")
        browseaction.triggered.connect(self.__runOpenDialog)
        reloadaction = QAction("Reload",
                               self,
                               icon=icons.reload_icon,
                               toolTip="Reload current image set")
        reloadaction.triggered.connect(self.reload)
        self.__actions = namespace(
            browse=browseaction,
            reload=reloadaction,
        )

        browsebutton = QPushButton(browseaction.iconText(),
                                   icon=browseaction.icon(),
                                   toolTip=browseaction.toolTip(),
                                   clicked=browseaction.trigger)
        reloadbutton = QPushButton(
            reloadaction.iconText(),
            icon=reloadaction.icon(),
            clicked=reloadaction.trigger,
            default=True,
        )

        hbox.layout().addWidget(self.recent_cb)
        hbox.layout().addWidget(browsebutton)
        hbox.layout().addWidget(reloadbutton)

        self.addActions([browseaction, reloadaction])

        reloadaction.changed.connect(
            lambda: reloadbutton.setEnabled(reloadaction.isEnabled()))
        box = gui.vBox(vbox, "Info")
        self.infostack = QStackedWidget()

        self.info_area = QLabel(text="No image set selected", wordWrap=True)
        self.progress_widget = QProgressBar(minimum=0, maximum=0)
        self.cancel_button = QPushButton(
            "Cancel",
            icon=icons.cancel_icon,
        )
        self.cancel_button.clicked.connect(self.cancel)

        w = QWidget()
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        hlayout = QHBoxLayout()
        hlayout.setContentsMargins(0, 0, 0, 0)

        hlayout.addWidget(self.progress_widget)
        hlayout.addWidget(self.cancel_button)
        vlayout.addLayout(hlayout)

        self.pathlabel = TextLabel()
        self.pathlabel.setTextElideMode(Qt.ElideMiddle)
        self.pathlabel.setAttribute(Qt.WA_MacSmallSize)

        vlayout.addWidget(self.pathlabel)
        w.setLayout(vlayout)

        self.infostack.addWidget(self.info_area)
        self.infostack.addWidget(w)

        box.layout().addWidget(self.infostack)

        self.__initRecentItemsModel()
        self.__invalidated = True
        self.__executor = ThreadExecutor(self)

        QApplication.postEvent(self, QEvent(RuntimeEvent.Init))

    def __initRecentItemsModel(self):
        if self.currentPath is not None and \
                not os.path.isdir(self.currentPath):
            self.currentPath = None

        recent_paths = []
        for item in self.recent_paths:
            if os.path.isdir(item.abspath):
                recent_paths.append(item)
        recent_paths = recent_paths[:OWImportImages.MaxRecentItems]
        recent_model = self.recent_cb.model()
        for pathitem in recent_paths:
            item = RecentPath_asqstandarditem(pathitem)
            recent_model.appendRow(item)

        self.recent_paths = recent_paths

        if self.currentPath is not None and \
                os.path.isdir(self.currentPath) and self.recent_paths and \
                os.path.samefile(self.currentPath, self.recent_paths[0].abspath):
            self.recent_cb.setCurrentIndex(0)
        else:
            self.currentPath = None
            self.recent_cb.setCurrentIndex(-1)
        self.__actions.reload.setEnabled(self.currentPath is not None)

    def customEvent(self, event):
        """Reimplemented."""
        if event.type() == RuntimeEvent.Init:
            if self.__invalidated:
                try:
                    self.start()
                finally:
                    self.__invalidated = False

        super().customEvent(event)

    def __runOpenDialog(self):
        startdir = os.path.expanduser("~/")
        if self.recent_paths:
            startdir = self.recent_paths[0].abspath

        if OWImportImages.Modality == Qt.WindowModal:
            dlg = QFileDialog(
                self,
                "Select Top Level Directory",
                startdir,
                acceptMode=QFileDialog.AcceptOpen,
                modal=True,
            )
            dlg.setFileMode(QFileDialog.Directory)
            dlg.setOption(QFileDialog.ShowDirsOnly)
            dlg.setDirectory(startdir)
            dlg.setAttribute(Qt.WA_DeleteOnClose)

            @dlg.accepted.connect
            def on_accepted():
                dirpath = dlg.selectedFiles()
                if dirpath:
                    self.setCurrentPath(dirpath[0])
                    self.start()

            dlg.open()
        else:
            dirpath = QFileDialog.getExistingDirectory(
                self, "Select Top Level Directory", startdir)
            if dirpath:
                self.setCurrentPath(dirpath)
                self.start()

    def __onRecentActivated(self, index):
        item = self.recent_cb.itemData(index)
        if item is None:
            return
        assert isinstance(item, RecentPath)
        self.setCurrentPath(item.abspath)
        self.start()

    def __updateInfo(self):
        if self.__state == State.NoState:
            text = "No image set selected"
        elif self.__state == State.Processing:
            text = "Processing"
        elif self.__state == State.Done:
            nvalid = sum(imeta.isvalid for imeta in self._imageMeta)
            ncategories = len(self._imageCategories)
            if ncategories < 2:
                text = "{} images".format(nvalid)
            else:
                text = "{} images / {} categories".format(nvalid, ncategories)
        elif self.__state == State.Cancelled:
            text = "Cancelled"
        elif self.__state == State.Error:
            text = "Error state"
        else:
            assert False

        self.info_area.setText(text)

        if self.__state == State.Processing:
            self.infostack.setCurrentIndex(1)
        else:
            self.infostack.setCurrentIndex(0)

    def setCurrentPath(self, path):
        """
        Set the current root image path to path

        If the path does not exists or is not a directory the current path
        is left unchanged

        Parameters
        ----------
        path : str
            New root import path.

        Returns
        -------
        status : bool
            True if the current root import path was successfully
            changed to path.
        """
        if self.currentPath is not None and path is not None and \
                os.path.isdir(self.currentPath) and os.path.isdir(path) and \
                os.path.samefile(self.currentPath, path):
            return True

        if not os.path.exists(path):
            warnings.warn("'{}' does not exist".format(path), UserWarning)
            return False
        elif not os.path.isdir(path):
            warnings.warn("'{}' is not a directory".format(path), UserWarning)
            return False

        newindex = self.addRecentPath(path)
        self.recent_cb.setCurrentIndex(newindex)
        if newindex >= 0:
            self.currentPath = path
        else:
            self.currentPath = None
        self.__actions.reload.setEnabled(self.currentPath is not None)

        if self.__state == State.Processing:
            self.cancel()

        return True

    def addRecentPath(self, path):
        """
        Prepend a path entry to the list of recent paths

        If an entry with the same path already exists in the recent path
        list it is moved to the first place

        Parameters
        ----------
        path : str
        """
        existing = None
        for pathitem in self.recent_paths:
            if os.path.samefile(pathitem.abspath, path):
                existing = pathitem
                break

        model = self.recent_cb.model()

        if existing is not None:
            selected_index = self.recent_paths.index(existing)
            assert model.item(selected_index).data(Qt.UserRole) is existing
            self.recent_paths.remove(existing)
            row = model.takeRow(selected_index)
            self.recent_paths.insert(0, existing)
            model.insertRow(0, row)
        else:
            item = RecentPath(path, None, None)
            self.recent_paths.insert(0, item)
            model.insertRow(0, RecentPath_asqstandarditem(item))
        return 0

    def __setRuntimeState(self, state):
        assert state in State
        self.setBlocking(state == State.Processing)
        message = ""
        if state == State.Processing:
            assert self.__state in [
                State.Done, State.NoState, State.Error, State.Cancelled
            ]
            message = "Processing"
        elif state == State.Done:
            assert self.__state == State.Processing
        elif state == State.Cancelled:
            assert self.__state == State.Processing
            message = "Cancelled"
        elif state == State.Error:
            message = "Error during processing"
        elif state == State.NoState:
            message = ""
        else:
            assert False

        self.__state = state

        if self.__state == State.Processing:
            self.infostack.setCurrentIndex(1)
        else:
            self.infostack.setCurrentIndex(0)

        self.setStatusMessage(message)
        self.__updateInfo()

    def reload(self):
        """
        Restart the image scan task
        """
        if self.__state == State.Processing:
            self.cancel()

        self._imageMeta = []
        self._imageCategories = {}
        self.start()

    def start(self):
        """
        Start/execute the image indexing operation
        """
        self.error()

        self.__invalidated = False
        if self.currentPath is None:
            return

        if self.__state == State.Processing:
            assert self.__pendingTask is not None
            log.info("Starting a new task while one is in progress. "
                     "Cancel the existing task (dir:'{}')".format(
                         self.__pendingTask.startdir))
            self.cancel()

        startdir = self.currentPath

        self.__setRuntimeState(State.Processing)

        report_progress = methodinvoke(self, "__onReportProgress", (object, ))

        task = ImageScan(startdir, report_progress=report_progress)

        # collect the task state in one convenient place
        self.__pendingTask = taskstate = namespace(
            task=task,
            startdir=startdir,
            future=None,
            watcher=None,
            cancelled=False,
            cancel=None,
        )

        def cancel():
            # Cancel the task and disconnect
            if taskstate.future.cancel():
                pass
            else:
                taskstate.task.cancelled = True
                taskstate.cancelled = True
                try:
                    taskstate.future.result(timeout=3)
                except UserInterruptError:
                    pass
                except TimeoutError:
                    log.info("The task did not stop in in a timely manner")
            taskstate.watcher.finished.disconnect(self.__onRunFinished)

        taskstate.cancel = cancel

        def run_image_scan_task_interupt():
            try:
                return task.run()
            except UserInterruptError:
                # Suppress interrupt errors, so they are not logged
                return

        taskstate.future = self.__executor.submit(run_image_scan_task_interupt)
        taskstate.watcher = FutureWatcher(taskstate.future)
        taskstate.watcher.finished.connect(self.__onRunFinished)

    @Slot()
    def __onRunFinished(self):
        assert QThread.currentThread() is self.thread()
        assert self.__state == State.Processing
        assert self.__pendingTask is not None
        assert self.sender() is self.__pendingTask.watcher
        assert self.__pendingTask.future.done()
        task = self.__pendingTask
        self.__pendingTask = None

        try:
            image_meta = task.future.result()
        except Exception as err:
            sys.excepthook(*sys.exc_info())
            state = State.Error
            image_meta = []
            self.error(traceback.format_exc())
        else:
            state = State.Done
            self.error()

        categories = {}

        for imeta in image_meta:
            # derive categories from the path relative to the starting dir
            dirname = os.path.dirname(imeta.path)
            relpath = os.path.relpath(dirname, task.startdir)
            categories[dirname] = relpath

        self._imageMeta = image_meta
        self._imageCategories = categories

        self.__setRuntimeState(state)
        self.commit()

    def cancel(self):
        """
        Cancel current pending task (if any).
        """
        if self.__state == State.Processing:
            assert self.__pendingTask is not None
            self.__pendingTask.cancel()
            self.__pendingTask = None
            self.__setRuntimeState(State.Cancelled)

    @Slot(object)
    def __onReportProgress(self, arg):
        # report on scan progress from a worker thread
        # arg must be a namespace(count: int, lastpath: str)
        assert QThread.currentThread() is self.thread()
        if self.__state == State.Processing:
            self.pathlabel.setText(prettyfypath(arg.lastpath))

    def commit(self):
        """
        Create and commit a Table from the collected image meta data.
        """
        if self._imageMeta:
            categories = self._imageCategories
            if len(categories) > 1:
                cat_var = Orange.data.DiscreteVariable(
                    "category", values=list(sorted(categories.values())))
            else:
                cat_var = None
            # Image name (file basename without the extension)
            imagename_var = Orange.data.StringVariable("image name")
            # Full fs path
            image_var = Orange.data.StringVariable("image")
            image_var.attributes["type"] = "image"
            # file size/width/height
            size_var = Orange.data.ContinuousVariable("size",
                                                      number_of_decimals=0)
            width_var = Orange.data.ContinuousVariable("width",
                                                       number_of_decimals=0)
            height_var = Orange.data.ContinuousVariable("height",
                                                        number_of_decimals=0)
            domain = Orange.data.Domain(
                [], [cat_var] if cat_var is not None else [],
                [imagename_var, image_var, size_var, width_var, height_var])
            cat_data = []
            meta_data = []

            for imgmeta in self._imageMeta:
                if imgmeta.isvalid:
                    if cat_var is not None:
                        category = categories.get(os.path.dirname(
                            imgmeta.path))
                        cat_data.append([cat_var.to_val(category)])
                    else:
                        cat_data.append([])
                    basename = os.path.basename(imgmeta.path)
                    imgname, _ = os.path.splitext(basename)

                    meta_data.append([
                        imgname, imgmeta.path, imgmeta.size, imgmeta.width,
                        imgmeta.height
                    ])

            cat_data = numpy.array(cat_data, dtype=float)
            meta_data = numpy.array(meta_data, dtype=object)
            table = Orange.data.Table.from_numpy(
                domain, numpy.empty((len(cat_data), 0), dtype=float), cat_data,
                meta_data)
        else:
            table = None

        self.send("Data", table)

    def onDeleteWidget(self):
        self.cancel()
        self.__executor.shutdown(wait=True)
コード例 #42
0
ファイル: winged.py プロジェクト: ifara/wingedbox-client
 def setCurrentIndex(self, index):
     self.fader_widget = FaderWidget(self.currentWidget(), self.widget(index))
     QStackedWidget.setCurrentIndex(self, index)
コード例 #43
0
class FltsSearchDockWidget(QDockWidget):
    """
    Dock widget for showing search widgets with each widget corresponding to
    a search configuration.
    """
    def __init__(self, *args, **kwargs):
        super(FltsSearchDockWidget, self).__init__(*args, **kwargs)
        self.setAllowedAreas(Qt.BottomDockWidgetArea)
        self._search_reg = SearchConfigurationRegistry.instance()
        self._stack_widget = QStackedWidget(self)
        self.setWidget(self._stack_widget)

        # Index data source to their location in the stack widget
        self._search_widget_idx = dict()

    def show_search_widget(self, data_source):
        """
        Shows the search widget associated with the given data source. If
        not found then it will create a new one by using the factory
        method in the search configuration.
        :param data_source: Data source name.
        :type data_source: str
        :return: Returns True if the operation was successful else False. It
        will be false if the data source is not found in the registry.
        :rtype: bool
        """
        config = self._search_reg.search_config(data_source)
        if not config:
            return False

        # Set current search widget
        self._set_current_widget(config)

        return True

    def _set_current_widget(self, config):
        # Updates dock widget based on the specified config.
        data_source = config.data_source

        # Create widget if it does not exist in the stack
        if not data_source in self._search_widget_idx:
            search_widget = config.create_widget()
            idx = self._stack_widget.addWidget(search_widget)
            self._search_widget_idx[data_source] = idx
        else:
            idx = self._search_widget_idx[data_source]

        self._stack_widget.setCurrentIndex(idx)

        # Set title
        self.setWindowTitle(u'Search {0}'.format(config.display_name))

    def current_widget(self):
        """
        :return: Returns the current search widget or None if there are no
        widgets in the stack.
        :rtype: QWidget
        """
        return self._stack_widget.currentWidget()

    def clear(self):
        """
        Removes all the search widgets and resets the indices.
        """
        while self._stack_widget.count() > 0:
            sw = self._stack_widget.widget(0)
            self._stack_widget.removeWidget(sw)
            del sw

        self._search_widget_idx = dict()
コード例 #44
0
ファイル: LeapFlow.py プロジェクト: Clepto/LeapFlow
class LeapFlow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.controller = Controller()
        self.listener = LeapListener(self)
        self.controller.add_listener(self.listener)

        self.mode = "gallery"
        self.scroll = False
        self.direction = ""
        self.direction_x = 0
        self.scroll_velocity = 0
        self.current_index = 0

        # List containing images for the gallery
        self.list_view = QListWidget()
        self.list_view.setFlow(0)
        self.list_view.setHorizontalScrollMode(1)
        self.list_view.setMouseTracking(True)
        self.list_view.itemClicked.connect(self.show_image)

        # Setting the style of the ListView, background, item selected, etc
        self.list_view.setStyleSheet(
            """
				QListWidget::item:hover {background: transparent;}
				QListWidget::item:disabled:hover {background: transparent;}
				QListWidget::item:hover:!active {background: transparent;}
				QListWidget::item:selected:active {background: transparent;}
	            QListWidget::item:selected:!active {background: transparent;}
	            QListWidget::item:selected:disabled {background: transparent;}
	            QListWidget::item:selected:!disabled {background: transparent;}
	            QListWidget {background: #2C3539}
			"""
        )

        # Image viewer
        self.scene = QGraphicsScene()
        self.viewer = QGraphicsView(self.scene)

        self.stackedWidget = QStackedWidget()
        self.stackedWidget.addWidget(self.list_view)
        self.stackedWidget.addWidget(self.viewer)

        self.setCentralWidget(self.stackedWidget)
        self.resize(500, 400)
        self.showMaximized()

        scan = ScanLibrary("/home/chris/Example")
        threads.append(scan)
        self.connect(scan, SIGNAL(scan.signal), self.add_images_to_list)
        scan.start()

        self.connect(self, SIGNAL("scrollChanged(bool)"), self.scroll_view)

    def setScroll(self, scroll):
        """Emit signal to scroll the view"""
        if self.scroll != scroll:
            self.scroll = scroll
            self.emit(SIGNAL("scrollChanged(bool)"), scroll)

    def scroll_view(self):
        """Scroll the view based on scroll velocity and direction"""

        x = self.direction_x * self.scroll_velocity / 100
        bar_x = self.list_view.horizontalScrollBar().value()
        self.list_view.horizontalScrollBar().setValue(bar_x + x)

    def add_images_to_list(self):
        """To add a widget to the listview you must add a QListWidgetItem
		and replace with your widget"""

        for image in library:
            item = QListWidgetItem()
            pixmap = QPixmap.fromImage(QImage(library[image]))
            label = QLabel()
            label.setPixmap(pixmap.scaled(600, 400))
            item.setSizeHint(label.sizeHint())
            item.setData(0, library[image])
            self.list_view.addItem(item)
            self.list_view.setItemWidget(item, label)

    def show_image(self, item):
        """"Display the selected image"""

        self.current_index = self.list_view.indexFromItem(item).row()
        self.scene.addPixmap((QPixmap.fromImage(QImage(item.text()))).scaled(self.viewer.size()))

        self.stackedWidget.setCurrentIndex(1)
        self.mode = "viewer"

    def previous_image(self):
        """Load previous image"""

        if self.current_index - 1 >= 0:
            self.current_index -= 1
            self.load_image()

    def next_image(self):
        """Load next image"""

        if self.current_index + 1 <= len(library.keys()) - 1:
            self.current_index += 1
            self.load_image()

    def load_image(self):
        """Load the image in self.current_index"""

        self.scene.addPixmap(QPixmap.fromImage(QImage(library[library.keys()[self.current_index]])))
コード例 #45
0
class E4SideBar(QWidget):
    """
    Class implementing a sidebar with a widget area, that is hidden or shown, if the
    current tab is clicked again.
    """
    Version = 1
    
    North = 0
    East  = 1
    South = 2
    West  = 3
    
    def __init__(self, orientation = None, delay = 200, parent = None):
        """
        Constructor
        
        @param orientation orientation of the sidebar widget (North, East, South, West)
        @param delay value for the expand/shrink delay in milliseconds (integer)
        @param parent parent widget (QWidget)
        """
        QWidget.__init__(self, parent)
        
        self.__tabBar = QTabBar()
        self.__tabBar.setDrawBase(True)
        self.__tabBar.setShape(QTabBar.RoundedNorth)
        self.__tabBar.setUsesScrollButtons(True)
        self.__tabBar.setDrawBase(False)
        self.__stackedWidget = QStackedWidget(self)
        self.__stackedWidget.setContentsMargins(0, 0, 0, 0)
        self.__autoHideButton = QToolButton()
        self.__autoHideButton.setCheckable(True)
        self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png"))
        self.__autoHideButton.setChecked(True)
        self.__autoHideButton.setToolTip(
            self.trUtf8("Deselect to activate automatic collapsing"))
        self.barLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.barLayout.setMargin(0)
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.layout.setMargin(0)
        self.layout.setSpacing(0)
        self.barLayout.addWidget(self.__autoHideButton)
        self.barLayout.addWidget(self.__tabBar)
        self.layout.addLayout(self.barLayout)
        self.layout.addWidget(self.__stackedWidget)
        self.setLayout(self.layout)
        
        # initialize the delay timer
        self.__actionMethod = None
        self.__delayTimer = QTimer(self)
        self.__delayTimer.setSingleShot(True)
        self.__delayTimer.setInterval(delay)
        self.connect(self.__delayTimer, SIGNAL("timeout()"), self.__delayedAction)
        
        self.__minimized = False
        self.__minSize = 0
        self.__maxSize = 0
        self.__bigSize = QSize()
        
        self.splitter = None
        self.splitterSizes = []
        
        self.__hasFocus = False # flag storing if this widget or any child has the focus
        self.__autoHide = False
        
        self.__tabBar.installEventFilter(self)
        
        self.__orientation = E4SideBar.North
        if orientation is None:
            orientation = E4SideBar.North
        self.setOrientation(orientation)
        
        self.connect(self.__tabBar, SIGNAL("currentChanged(int)"), 
                     self.__stackedWidget, SLOT("setCurrentIndex(int)"))
        self.connect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), 
                     self.__appFocusChanged)
        self.connect(self.__autoHideButton, SIGNAL("toggled(bool)"), 
                     self.__autoHideToggled)
    
    def setSplitter(self, splitter):
        """
        Public method to set the splitter managing the sidebar.
        
        @param splitter reference to the splitter (QSplitter)
        """
        self.splitter = splitter
        self.connect(self.splitter, SIGNAL("splitterMoved(int, int)"), 
                     self.__splitterMoved)
        self.splitter.setChildrenCollapsible(False)
        index = self.splitter.indexOf(self)
        self.splitter.setCollapsible(index, False)
    
    def __splitterMoved(self, pos, index):
        """
        Private slot to react on splitter moves.
        
        @param pos new position of the splitter handle (integer)
        @param index index of the splitter handle (integer)
        """
        if self.splitter:
            self.splitterSizes = self.splitter.sizes()
    
    def __delayedAction(self):
        """
        Private slot to handle the firing of the delay timer.
        """
        if self.__actionMethod is not None:
            self.__actionMethod()
    
    def setDelay(self, delay):
        """
        Public method to set the delay value for the expand/shrink delay in milliseconds.
        
        @param delay value for the expand/shrink delay in milliseconds (integer)
        """
        self.__delayTimer.setInterval(delay)
    
    def delay(self):
        """
        Public method to get the delay value for the expand/shrink delay in milliseconds.
        
        @return value for the expand/shrink delay in milliseconds (integer)
        """
        return self.__delayTimer.interval()
    
    def __cancelDelayTimer(self):
        """
        Private method to cancel the current delay timer.
        """
        self.__delayTimer.stop()
        self.__actionMethod = None
    
    def shrink(self):
        """
        Public method to record a shrink request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__shrinkIt
        self.__delayTimer.start()
   
    def __shrinkIt(self):
        """
        Private method to shrink the sidebar.
        """
        self.__minimized = True
        self.__bigSize = self.size()
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
            self.__maxSize = self.maximumHeight()
        else:
            self.__minSize = self.minimumSizeHint().width()
            self.__maxSize = self.maximumWidth()
        if self.splitter:
            self.splitterSizes = self.splitter.sizes()
        
        self.__stackedWidget.hide()
        
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.setFixedHeight(self.__tabBar.minimumSizeHint().height())
        else:
            self.setFixedWidth(self.__tabBar.minimumSizeHint().width())
        
        self.__actionMethod = None
    
    def expand(self):
        """
        Private method to record a expand request.
        """
        self.__delayTimer.stop()
        self.__actionMethod = self.__expandIt
        self.__delayTimer.start()
    
    def __expandIt(self):
        """
        Public method to expand the sidebar.
        """
        self.__minimized = False
        self.__stackedWidget.show()
        self.resize(self.__bigSize)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            minSize = max(self.__minSize, self.minimumSizeHint().height())
            self.setMinimumHeight(minSize)
            self.setMaximumHeight(self.__maxSize)
        else:
            minSize = max(self.__minSize, self.minimumSizeHint().width())
            self.setMinimumWidth(minSize)
            self.setMaximumWidth(self.__maxSize)
        if self.splitter:
            self.splitter.setSizes(self.splitterSizes)
        
        self.__actionMethod = None
    
    def isMinimized(self):
        """
        Public method to check the minimized state.
        
        @return flag indicating the minimized state (boolean)
        """
        return self.__minimized
    
    def isAutoHiding(self):
        """
        Public method to check, if the auto hide function is active.
        
        @return flag indicating the state of auto hiding (boolean)
        """
        return self.__autoHide
    
    def eventFilter(self, obj, evt):
        """
        Protected method to handle some events for the tabbar.
        
        @param obj reference to the object (QObject)
        @param evt reference to the event object (QEvent)
        @return flag indicating, if the event was handled (boolean)
        """
        if obj == self.__tabBar:
            if evt.type() == QEvent.MouseButtonPress:
                pos = evt.pos()
                for i in range(self.__tabBar.count()):
                    if self.__tabBar.tabRect(i).contains(pos):
                        break
                
                if i == self.__tabBar.currentIndex():
                    if self.isMinimized():
                        self.expand()
                    else:
                        self.shrink()
                    return True
                elif self.isMinimized():
                    self.expand()
            elif evt.type() == QEvent.Wheel and not self.__stackedWidget.isHidden():
                if evt.delta() > 0:
                    self.prevTab()
                else:
                    self.nextTab()
                return True
        
        return QWidget.eventFilter(self, obj, evt)
    
    def addTab(self, widget, iconOrLabel, label = None):
        """
        Public method to add a tab to the sidebar.
        
        @param widget reference to the widget to add (QWidget)
        @param iconOrLabel reference to the icon or the labeltext of the tab
            (QIcon, string or QString)
        @param label the labeltext of the tab (string or QString) (only to be
            used, if the second parameter is a QIcon)
        """
        if label:
            index = self.__tabBar.addTab(iconOrLabel, label)
            self.__tabBar.setTabToolTip(index, label)
        else:
            index = self.__tabBar.addTab(iconOrLabel)
            self.__tabBar.setTabToolTip(index, iconOrLabel)
        self.__stackedWidget.addWidget(widget)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def insertTab(self, index, widget, iconOrLabel, label = None):
        """
        Public method to insert a tab into the sidebar.
        
        @param index the index to insert the tab at (integer)
        @param widget reference to the widget to insert (QWidget)
        @param iconOrLabel reference to the icon or the labeltext of the tab
            (QIcon, string or QString)
        @param label the labeltext of the tab (string or QString) (only to be
            used, if the second parameter is a QIcon)
        """
        if label:
            index = self.__tabBar.insertTab(index, iconOrLabel, label)
            self.__tabBar.setTabToolTip(index, label)
        else:
            index = self.__tabBar.insertTab(index, iconOrLabel)
            self.__tabBar.setTabToolTip(index, iconOrLabel)
        self.__stackedWidget.insertWidget(index, widget)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def removeTab(self, index):
        """
        Public method to remove a tab.
        
        @param index the index of the tab to remove (integer)
        """
        self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index))
        self.__tabBar.removeTab(index)
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            self.__minSize = self.minimumSizeHint().height()
        else:
            self.__minSize = self.minimumSizeHint().width()
    
    def clear(self):
        """
        Public method to remove all tabs.
        """
        while self.count() > 0:
            self.removeTab(0)
    
    def prevTab(self):
        """
        Public slot used to show the previous tab.
        """
        ind = self.currentIndex() - 1
        if ind == -1:
            ind = self.count() - 1
            
        self.setCurrentIndex(ind)
        self.currentWidget().setFocus()
    
    def nextTab(self):
        """
        Public slot used to show the next tab.
        """
        ind = self.currentIndex() + 1
        if ind == self.count():
            ind = 0
            
        self.setCurrentIndex(ind)
        self.currentWidget().setFocus()
    
    def count(self):
        """
        Public method to get the number of tabs.
        
        @return number of tabs in the sidebar (integer)
        """
        return self.__tabBar.count()
    
    def currentIndex(self):
        """
        Public method to get the index of the current tab.
        
        @return index of the current tab (integer)
        """
        return self.__stackedWidget.currentIndex()
    
    def setCurrentIndex(self, index):
        """
        Public slot to set the current index.
        
        @param index the index to set as the current index (integer)
        """
        self.__tabBar.setCurrentIndex(index)
        self.__stackedWidget.setCurrentIndex(index)
        if self.isMinimized():
            self.expand()
    
    def currentWidget(self):
        """
        Public method to get a reference to the current widget.
        
        @return reference to the current widget (QWidget)
        """
        return self.__stackedWidget.currentWidget()
    
    def setCurrentWidget(self, widget):
        """
        Public slot to set the current widget.
        
        @param widget reference to the widget to become the current widget (QWidget)
        """
        self.__stackedWidget.setCurrentWidget(widget)
        self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex())
        if self.isMinimized():
            self.expand()
    
    def indexOf(self, widget):
        """
        Public method to get the index of the given widget.
        
        @param widget reference to the widget to get the index of (QWidget)
        @return index of the given widget (integer)
        """
        return self.__stackedWidget.indexOf(widget)
    
    def isTabEnabled(self, index):
        """
        Public method to check, if a tab is enabled.
        
        @param index index of the tab to check (integer)
        @return flag indicating the enabled state (boolean)
        """
        return self.__tabBar.isTabEnabled(index)
    
    def setTabEnabled(self, index, enabled):
        """
        Public method to set the enabled state of a tab.
        
        @param index index of the tab to set (integer)
        @param enabled enabled state to set (boolean)
        """
        self.__tabBar.setTabEnabled(index, enabled)
    
    def orientation(self):
        """
        Public method to get the orientation of the sidebar.
        
        @return orientation of the sidebar (North, East, South, West)
        """
        return self.__orientation
    
    def setOrientation(self, orient):
        """
        Public method to set the orientation of the sidebar.
        @param orient orientation of the sidebar (North, East, South, West)
        """
        if orient == E4SideBar.North:
            self.__tabBar.setShape(QTabBar.RoundedNorth)
            self.__tabBar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == E4SideBar.East:
            self.__tabBar.setShape(QTabBar.RoundedEast)
            self.__tabBar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.RightToLeft)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        elif orient == E4SideBar.South:
            self.__tabBar.setShape(QTabBar.RoundedSouth)
            self.__tabBar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
            self.barLayout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setDirection(QBoxLayout.BottomToTop)
            self.layout.setAlignment(self.barLayout, Qt.AlignLeft)
        elif orient == E4SideBar.West:
            self.__tabBar.setShape(QTabBar.RoundedWest)
            self.__tabBar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
            self.barLayout.setDirection(QBoxLayout.TopToBottom)
            self.layout.setDirection(QBoxLayout.LeftToRight)
            self.layout.setAlignment(self.barLayout, Qt.AlignTop)
        self.__orientation = orient
    
    def tabIcon(self, index):
        """
        Public method to get the icon of a tab.
        
        @param index index of the tab (integer)
        @return icon of the tab (QIcon)
        """
        return self.__tabBar.tabIcon(index)
    
    def setTabIcon(self, index, icon):
        """
        Public method to set the icon of a tab.
        
        @param index index of the tab (integer)
        @param icon icon to be set (QIcon)
        """
        self.__tabBar.setTabIcon(index, icon)
    
    def tabText(self, index):
        """
        Public method to get the text of a tab.
        
        @param index index of the tab (integer)
        @return text of the tab (QString)
        """
        return self.__tabBar.tabText(index)
    
    def setTabText(self, index, text):
        """
        Public method to set the text of a tab.
        
        @param index index of the tab (integer)
        @param text text to set (QString)
        """
        self.__tabBar.setTabText(index, text)
    
    def tabToolTip(self, index):
        """
        Public method to get the tooltip text of a tab.
        
        @param index index of the tab (integer)
        @return tooltip text of the tab (QString)
        """
        return self.__tabBar.tabToolTip(index)
    
    def setTabToolTip(self, index, tip):
        """
        Public method to set the tooltip text of a tab.
        
        @param index index of the tab (integer)
        @param tooltip text text to set (QString)
        """
        self.__tabBar.setTabToolTip(index, tip)
    
    def tabWhatsThis(self, index):
        """
        Public method to get the WhatsThis text of a tab.
        
        @param index index of the tab (integer)
        @return WhatsThis text of the tab (QString)
        """
        return self.__tabBar.tabWhatsThis(index)
    
    def setTabWhatsThis(self, index, text):
        """
        Public method to set the WhatsThis text of a tab.
        
        @param index index of the tab (integer)
        @param WhatsThis text text to set (QString)
        """
        self.__tabBar.setTabWhatsThis(index, text)
    
    def widget(self, index):
        """
        Public method to get a reference to the widget associated with a tab.
        
        @param index index of the tab (integer)
        @return reference to the widget (QWidget)
        """
        return self.__stackedWidget.widget(index)
    
    def saveState(self):
        """
        Public method to save the state of the sidebar.
        
        @return saved state as a byte array (QByteArray)
        """
        if len(self.splitterSizes) == 0:
            if self.splitter:
                self.splitterSizes = self.splitter.sizes()
            self.__bigSize = self.size()
            if self.__orientation in [E4SideBar.North, E4SideBar.South]:
                self.__minSize = self.minimumSizeHint().height()
                self.__maxSize = self.maximumHeight()
            else:
                self.__minSize = self.minimumSizeHint().width()
                self.__maxSize = self.maximumWidth()
        
        data = QByteArray()
        stream = QDataStream(data, QIODevice.WriteOnly)
        
        stream.writeUInt16(self.Version)
        stream.writeBool(self.__minimized)
        stream << self.__bigSize
        stream.writeUInt16(self.__minSize)
        stream.writeUInt16(self.__maxSize)
        stream.writeUInt16(len(self.splitterSizes))
        for size in self.splitterSizes:
            stream.writeUInt16(size)
        stream.writeBool(self.__autoHide)
        
        return data
    
    def restoreState(self, state):
        """
        Public method to restore the state of the sidebar.
        
        @param state byte array containing the saved state (QByteArray)
        @return flag indicating success (boolean)
        """
        if state.isEmpty():
            return False
        
        if self.__orientation in [E4SideBar.North, E4SideBar.South]:
            minSize = self.layout.minimumSize().height()
            maxSize = self.maximumHeight()
        else:
            minSize = self.layout.minimumSize().width()
            maxSize = self.maximumWidth()
        
        data = QByteArray(state)
        stream = QDataStream(data, QIODevice.ReadOnly)
        stream.readUInt16()  # version
        minimized = stream.readBool()
        
        if minimized:
            self.shrink()
        
        stream >> self.__bigSize
        self.__minSize = max(stream.readUInt16(), minSize)
        self.__maxSize = max(stream.readUInt16(), maxSize)
        count = stream.readUInt16()
        self.splitterSizes = []
        for i in range(count):
            self.splitterSizes.append(stream.readUInt16())
        
        self.__autoHide = stream.readBool()
        self.__autoHideButton.setChecked(not self.__autoHide)
        
        if not minimized:
            self.expand()
        
        return True
    
    #######################################################################
    ## methods below implement the autohide functionality
    #######################################################################
    
    def __autoHideToggled(self, checked):
        """
        Private slot to handle the toggling of the autohide button.
        
        @param checked flag indicating the checked state of the button (boolean)
        """
        self.__autoHide = not checked
        if self.__autoHide:
            self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOn.png"))
        else:
            self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png"))
    
    def __appFocusChanged(self, old, now):
        """
        Private slot to handle a change of the focus.
        
        @param old reference to the widget, that lost focus (QWidget or None)
        @param now reference to the widget having the focus (QWidget or None)
        """
        self.__hasFocus = self.isAncestorOf(now)
        if self.__autoHide and not self.__hasFocus and not self.isMinimized():
            self.shrink()
        elif self.__autoHide and self.__hasFocus and self.isMinimized():
            self.expand()
    
    def enterEvent(self, event):
        """
        Protected method to handle the mouse entering this widget.
        
        @param event reference to the event (QEvent)
        """
        if self.__autoHide and self.isMinimized():
            self.expand()
        else:
            self.__cancelDelayTimer()
    
    def leaveEvent(self, event):
        """
        Protected method to handle the mouse leaving this widget.
        
        @param event reference to the event (QEvent)
        """
        if self.__autoHide and not self.__hasFocus and not self.isMinimized():
            self.shrink()
        else:
            self.__cancelDelayTimer()
    
    def shutdown(self):
        """
        Public method to shut down the object.
        
        This method does some preparations so the object can be deleted properly.
        It disconnects from the focusChanged signal in order to avoid trouble later
        on.
        """
        self.disconnect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), 
                        self.__appFocusChanged)
コード例 #46
0
 def setCurrentIndex(self, index):
     """Change the current widget being displayed with an animation."""
     self.fader_widget = ui_tools.FaderWidget(self.currentWidget(),
         self.widget(index))
     QStackedWidget.setCurrentIndex(self, index)
コード例 #47
0
ファイル: Declaration.py プロジェクト: TibbersBear/openfisca
class Declaration(QDialog, ui_declaration.Ui_Declaration):
    def __init__(self, parent, noi):
        super(Declaration, self).__init__(parent)
        self.setupUi(self)
        self.setStyleSheet(OfSs.declaration_page_style)
        self.noidec = noi
        self.parent = parent
        self.scenario = parent.scenario

        self.pages_widget = QStackedWidget(self)
        self.connect(self.pages_widget, SIGNAL("currentChanged(int)"),
                     self.current_page_changed)
        self.connect(self.contents_widget, SIGNAL("currentRowChanged(int)"),
                     self.pages_widget.setCurrentIndex)

        self.scrollArea.setWidget(self.pages_widget)

        self.connect(self.next_btn, SIGNAL('clicked()'), self.next_page)
        self.connect(self.prev_btn, SIGNAL('clicked()'), self.prev_page)

        self.pages = [
            Page01(self),
            Page02(self),
            Page03(self),
            Page04(self),
            Page05(self),
            Page06(self),
            Page07(self),
            PageIsf(self)
        ]

        for widget in self.pages:
            self.add_page(widget)

        self.set_current_index(0)
        self.current_page_changed(0)

    def current_page_changed(self, index):
        nb = self.pages_widget.count() - 1
        self.prev_btn.setEnabled(True)
        self.next_btn.setEnabled(True)
        if index == nb:
            self.next_btn.setEnabled(False)
        if index == 0:
            self.prev_btn.setEnabled(False)

    def next_page(self):
        idx = self.pages_widget.currentIndex()
        self.set_current_index(idx + 1)

    def prev_page(self):
        idx = self.pages_widget.currentIndex()
        self.set_current_index(idx - 1)

    def get_current_index(self):
        """Return current page index"""
        return self.contents_widget.currentRow()

    def set_current_index(self, index):
        """Set current page index"""
        self.contents_widget.setCurrentRow(index)
        self.pages_widget.setCurrentIndex(index)

    def accept(self):
        for page in self.pages:
            for key in page.__dict__:
                widget = getattr(page, key)
                if isinstance(widget, QSpinBox):
                    var = str(widget.objectName())
                    val = widget.value()
                    page.updateFoyer(var, val)
                elif isinstance(widget, QCheckBox):
                    var = str(widget.objectName())
                    val = 1 * (widget.checkState() >= 1)
                    page.updateFoyer(var, val)
        QDialog.accept(self)

    def add_page(self, widget):
        self.pages_widget.addWidget(widget)
        item = QListWidgetItem(self.contents_widget)
        item.setText(widget.get_name())
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)