Beispiel #1
0
class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.initTitle()
        self.initMainToolBar()
        self.initCentralWidget()

    def initTitle(self):
        pid = QApplication.instance().applicationPid()
        self.setWindowTitle("My Projects - ({0})".format(pid))

    def initMainToolBar(self):
        self.tb1 = self.addToolBar("ToolBar 1")
        self.tb1.addWidget(QLabel("ToolBar 1"))
        self.tb1.orientationChanged.connect(self.mainToolBarOrientationChanged)
        
        self.tb1.addSeparator()
        
        for index in range(5):
            pb = QPushButton("B {0}".format(index))
            self.tb1.addWidget(pb)

    def mainToolBarOrientationChanged(self, orientation):
        print "Orientation changed {0}".format(orientation)

    def initCentralWidget(self):
        self.intro = QTextEdit()
        self.setCentralWidget(self.intro)
        self.intro.setText("This application is still being designed")
Beispiel #2
0
class Notepad(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._text_edit = QTextEdit()
        self._open_button = QPushButton(self.tr("&Open"))
        self._save_button = QPushButton(self.tr("&Save"))
        self._exit_button = QPushButton(self.tr("&Exit"))

        button_layout = QVBoxLayout()
        button_layout.addWidget(self._open_button)
        button_layout.addWidget(self._save_button)
        button_layout.addWidget(self._exit_button)
        button_layout.addStretch()

        main_layout = QHBoxLayout()
        main_layout.addWidget(self._text_edit)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)
        
        self.setWindowTitle(self.tr('Notepad'))
        self._save_button.clicked.connect(self.save)
        self._open_button.clicked.connect(self.open)
        self._exit_button.clicked.connect(self.exit)

    def open(self):
        file_name = QFileDialog.getOpenFileName(self)[0]
        if file_name != '':
            try:
                with open(file_name, mode='rt') as in_file:
                    text = in_file.read()
                    self._text_edit.setText(text)
            except:
                QMessageBox.critical(self, self.tr('Error'),
                                           self.tr('Could not open file'))

    def save(self):
        file_name = QFileDialog.getSaveFileName(self)[0]
        if file_name != '':
            try:
                with open(file_name, mode='wt') as out_file:
                    text = self._text_edit.toPlainText()
                    out_file.write(text)
            except:
                QMessageBox.critical(self, self.tr('Error'),
                                           self.tr('Could not save file'))

    def exit(self):
        button = QMessageBox.question(
            self, self.tr('Notepad - Quit'),
            self.tr('Do you really want to quit?'),
            QMessageBox.Yes | QMessageBox.No)
        if button == QMessageBox.Yes:
            self.window().close()
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(731, 475)
        centralwidget = QWidget(self)
        gridLayout = QGridLayout(centralwidget)
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        menu_File = QMenu(menubar)
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
        action_About.triggered.connect(self.about)        
        iconToolBar = self.addToolBar("iconBar.png")
#------------------------------------------------------
# Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")        
        action_Close.setIcon(QIcon(":/quit.png"))
#------------------------------------------------------
# Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
#------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())
 
        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
             
    def showGPL(self):
        '''Read and display GPL licence.'''
        self.textEdit.setText(open('COPYING.txt').read())
       
    def about(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PyQt, Platform and the like")
Beispiel #4
0
class Notepad(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._text_edit = QTextEdit()
        self._open_button = QPushButton(self.tr("&Open"))
        self._save_button = QPushButton(self.tr("&Save"))
        self._exit_button = QPushButton(self.tr("&Exit"))

        button_layout = QVBoxLayout()
        button_layout.addWidget(self._open_button)
        button_layout.addWidget(self._save_button)
        button_layout.addWidget(self._exit_button)
        button_layout.addStretch()

        main_layout = QHBoxLayout()
        main_layout.addWidget(self._text_edit)
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)

        self.setWindowTitle(self.tr('Notepad'))
        self._save_button.clicked.connect(self.save)
        self._open_button.clicked.connect(self.open)
        self._exit_button.clicked.connect(self.exit)

    def open(self):
        file_name = QFileDialog.getOpenFileName(self)[0]
        if file_name != '':
            try:
                with open(file_name, mode='rt') as in_file:
                    text = in_file.read()
                    self._text_edit.setText(text)
            except:
                QMessageBox.critical(self, self.tr('Error'),
                                     self.tr('Could not open file'))

    def save(self):
        file_name = QFileDialog.getSaveFileName(self)[0]
        if file_name != '':
            try:
                with open(file_name, mode='wt') as out_file:
                    text = self._text_edit.toPlainText()
                    out_file.write(text)
            except:
                QMessageBox.critical(self, self.tr('Error'),
                                     self.tr('Could not save file'))

    def exit(self):
        button = QMessageBox.question(self, self.tr('Notepad - Quit'),
                                      self.tr('Do you really want to quit?'),
                                      QMessageBox.Yes | QMessageBox.No)
        if button == QMessageBox.Yes:
            self.window().close()
Beispiel #5
0
 def license_(self):
     lic = QTextEdit(self)
     lic.setWindowFlags(Qt.Window)
     lic.setWindowTitle("QReduce FreeBSD License")
     font = lic.font()
     font.setFamily('')
     font.setFixedPitch(True)
     font.setKerning(0)
     font.setWeight(QFont.Normal)
     font.setItalic(False)
     lic.setFont(font)
     lic.setText(
         'Copyright (c) 2009-2014 T. Sturm, 2010 C. Zengler'
         '<p>'
         'All rights reserved.'
         '<p>'
         'Redistribution and use in source and binary forms, with '
         'or without modification, are permitted provided that the '
         'following conditions are met:'
         '<ol>'
         '<li>Redistributions of source code must retain the relevant '
         'copyright notice, this list of conditions and the following '
         'disclaimer. '
         '<p>'
         '<li>Redistributions in binary form must reproduce the above '
         'copyright notice, this list of conditions and the following '
         'disclaimer in the documentation and/or other materials '
         'provided with the distribution. '
         '</ol>'
         '<p>'
         'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND '
         'CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, '
         'INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF '
         'MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE '
         'DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNERS OR '
         'CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, '
         'SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT '
         'NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; '
         'LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) '
         'HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN '
         'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR '
         'OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS '
         'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.'
         '</span>')
     lic.setReadOnly(True)
     w = 66 * lic.fontMetrics().width('m')
     h = 36 * lic.fontMetrics().height()
     lic.resize(w,h)
     lic.show()
     lic.raise_()
Beispiel #6
0
class DockBottom(BaseDock):
    def __init__(self):

        BaseDock.__init__(self, 100)

        self.ttt = QTextEdit()
        self.setWidget(self.ttt)

        tt = QStyleOptionDockWidget()
        tt.closable = False
        tt.title = "OMG"

        self.initStyleOption(tt)

        self.setFeatures(QDockWidget.DockWidgetClosable)
        # self.setStyleSheet(get_theme("dock"))

    def set_log(self, p_text):
        self.ttt.setText(p_text)
Beispiel #7
0
class Prozor(QWidget):
    def __init__(self,element):
        #kreiramo prozor
        QWidget.__init__(self)
        self.element = element
        #iskljucujemo polja za uvecanje i minimizaciju
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowMaximizeButtonHint & ~Qt.WindowMinimizeButtonHint)
        #Podesavamo naslov
        self.setWindowTitle(self.element.ime)
        self.focusWidget()
        #editor teksta
        self.textEditor = QTextEdit()
        self.textEditor.setText(self.element.data)
        #dodajemo dugmad za primenu i odbacivanje promena
        #i povezujemo ih sa odgovarajucim funkcijama
        self.dugmeOk = QPushButton("Potvrdi")
        self.dugmeOtkazi = QPushButton("Otkazi")
        self.connect(self.dugmeOk,SIGNAL('clicked()'),self,SLOT('podesi()'))
        self.connect(self.dugmeOtkazi,SIGNAL('clicked()'),self,SLOT('zatvori()'))
        #formiramo raspored
        raspored = QFormLayout()
        raspored.addRow(self.textEditor)
        raspored.addRow(self.dugmeOtkazi,self.dugmeOk)
        self.setLayout(raspored)
        
    def zatvori(self):
        '''
            Funkcija za dugme otkazi promene, vraca parametre liste na trenutno stanje aplikacije
        '''
        self.textEditor.clear()
        self.textEditor.setText(self.element.data)
        self.hide()
        
    def podesi(self):
        '''
            Funkcija za dugme potvrdi promene, poziva akcije za izmenu jezika i izgleda
        '''
        self.element.data = self.textEditor.toPlainText()
        self.hide()
        
    def closeEvent(self, event):
        self.zatvori()
Beispiel #8
0
class EditorWindow(QMainWindow):
    """initialize editor"""
    def __init__(self, cpacs_file, cpacs_schema):
        super(EditorWindow, self).__init__()

        self.editor = QTextEdit()      
        self.temp = CPACS_Handler()  
        self.temp.loadFile(cpacs_file, cpacs_schema)
        text = self.temp.tixi.exportDocumentAsString()
        
        xpath = self.temp.tixi.uIDGetXPath('NACA0009')
        print xpath
        #directory = self.temp.tixi.exportDocumentAsString()
        #version = self.temp.tixi.getTextElement('/cpacs/vehicles/aircraft/model/name')
        #attributeValue = self.temp.tixi.getTextAttribute(config.path_element2, config.attrName2)
        
        vecX = self.temp.tixi.getFloatVector(xpath + "/pointList/x",100)
        vecY = self.temp.tixi.getFloatVector(xpath + "/pointList/y",100)
        vecZ = self.temp.tixi.getFloatVector(xpath + "/pointList/z",100)
        print vecX
        print vecY
        print vecZ
        self.temp.tixi.close()
        
        #print version
        #print attributeValue
        self.editor.setText(text)
        
        self.statusBar()
        self.setWindowTitle('Simple XML editor')
        self.setCentralWidget(self.editor)
        self.resize(800, 800)

    def find(self, word) :
        self.editor.find(self.searchbox.text(), QTextDocument.FindBackward)      

    def search(self, xpath):
        print "test"
Beispiel #9
0
class MainWindow(QMainWindow):
    """Fenêtre principale du programme"""
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.setWindowIcon(QIcon('Stock/appicon.png'))

    def setupComponent(self):
        """Initialise l'ensemble des éléments de l'application"""
        self.setupStatusBar()
        self.setupZoneText()
        self.setupMenu()
        self.setupToolBar()

    def setupStatusBar(self):
        """Ajoute une barre de status"""
        self.progressBar = QProgressBar()
        self.statusLabel = QLabel('Progression ...')
        self.progressBar.setMaximum(100)
        self.progressBar.setMinimum(0)
        self.statusBar = QStatusBar()
        # # Affiche un message durant 2 sec après ouverture de l'application
        # self.statusBar.showMessage('Please Wait ...', 2000)
        self.progressBar.setValue(10)
        self.statusBar.addWidget(self.statusLabel, 1)
        self.statusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.statusBar)

    def setupZoneText(self):
        """Ajout du widget central (zone de texte)"""
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

    def setupMenu(self):
        """Ajout de menus contextuels"""
        self.createActions()
        self.createMenu()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    def setupToolBar(self):
        """Ajout de la barre d'outils"""
        self.mainToolBar = self.addToolBar('Main')
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

    def showProgress(self):
        """Avancement de la barre de progression"""
        while self.progressBar.value() < self.progressBar.maximum():
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1 / 10)
        # self.statusBar.showMessage('Ready', 2000)
        self.statusLabel.setText('Ready !!')

    def createMenu(self):
        """Création de la barre de menu avec 3 menus"""
        self.fileMenu = self.menuBar().addMenu('&Fichier')
        self.editMenu = self.menuBar().addMenu('&Edition')
        self.helpMenu = self.menuBar().addMenu('&About')

    def createActions(self):
        """Création des différentes actions du menu
           '&' permet de surligner une lettre pour acès rapide Alt+lettre
           'shortcut' permet de définir le raccourci de l'action du menu
           'statusTip' permet de modifier l'affichage dans la barre de status
           'triggered' permet de définir l'action à réaliser"""
        self.newAction = QAction('&New',
                                 self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Créer un nouveau fichier",
                                 triggered=self.newFile)
        self.exitAction = QAction('&Exit',
                                  self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Quitter l'application",
                                  triggered=self.exitFile)
        self.copyAction = QAction('&Copy',
                                  self,
                                  shortcut="Ctrl+C",
                                  statusTip="Copier",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction('&Paste',
                                   self,
                                   shortcut="Ctrl+V",
                                   statusTip="Coller",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction('&About',
                                   self,
                                   statusTip="Infos à propos de l'éditeur",
                                   triggered=self.aboutHelp)

    def newFile(self):
        """Efface le contenu du widget de text"""
        self.textEdit.setText('')

    def exitFile(self):
        """Ferme le programme"""
        self.close()

    def aboutHelp(self):
        """Affiche des renseignements sur le logiciel"""
        QMessageBox.about(self, "About this application",
                          "Just a simple text editor using Menu Bar")
Beispiel #10
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        #        self.setObjectName("MainWindow")
        self.resize(731, 475)
        centralwidget = QWidget(self)
        #        centralwidget.setObjectName("centralwidget")
        gridLayout = QGridLayout(centralwidget)
        #        gridLayout.setObjectName("gridLayout")
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
        #        self.textEdit.setObjectName("textEdit")
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        #        menubar.setObjectName("menubar")
        menu_File = QMenu(menubar)
        #        menu_File.setObjectName("menu_File")
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        #        statusbar.setObjectName("statusbar")
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
        #        actionShow_GPL.setObjectName("actionShow_GPL")
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
        #        action_About.setObjectName("action_About")
        action_About.triggered.connect(self.about)
        iconToolBar = self.addToolBar("iconBar.png")
        #------------------------------------------------------
        # Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")
        action_Close.setIcon(QIcon(":/quit.png"))
        #------------------------------------------------------
        # Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
        #------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())

        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)

    def showGPL(self):
        '''Read and display GPL licence.'''
        self.textEdit.setText(open('COPYING.txt').read())

    def about(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PyQt, Platform and the like",
                """<b> About this program </b> v %s
                <p>Copyright 2011 Your Name.
                All rights reserved in accordance with
                GPL v2 or later - NO WARRANTIES!
                <p>This application can be used for
                displaying OS and platform details.
                <p>Python %s - PySide version %s - Qt version %s on %s""" % \
                (__version__, platform.python_version(), PySide.__version__,\
                 PySide.QtCore.__version__, platform.system()))
Beispiel #11
0
class Airport_project_UI(QWidget):

    airports = [
        'KRK',
        'LA',
        'LIS'
    ]

    elitism_possibly_values = ['true', 'false']

    max_flights_list = ['1', '2', '3', '4', '5']

    def __init__(self):
        QWidget.__init__(self)
        self.params = {}

       # self.setMinimumSize(600, 250)
        #self.setWindowTitle("Medody Optymalizacji - Projekt")
       # self.setIcon()

        self.start_airport_label = QLabel("Start airport:", self)
        self.start_airport_label.move(5, 10)
        self.start_airport = QLineEdit(self)
        self.start_airport.setText('1')
        #self.start_airport.addItems(self.airports)
        self.start_airport.setMinimumHeight(20)
        self.start_airport.setMaximumHeight(20)
        self.start_airport.setMinimumWidth(60)
        self.start_airport.setMaximumWidth(60)
        self.start_airport.move(150, 5)

#TODO function to convert names of airport to indexes

        self.destination_airport_label = QLabel("Destination airport:", self)
        self.destination_airport_label.move(5, 40)
        self.destination_airport = QLineEdit(self)
        self.destination_airport.setText('2')
       # self.destination_airport.addItems(self.airports)
        self.destination_airport.setMinimumHeight(20)
        self.destination_airport.setMaximumHeight(20)
        self.destination_airport.setMaximumWidth(60)
        self.destination_airport.setMinimumWidth(60)
        self.destination_airport.move(150, 35)

        self.max_flights_label = QLabel("max number of flights:", self)
        self.max_flights_label.move(5, 70)
        self.max_flights = QLineEdit(self)
        self.max_flights.setText("3")
        #self.max_flights.addItems(self.max_flights_list)
        self.max_flights.setMaximumHeight(20)
        self.max_flights.setMinimumHeight(20)
        self.max_flights.setMaximumWidth(60)
        self.max_flights.setMinimumWidth(60)
        #self.max_flights.setMinimumWidth(60)
        self.max_flights.move(150, 65)

        self.cost_weight_label = QLabel("max cost weights:", self)
        self.cost_weight_label.move(5, 100)
        self.cost_weight = QLineEdit(self)
        self.cost_weight.setText("4")
        self.cost_weight.setMinimumWidth(60)
        self.cost_weight.setMaximumWidth(60)
        self.cost_weight.setMinimumHeight(20)
        self.cost_weight.setMaximumHeight(20)
        self.cost_weight.move(150, 95)


        self.time_weight_label = QLabel("time weight:", self)
        self.time_weight_label.move(5, 130)
        self.time_weight = QLineEdit(self)
        self.time_weight.setText("5")
        self.time_weight.setMinimumWidth(60)
        self.time_weight.setMaximumWidth(60)
        self.time_weight.setMinimumHeight(20)
        self.time_weight.setMaximumHeight(20)
        self.time_weight.move(150, 125)

        self.pop_size_label = QLabel("pop size:", self)
        self.pop_size_label.move(5, 160)  # +30

        self.pop_size = QLineEdit(self)
        self.pop_size.setText("6")
        self.pop_size.setMinimumWidth(60)
        self.pop_size.setMaximumWidth(60)
        self.pop_size.setMinimumHeight(20)
        self.pop_size.setMaximumHeight(20)
        self.pop_size.move(150, 155) # +30

        self.generation_label = QLabel("generations:", self)
        self.generation_label.move(5, 190)  # +30

        self.generation = QLineEdit(self)
        self.generation.setText("7")
        self.generation.setMinimumWidth(60)
        self.generation.setMaximumWidth(60)
        self.generation.setMinimumHeight(20)
        self.generation.setMaximumHeight(20)
        self.generation.move(150, 185) # +30

        self.mutation_rate_label = QLabel("mutation rate:", self)
        self.mutation_rate_label.move(5, 210)  # +30

        self.mutation_rate = QLineEdit(self)
        self.mutation_rate.setText("8")
        self.mutation_rate.setMinimumWidth(60)
        self.mutation_rate.setMaximumWidth(60)
        self.mutation_rate.setMinimumHeight(20)
        self.mutation_rate.setMaximumHeight(20)
        self.mutation_rate.move(150, 215) # +30


        self.tournament_size_label = QLabel("tournament size:", self)
        self.tournament_size_label.move(5, 240)  # +30

        self.tournament_size = QLineEdit(self)
        self.tournament_size.setText("9")
        self.tournament_size.setMinimumWidth(60)
        self.tournament_size.setMaximumWidth(60)
        self.tournament_size.setMinimumHeight(20)
        self.tournament_size.setMaximumHeight(20)
        self.tournament_size.move(150, 245) # +30

        self.elitism_label = QLabel("elitism:", self)
        self.elitism_label.move(5, 270)  # +30

        self.elitism = QComboBox(self)
        self.elitism.addItems(self.elitism_possibly_values)
        self.elitism.setMinimumWidth(60)
        self.elitism.setMaximumWidth(60)
        self.elitism.setMinimumHeight(20)
        self.elitism.setMaximumHeight(20)
        self.elitism.move(150, 275) # +30

        self.destination_min_label = QLabel("dest min:", self)
        self.destination_min_label.move(5, 300)  # +30

        self.dest_min = QLineEdit(self)
        self.dest_min.setText("4")
        self.dest_min.setMinimumWidth(60)
        self.dest_min.setMaximumWidth(60)
        self.dest_min.setMinimumHeight(20)
        self.dest_min.setMaximumHeight(20)
        self.dest_min.move(150, 305) # +30

        self.destination_max_label = QLabel("dest max:", self)
        self.destination_max_label.move(5, 330)  # +30

        self.dest_max = QLineEdit(self)
        self.dest_max.setText("10")
        self.dest_max.setMinimumWidth(60)
        self.dest_max.setMaximumWidth(60)
        self.dest_max.setMinimumHeight(20)
        self.dest_max.setMaximumHeight(20)
        self.dest_max.move(150, 335) # +30

        self.generate_graph_button = QPushButton("Generate graph!", self)
        self.generate_graph_button.setMinimumWidth(170)
        self.generate_graph_button.move(25, 365)

        self.start_evolution_button = QPushButton("Start evolution!", self)
        self.start_evolution_button.setMinimumWidth(170)
        self.start_evolution_button.move(25, 395)

        self.start_evolution_button.clicked.connect(self.start_evolution)
        self.generate_graph_button.clicked.connect(self.generate_graph)
        #self.get_list_of_possibly_airports() #TODO to have full list of airports in QComboBox

    def generate_graph(self):
        self.params = {
            'graph'           : None,
            'start_idx'       : int(self.start_airport.text()),
            'end_idx'         : int(self.destination_airport.text()),
            'max_flights'     : int(self.max_flights.text()),
            'cost_weight'     : int(self.cost_weight.text()),
            'time_weight'     : int(self.time_weight.text()),
            'pop_size'        : int(self.pop_size.text()),
            'generations'     : int(self.generation.text()),
            'mutation_rate'   : float(self.mutation_rate.text()),
            'tournament_size' : int(self.tournament_size.text()),
            'elitism'         : bool(self.elitism.currentText()),
            'dest_min'        : int(self.dest_min.text()),
            'dest_max'        : int(self.dest_max.text()),
            'max_flights'     : 4,
        }
        data = DataGenerator()
        DataGenerator.DESTINATIONS_MIN = self.params['dest_min']
        DataGenerator.DESTINATIONS_MAX = self.params['dest_max']

        # if input_graph_file is not None:
        #     data.load_saved_graph(input_graph_file)
        #
        # else:
        #TODO ilosc lotnisk
        data.load_new_data(10)
        data.create_graph()

        # if graph_save_file is not None:
        #     data.save_graph(graph_save_file)

        testsuite_airports = data.get_airports()
        testsuite_graph = data.get_graph()

        self.graph = GraphManager(self.params['max_flights'])
        self.graph.set_graph(testsuite_graph, testsuite_airports)

        airports_parser = Testsuite_airports_parser(testsuite_airports)


    def start_evolution(self):
        import pprint
        self.params = {
        'graph'           : self.graph,
        'start_idx'       : int(self.start_airport.text()),
        'end_idx'         : int(self.destination_airport.text()),
        'max_flights'     : int(self.max_flights.text()),
        'cost_weight'     : int(self.cost_weight.text()),
        'time_weight'     : int(self.time_weight.text()),
        'pop_size'        : int(self.pop_size.text()),
        'generations'     : int(self.generation.text()),
        'mutation_rate'   : float(self.mutation_rate.text()),
        'tournament_size' : int(self.tournament_size.text()),
        'elitism'         : bool(self.elitism.currentText()),
        'dest_min'        : int(self.dest_min.text()),
        'dest_max'        : int(self.dest_max.text()),
        }
        # pprint.pprint(params)
        self.output_of_algorithm = sys.__stdout__
        GA.run_with_params(self.params)
        self.newwindow()

    def newwindow(self):
        import pprint
        print("##############")
        pprint.pprint(self.output_of_algorithm)
        print("##############")
        self.wid = QWidget()
        self.wid.resize(250, 150)
        self.wid.setWindowTitle('NewWindow')
        self.result = QTextEdit(self.wid)
        self.result.setText(str(self.output_of_algorithm))
        #self.start_airport.addItems(self.airports)
        self.result.setMinimumHeight(200)
        self.result.setMaximumHeight(200)
        self.result.setMinimumWidth(600)
        self.start_airport.setMaximumWidth(600)
        # self.start_airport.move(150, 5)
        self.output_of_algorithm = None
        self.wid.show()
class SampleWindow(QMainWindow):
 """ Our main window class
 """
 def __init__(self,fileName=None):
    """ Constructor Function
    """
    # QWidget.__init__(self)
    # self.setWindowTitle("Icon Sample")
    # self.setGeometry(300, 300, 200, 150)
    QMainWindow.__init__(self)
    self.setWindowTitle("Icon Sample")
    self.setGeometry(300, 300, 200, 150)
    QToolTip.setFont(QFont("Decorative", 8, QFont.Bold))
    self.setToolTip('Our Main Window')
    self.icon='C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif'
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    self.fileName = None
    self.filters = "Text files (*.txt)"

    openFile = QAction(QIcon('open.png'), 'Open', self)
    openFile.setShortcut('Ctrl+O')
    openFile.setStatusTip('Open new File')
    openFile.triggered.connect(self.showDialog)
    menubar = self.menuBar()
    # fileMenu = menubar.addMenu('&File')
    # fileMenu.addAction(openFile)
    self.setGeometry(300, 300, 350, 300)
    self.setWindowTitle('Example - File Dialog')

    # self.myNameLE = QLineEdit(self)
    # self.myAgeLE = QLineEdit(self)
    # self.myChoiceLE = QLineEdit(self)

    self.statusLabel = QLabel('Showing Progress')
    self.progressBar = QProgressBar()
    self.progressBar.setMinimum(0)
    self.progressBar.setMaximum(100)
##################@@@@@@@@@@@@@@2
    self.threads = []

    self.addWorker(MyWorkerThread(1))
    self.addWorker(MyWorkerThread(2))
#######################@@@@@@@@@@@@@
    self.show()
##########################@@@@@@@@@@
 def addWorker(self, worker):
        worker.message.connect(self.printMessage, QtCore.Qt.QueuedConnection)
        # connect the finished signal to method so that we are notified
        worker.finished.connect(self.workersFinished)
        self.threads.append(worker)

 def startWorkers(self):
        for worker in self.threads:
            worker.start()
            # no wait, no finished. you start the threads and leave.

 def workersFinished(self):
        if all(worker.isFinished() for worker in self.threads):
            # wait until all the threads finished
            QtCore.QCoreApplication.instance().quit()

 @QtCore.Slot(str)
 def printMessage(self, text):
        sys.stdout.write(text+'\n')
        sys.stdout.flush()
################################

 def openAbout(self):
    aboutDialog = QtGui.QDialog(self)
    # aboutUi = about.About_Dialog()
    # aboutUi.setupUi(aboutDialog)
    aboutDialog.show()

 def newwindow(self):
        # w = W1()
        # w.show()
        # self.hide()
        # form = Form()
        # form.show()

        w2 = chooseoption.Form1(self)
        w2.show()
        import webbrowser
        your_swf_url='E:\soheil\web_site_root\ieee\all_functions\linux server\python GUI\Double_angle_off.swf'
        webbrowser.open(your_swf_url)
        # self.wid = QWidget()
        # self.wid.resize(250, 150)
        # self.wid.setWindowTitle('NewWindow')
        # self.wid.show()
        # self.actionAbout.triggered.connect(self.openAbout)
 def retranslateUi(self, Dialog):
    Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
    self.aboutLbl.setText(QtGui.QApplication.translate("Dialog", "Mailer version 0.0.1 by .....", None, QtGui.QApplication.UnicodeUTF8))

 def showNameDialog(self):
    text, ok = QInputDialog.getText(self, 'Input Text Dialog',
    'Enter your name:')
    if ok:
        self.myNameLE.setText(str(text))

 def showDialog(self):
    fileName, _ = QFileDialog.getOpenFileName(self, "Open Text Files", "c:/", "Text files(*.txt)")
    try:
        contents = open(fileName, 'r')
        with contents:
            data = contents.read()
            self.textEdit.setText(data)
    except:
        pass

 def CreateStatusBar(self):
    """ Function to create the status bar
    """
    self.myStatusBar = QStatusBar()
    self.progressBar.setValue(10)
    self.myStatusBar.addWidget(self.statusLabel, 1)
    self.myStatusBar.addWidget(self.progressBar, 2)
    self.setStatusBar(self.myStatusBar)
 def ShowProgress(self):
    """ Function to show progress
    """
    import time
    while(self.progressBar.value() < self.progressBar.maximum()):
        self.progressBar.setValue(self.progressBar.value() + 10)
        # time.sleep(1)
    self.statusLabel.setText('Ready')
 def SetupComponents(self):
    """ Function to setup status bar, central widget, menu bar
    """
    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    # self.CreateActions()
    # self.CreateMenus()
    # self.fileMenu.addAction(self.newAction)
    # self.fileMenu.addSeparator()
    # self.fileMenu.addAction(self.exitAction)
    # self.editMenu.addAction(self.copyAction)
    # self.fileMenu.addSeparator()
    # self.editMenu.addAction(self.pasteAction)
    # self.helpMenu.addAction(self.aboutAction)



    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.CreateActions()
    self.CreateMenus()
    self.CreateToolBar()
    self.fileMenu.addAction(self.newAction)
    self.fileMenu.addAction(self.openAction)
    self.fileMenu.addAction(self.saveAction)
    self.fileMenu.addSeparator()
    self.fileMenu.addAction(self.exitAction)
    self.editMenu.addAction(self.cutAction)
    self.editMenu.addAction(self.copyAction)
    self.editMenu.addAction(self.pasteAction)
    self.editMenu.addSeparator()
    self.editMenu.addAction(self.undoAction)
    self.editMenu.addAction(self.redoAction)
    self.editMenu.addAction(self.ss_image)

    self.editMenu.addSeparator()
    self.editMenu.addAction(self.selectAllAction)
    self.formatMenu.addAction(self.fontAction)
    self.helpMenu.addAction(self.aboutAction)
    self.helpMenu.addSeparator()
    self.helpMenu.addAction(self.aboutQtAction)
    self.mainToolBar.addAction(self.newAction)
    self.mainToolBar.addAction(self.openAction)
    self.mainToolBar.addAction(self.saveAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.cutAction)
    self.mainToolBar.addAction(self.copyAction)
    self.mainToolBar.addAction(self.pasteAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.undoAction)
    self.mainToolBar.addAction(self.redoAction)


 def openFile(self):
    self.fileName, self.filterName =QFileDialog.getOpenFileName(self)
    try:
        self.textEdit.setText(open(self.fileName).read())
    except:
        pass
    # Slots called when the menu actions are triggered
 def newFile(self):
    self.textEdit.setText('')
 def exitFile(self):
    self.close()
 def aboutHelp(self):
    QMessageBox.about(self, "About Simple Text Editor",
    "This example demonstrates the use "
    "of Menu Bar")

 def fontChange(self):
    (font, ok) = QFontDialog.getFont(QFont("Helvetica [Cronyx]", 10), self)
    if ok:
        self.textEdit.setCurrentFont(font)

 def saveFile(self):
    if self.fileName == None or self.fileName == '':
        self.fileName, self.filterName = QFileDialog.getSaveFileName(self, \
        filter=self.filters)
    if(self.fileName != ''):
        file = open(self.fileName, 'w')
        file.write(self.textEdit.toPlainText())
        self.statusBar().showMessage("File saved", 2000)
 def image_ss(self):
    from PySide import QtGui, QtCore

    import wxpython_flash_Simple_working
    hbox = QtGui.QHBoxLayout(self)
    pixmap = QtGui.QPixmap('C:\Users\Hamed\Pictures\LED\led.jpg')

    lbl = QtGui.QLabel(self)
    lbl.setPixmap(pixmap)

    hbox.addWidget(lbl)
    self.setLayout(hbox)

    self.setGeometry(300, 300, 280, 170)
    self.setWindowTitle('Red Rock')

    self.show()


    # from PIL import Image
    # from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication
    #
    # im = Image.open('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    # data = im.tostring('raw')
    #
    ##app = QApplication([])
    ## image = QImage(data);
    # image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    # pix = QPixmap.fromImage(image)
    # lbl = QLabel()
    # lbl.setPixmap(pix)
    # lbl.show()
 def image_ss_main(self):
    from PySide import QtGui, QtCore
    hbox = QtGui.QHBoxLayout(self)
    pixmap = QtGui.QPixmap('C:\Users\Hamed\Pictures\LED\led.jpg')

    lbl = QtGui.QLabel(self)
    lbl.setPixmap(pixmap)

    hbox.addWidget(lbl)
    self.setLayout(hbox)

    self.setGeometry(300, 300, 280, 170)
    self.setWindowTitle('Red Rock')

    self.show()


    # from PIL import Image
    # from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication
    #
    # im = Image.open('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    # data = im.tostring('raw')
    #
    ##app = QApplication([])
    ## image = QImage(data);
    # image = QImage(data, im.size[0], im.size[1], QImage.Format_ARGB32)
    # pix = QPixmap.fromImage(image)
    # lbl = QLabel()
    # lbl.setPixmap(pix)
    # lbl.show(
 def CreateActions(self):
    """ Function to create actions for menus
    """
    self.newAction = QAction( QIcon('new.png'), '&New',
    self, shortcut=QKeySequence.New,
    statusTip="Create a New File",
    triggered=self.newFile)
    self.exitAction = QAction( QIcon(self.icon), 'E&xit',
    self, shortcut="Ctrl+Q",
    statusTip="Exit the Application",
    triggered=self.exitFile)
    self.copyAction = QAction( QIcon('copy.png'), 'C&opy',
    self, shortcut="Ctrl+C",
    statusTip="Copy",
    triggered=self.textEdit.copy)
    self.pasteAction = QAction( QIcon('paste.png'), '&Paste',
    self, shortcut="Ctrl+V",
    statusTip="Paste",
    triggered=self.textEdit.paste)
    self.aboutAction = QAction( QIcon('about.png'), 'A&bout',
    self, statusTip="Displays info about text editor",
    triggered=self.aboutHelp)

    self.openAction = QAction( QIcon('open.png'), 'O&pen',
    self, shortcut=QKeySequence.Open,
    statusTip="Open an existing file",
    triggered=self.openFile)

    self.saveAction = QAction( QIcon('save.png'), '&Save',
    self, shortcut=QKeySequence.Save,
    statusTip="Save the current file to disk",
    triggered=self.saveFile)

    self.cutAction = QAction( QIcon('cut.png'), 'C&ut',
    self, shortcut=QKeySequence.Cut,
    statusTip="Cut the current selection to clipboard",
    triggered=self.textEdit.cut)

    self.undoAction = QAction( QIcon('undo.png'),'Undo', self,
    shortcut=QKeySequence.Undo,
    statusTip="Undo previous action",
    triggered=self.textEdit.undo)

    self.redoAction = QAction( QIcon('redo.png'),'Redo', self,
    shortcut=QKeySequence.Redo,
    statusTip="Redo previous action",
    triggered=self.textEdit.redo)

    self.selectAllAction = QAction( QIcon('selectAll.png'),
    'Select All',
    self, statusTip="Select All",
    triggered=self.textEdit.selectAll)

    self.fontAction = QAction( 'F&ont', self,
    statusTip = "Modify font properties",
    triggered = self.fontChange)

    self.aboutAction = QAction( QIcon('about.png'), 'A&bout',
    self, statusTip="Displays info about text editor",
    # triggered=self.aboutHelp)
    triggered=self.newwindow)

    self.aboutQtAction = QAction("About &Qt", self,
    statusTip="Show the Qt library's About box",
    triggered=qApp.aboutQt)

    self.ss_image = QAction("Insert &.SWF(flash)", self,
    statusTip="Show the Qt library's About box",
    triggered=self.image_ss)

    self.actionAbout = QAction("image &Qt", self,
    statusTip="Show the Qt library's About box",
    triggered=self.openAbout)


# Actual menu bar item creation
 def CreateToolBar(self):
    """ Function to create actual menu bar
    """
    self.mainToolBar = self.addToolBar('Main')
    self.mainToolBar.addAction(self.newAction)
    self.mainToolBar.addSeparator()
    self.mainToolBar.addAction(self.copyAction)
    self.mainToolBar.addAction(self.pasteAction)

# Actual menu bar item creation
 def CreateMenus(self):
    """ Function to create actual menu bar
    """
    self.fileMenu = self.menuBar().addMenu("&File")
    self.fileMenu.addSeparator()
    self.editMenu = self.menuBar().addMenu("&Edit")
    self.helpMenu = self.menuBar().addMenu("&Help")
    self.formatMenu = self.menuBar().addMenu("F&ormat")
 def setAboutButton(self):
    """ Function to set About Button
    """
    self.aboutButton = QPushButton("About", self)
    self.aboutButton.move(110, 100)
    self.aboutButton.clicked.connect(self.showAbout)
 def showAbout(self):
        """ Function to show About Box
        """
        QMessageBox.about(self.aboutButton, "About PySide",
        "PySide is a cross-platform tool for generating GUI Programs.")

 def center(self):
    """ Function to center the application
    """
    qRect = self.frameGeometry()
    centerPoint = QDesktopWidget().availableGeometry().center()
    qRect.moveCenter(centerPoint)
    self.move(qRect.topLeft())
 def quitApp(self):
    """ Function to confirm a message from the user
    """
    userInfo = QMessageBox.question(self, 'Confirmation',
    "This will quit the application. Do you want to Continue?",
    QMessageBox.Yes | QMessageBox.No)
    if userInfo == QMessageBox.Yes:
        myApp.quit()
    if userInfo == QMessageBox.No:
       pass
 def setIconModes(self):
    myIcon1 = QIcon( self.icon)
    myLabel1 = QLabel('sample', self)
    pixmap1 = myIcon1.pixmap(50, 50, QIcon.Active, QIcon.On)
    myLabel1.setPixmap(pixmap1)
    myIcon2 = QIcon( self.icon)
    myLabel2 = QLabel('sample', self)
    pixmap2 = myIcon2.pixmap(50, 50, QIcon.Disabled, QIcon.Off)
    myLabel2.setPixmap(pixmap2)
    myLabel2.move(50, 0)
    myIcon3 = QIcon( self.icon)
    myLabel3 = QLabel('sample', self)
    pixmap3 = myIcon3.pixmap(50, 50, QIcon.Selected, QIcon.On)
    myLabel3.setPixmap(pixmap3)
    myLabel3.move(100, 0)
 def setIcon(self):
    """ Function to set Icon
    """
    from  PySide.QtGui import QPixmap
    pixmap = QPixmap(r'C:\Users\Hamed\Pictures\LED\led.jpg')
    # appIcon = QIcon('C:\Users\Hamed\Documents\soheil sites image\imageedit__9411602959.gif')
    appIcon = QIcon(pixmap)
    self.setWindowIcon(appIcon)

 def setButton(self):
    """ Function to add a quit button
    """
    myButton = QPushButton('Quit', self)
    myButton.move(20, 100)
    # myButton.clicked.connect(myApp.quit)
    myButton.clicked.connect(self.quitApp)
Beispiel #13
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(730, 475)
        self.setWindowTitle('Combine Code Blocks.')
        centralwidget = QWidget(self)
        gridLayout = QGridLayout(centralwidget)
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        menu_File = QMenu(menubar)
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        self.setStatusBar(statusbar)
        actionShow_CCPL = QAction(self)
        actionShow_CCPL.triggered.connect(self.showCCPL)
        action_About = QAction(self)
        action_About.triggered.connect(self.about)
        iconToolBar = self.addToolBar("iconBar.png")
        #------------------------------------------------------
        # Add icons to appear in tool bar - step 1
        actionShow_CCPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")
        action_Close.setIcon(QIcon(":/quit.png"))
        #------------------------------------------------------
        # Show a tip on the Status Bar - step 2
        actionShow_CCPL.setStatusTip("Show CC Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
        #------------------------------------------------------
        menu_File.addAction(actionShow_CCPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())

        iconToolBar.addAction(actionShow_CCPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)

    def showCCPL(self):
        'Read and display CCPL licence.'
        with open('CCPL.txt') as fi:
            self.textEdit.setText(fi.read())

    def about(self):
        '''Popup a box with about message.'''
        QMessageBox.about(
            self, "About PySide, Platform and version.",
            """<b> about.py version %s </b> 
                <p>Copyright &copy; 2013 by Algis Kabaila. 
                This work is made available under  the terms of
                Creative Commons Attribution-ShareAlike 3.0 license,
                http://creativecommons.org/licenses/by-sa/3.0/.
                <p>This application is useful for displaying  
                Qt version and other details.
                <p>Python %s -  PySide version %s - Qt version %s on %s""" %
            (__version__, platform.python_version(), PySide.__version__,
             PySide.QtCore.__version__, platform.system()))
Beispiel #14
0
class MainWindow(QMainWindow):
    """ Create the Application Main Window CLass
    """
    def __init__(self):
        """ Constructor FUnction
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("Application Title Here")
        self.setGeometry(300, 250, 400, 300)

    def SetupComponents(self):
        """ Setting the Central Widget
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.CreateActions()
        self.CreateMenus()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)
        self.helpMenu.addSeparator()
        self.helpMenu.addAction(self.aboutCopyrightAction)
        self.CreateToolBar()
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

    # Slots called when the action menus are triggered
    def newFile(self):
       self.textEdit.setText('')

    def exitFile(self):
        self.close()

    def aboutHelp(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use "
                          "of Menu Bar")
    def aboutCopyright(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use "
                          "of Copyright Bar")

    def CreateActions(self):
        """ Function to create actions for menus
        """
        self.newAction = QAction(QIcon('new.png'), '&New',
                                  self, shortcut=QKeySequence.New,
                                  statusTip="Create a New File",
                                  triggered=self.newFile)
        self.exitAction = QAction(QIcon('exit.png'), 'E&xit',
                                  self, shortcut="Ctrl+Q",
                                  statusTip="Exit the Application",
                                  triggered=self.exitFile)
        self.copyAction = QAction(QIcon('copy.png'), 'C&opy',
                                  self, shortcut="Ctrl+C",
                                  statusTip="Copy",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction(QIcon('paste.png'), '&Paste',
                                   self, shortcut="Ctrl+V",
                                   statusTip="Paste",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction(QIcon('about.png'), 'A&bout',
                                   self, statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)
        self.aboutCopyrightAction = QAction(QIcon('about.png'), '&Copyright',
                                   self, statusTip="Displays info about Copyright",
                                   triggered=self.aboutCopyright)

    def CreateMenus(self):
        """ Function to create actual menu bar
        """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.viewMenu = self.menuBar().addMenu("&View")
        self.helpMenu = self.menuBar().addMenu("&Help")

    def CreateToolBar(self):
        """ Function to create tool bar
        """
        self.mainToolBar = self.addToolBar('Main')
Beispiel #15
0
class Airport_project_UI(QWidget):

    airports = ['KRK', 'LA', 'LIS']

    elitism_possibly_values = ['true', 'false']

    max_flights_list = ['1', '2', '3', '4', '5']

    def __init__(self):
        QWidget.__init__(self)
        self.params = {}

        # self.setMinimumSize(600, 250)
        #self.setWindowTitle("Medody Optymalizacji - Projekt")
        # self.setIcon()

        self.start_airport_label = QLabel("Start airport:", self)
        self.start_airport_label.move(5, 10)
        self.start_airport = QLineEdit(self)
        self.start_airport.setText('1')
        #self.start_airport.addItems(self.airports)
        self.start_airport.setMinimumHeight(20)
        self.start_airport.setMaximumHeight(20)
        self.start_airport.setMinimumWidth(60)
        self.start_airport.setMaximumWidth(60)
        self.start_airport.move(150, 5)

        #TODO function to convert names of airport to indexes

        self.destination_airport_label = QLabel("Destination airport:", self)
        self.destination_airport_label.move(5, 40)
        self.destination_airport = QLineEdit(self)
        self.destination_airport.setText('2')
        # self.destination_airport.addItems(self.airports)
        self.destination_airport.setMinimumHeight(20)
        self.destination_airport.setMaximumHeight(20)
        self.destination_airport.setMaximumWidth(60)
        self.destination_airport.setMinimumWidth(60)
        self.destination_airport.move(150, 35)

        self.max_flights_label = QLabel("max number of flights:", self)
        self.max_flights_label.move(5, 70)
        self.max_flights = QLineEdit(self)
        self.max_flights.setText("3")
        #self.max_flights.addItems(self.max_flights_list)
        self.max_flights.setMaximumHeight(20)
        self.max_flights.setMinimumHeight(20)
        self.max_flights.setMaximumWidth(60)
        self.max_flights.setMinimumWidth(60)
        #self.max_flights.setMinimumWidth(60)
        self.max_flights.move(150, 65)

        self.cost_weight_label = QLabel("max cost weights:", self)
        self.cost_weight_label.move(5, 100)
        self.cost_weight = QLineEdit(self)
        self.cost_weight.setText("4")
        self.cost_weight.setMinimumWidth(60)
        self.cost_weight.setMaximumWidth(60)
        self.cost_weight.setMinimumHeight(20)
        self.cost_weight.setMaximumHeight(20)
        self.cost_weight.move(150, 95)

        self.time_weight_label = QLabel("time weight:", self)
        self.time_weight_label.move(5, 130)
        self.time_weight = QLineEdit(self)
        self.time_weight.setText("5")
        self.time_weight.setMinimumWidth(60)
        self.time_weight.setMaximumWidth(60)
        self.time_weight.setMinimumHeight(20)
        self.time_weight.setMaximumHeight(20)
        self.time_weight.move(150, 125)

        self.pop_size_label = QLabel("pop size:", self)
        self.pop_size_label.move(5, 160)  # +30

        self.pop_size = QLineEdit(self)
        self.pop_size.setText("6")
        self.pop_size.setMinimumWidth(60)
        self.pop_size.setMaximumWidth(60)
        self.pop_size.setMinimumHeight(20)
        self.pop_size.setMaximumHeight(20)
        self.pop_size.move(150, 155)  # +30

        self.generation_label = QLabel("generations:", self)
        self.generation_label.move(5, 190)  # +30

        self.generation = QLineEdit(self)
        self.generation.setText("7")
        self.generation.setMinimumWidth(60)
        self.generation.setMaximumWidth(60)
        self.generation.setMinimumHeight(20)
        self.generation.setMaximumHeight(20)
        self.generation.move(150, 185)  # +30

        self.mutation_rate_label = QLabel("mutation rate:", self)
        self.mutation_rate_label.move(5, 210)  # +30

        self.mutation_rate = QLineEdit(self)
        self.mutation_rate.setText("8")
        self.mutation_rate.setMinimumWidth(60)
        self.mutation_rate.setMaximumWidth(60)
        self.mutation_rate.setMinimumHeight(20)
        self.mutation_rate.setMaximumHeight(20)
        self.mutation_rate.move(150, 215)  # +30

        self.tournament_size_label = QLabel("tournament size:", self)
        self.tournament_size_label.move(5, 240)  # +30

        self.tournament_size = QLineEdit(self)
        self.tournament_size.setText("9")
        self.tournament_size.setMinimumWidth(60)
        self.tournament_size.setMaximumWidth(60)
        self.tournament_size.setMinimumHeight(20)
        self.tournament_size.setMaximumHeight(20)
        self.tournament_size.move(150, 245)  # +30

        self.elitism_label = QLabel("elitism:", self)
        self.elitism_label.move(5, 270)  # +30

        self.elitism = QComboBox(self)
        self.elitism.addItems(self.elitism_possibly_values)
        self.elitism.setMinimumWidth(60)
        self.elitism.setMaximumWidth(60)
        self.elitism.setMinimumHeight(20)
        self.elitism.setMaximumHeight(20)
        self.elitism.move(150, 275)  # +30

        self.destination_min_label = QLabel("dest min:", self)
        self.destination_min_label.move(5, 300)  # +30

        self.dest_min = QLineEdit(self)
        self.dest_min.setText("4")
        self.dest_min.setMinimumWidth(60)
        self.dest_min.setMaximumWidth(60)
        self.dest_min.setMinimumHeight(20)
        self.dest_min.setMaximumHeight(20)
        self.dest_min.move(150, 305)  # +30

        self.destination_max_label = QLabel("dest max:", self)
        self.destination_max_label.move(5, 330)  # +30

        self.dest_max = QLineEdit(self)
        self.dest_max.setText("10")
        self.dest_max.setMinimumWidth(60)
        self.dest_max.setMaximumWidth(60)
        self.dest_max.setMinimumHeight(20)
        self.dest_max.setMaximumHeight(20)
        self.dest_max.move(150, 335)  # +30

        self.generate_graph_button = QPushButton("Generate graph!", self)
        self.generate_graph_button.setMinimumWidth(170)
        self.generate_graph_button.move(25, 365)

        self.start_evolution_button = QPushButton("Start evolution!", self)
        self.start_evolution_button.setMinimumWidth(170)
        self.start_evolution_button.move(25, 395)

        self.start_evolution_button.clicked.connect(self.start_evolution)
        self.generate_graph_button.clicked.connect(self.generate_graph)
        #self.get_list_of_possibly_airports() #TODO to have full list of airports in QComboBox

    def generate_graph(self):
        self.params = {
            'graph': None,
            'start_idx': int(self.start_airport.text()),
            'end_idx': int(self.destination_airport.text()),
            'max_flights': int(self.max_flights.text()),
            'cost_weight': int(self.cost_weight.text()),
            'time_weight': int(self.time_weight.text()),
            'pop_size': int(self.pop_size.text()),
            'generations': int(self.generation.text()),
            'mutation_rate': float(self.mutation_rate.text()),
            'tournament_size': int(self.tournament_size.text()),
            'elitism': bool(self.elitism.currentText()),
            'dest_min': int(self.dest_min.text()),
            'dest_max': int(self.dest_max.text()),
            'max_flights': 4,
        }
        data = DataGenerator()
        DataGenerator.DESTINATIONS_MIN = self.params['dest_min']
        DataGenerator.DESTINATIONS_MAX = self.params['dest_max']

        # if input_graph_file is not None:
        #     data.load_saved_graph(input_graph_file)
        #
        # else:
        #TODO ilosc lotnisk
        data.load_new_data(10)
        data.create_graph()

        # if graph_save_file is not None:
        #     data.save_graph(graph_save_file)

        testsuite_airports = data.get_airports()
        testsuite_graph = data.get_graph()

        self.graph = GraphManager(self.params['max_flights'])
        self.graph.set_graph(testsuite_graph, testsuite_airports)

        airports_parser = Testsuite_airports_parser(testsuite_airports)

    def start_evolution(self):
        import pprint
        self.params = {
            'graph': self.graph,
            'start_idx': int(self.start_airport.text()),
            'end_idx': int(self.destination_airport.text()),
            'max_flights': int(self.max_flights.text()),
            'cost_weight': int(self.cost_weight.text()),
            'time_weight': int(self.time_weight.text()),
            'pop_size': int(self.pop_size.text()),
            'generations': int(self.generation.text()),
            'mutation_rate': float(self.mutation_rate.text()),
            'tournament_size': int(self.tournament_size.text()),
            'elitism': bool(self.elitism.currentText()),
            'dest_min': int(self.dest_min.text()),
            'dest_max': int(self.dest_max.text()),
        }
        # pprint.pprint(params)
        self.output_of_algorithm = sys.__stdout__
        GA.run_with_params(self.params)
        self.newwindow()

    def newwindow(self):
        import pprint
        print("##############")
        pprint.pprint(self.output_of_algorithm)
        print("##############")
        self.wid = QWidget()
        self.wid.resize(250, 150)
        self.wid.setWindowTitle('NewWindow')
        self.result = QTextEdit(self.wid)
        self.result.setText(str(self.output_of_algorithm))
        #self.start_airport.addItems(self.airports)
        self.result.setMinimumHeight(200)
        self.result.setMaximumHeight(200)
        self.result.setMinimumWidth(600)
        self.start_airport.setMaximumWidth(600)
        # self.start_airport.move(150, 5)
        self.output_of_algorithm = None
        self.wid.show()
Beispiel #16
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
#        self.setObjectName("MainWindow")
        self.resize(731, 475)
        centralwidget = QWidget(self)
#        centralwidget.setObjectName("centralwidget")
        gridLayout = QGridLayout(centralwidget)
#        gridLayout.setObjectName("gridLayout")
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
#        self.textEdit.setObjectName("textEdit")
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
#        menubar.setObjectName("menubar")
        menu_File = QMenu(menubar)
#        menu_File.setObjectName("menu_File")
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
#        statusbar.setObjectName("statusbar")
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
#        actionShow_GPL.setObjectName("actionShow_GPL")
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
#        action_About.setObjectName("action_About")
        action_About.triggered.connect(self.about)       
        iconToolBar = self.addToolBar("iconBar.png")
#------------------------------------------------------
# Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")       
        action_Close.setIcon(QIcon(":/quit.png"))
#------------------------------------------------------
# Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show GPL Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
#------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())
 
        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
               
    def showGPL(self):
        '''Read and display GPL licence.'''
        self.textEdit.setText(open('COPYING.txt').read())
         
    def about(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PyQt, Platform and the like",
                """<b> About this program </b> v %s
                <p>Copyright 2011 Your Name.
                All rights reserved in accordance with
                GPL v2 or later - NO WARRANTIES!
                <p>This application can be used for
                displaying OS and platform details.
                <p>Python %s - PySide version %s - Qt version %s on %s""" % \
                (__version__, platform.python_version(), PySide.__version__,\
                 PySide.QtCore.__version__, platform.system()))      
Beispiel #17
0
class PrintPreorderDialog(QDialog):
    def __init__(self, parent):
        super(PrintPreorderDialog, self).__init__(parent)

        title = _("Print preorder")
        self.setWindowTitle(title)

        top_layout = QVBoxLayout()

        self.title_widget = TitleWidget(title, self)
        top_layout.addWidget(self.title_widget)

        info = QLabel(
            _("Here you can give a small message that will be printed togetehr with the preorder."
              ), self)
        info.setWordWrap(True)
        top_layout.addWidget(info)

        top_layout.addWidget(QLabel(_("Header text")))

        self.message_text_area = QTextEdit()
        top_layout.addWidget(self.message_text_area)

        top_layout.addWidget(QLabel(_("Footer text")))

        self.message_text_area_footer = QTextEdit()
        top_layout.addWidget(self.message_text_area_footer)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton(QDialogButtonBox.StandardButton.Cancel)
        self.buttons.addButton(QDialogButtonBox.Ok)

        top_layout.addWidget(self.buttons)

        self.setLayout(top_layout)
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

    def set_preorder(self, preorder_id):
        preorder = dao.order_dao.find_by_id_frozen(preorder_id)

        if preorder.preorder_print_note:
            self.message_text_area.setText(preorder.preorder_print_note)
        else:
            self.message_text_area.setText(
                _("Sir,\nPlease find your preorder below as discussed earlier. Please send us a signed copy to complete the order.\nBest regards"
                  ))

        if preorder.preorder_print_note_footer:
            self.message_text_area_footer.setText(
                preorder.preorder_print_note_footer)
        else:
            self.message_text_area_footer.setText(
                _("Best regards,\n\nthe company team."))

    def get_print_notes(self):
        return self.message_text_area.toPlainText().strip(
        ), self.message_text_area_footer.toPlainText().strip()

    @Slot()
    def accept(self):
        super(PrintPreorderDialog, self).accept()

    @Slot()
    def reject(self):
        super(PrintPreorderDialog, self).reject()
class MainWindow(QMainWindow):
    """Fenêtre principale du programme"""
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Window")
        self.setGeometry(300, 250, 400, 300)
        self.setWindowIcon(QIcon('Stock/appicon.png'))

    def setupComponent(self):
        """Initialise l'ensemble des éléments de l'application"""
        self.setupStatusBar()
        self.setupZoneText()
        self.setupMenu()
        self.setupToolBar()

    def setupStatusBar(self):
        """Ajoute une barre de status"""
        self.progressBar = QProgressBar()
        self.statusLabel = QLabel('Progression ...')
        self.progressBar.setMaximum(100)
        self.progressBar.setMinimum(0)
        self.statusBar = QStatusBar()
        # # Affiche un message durant 2 sec après ouverture de l'application
        # self.statusBar.showMessage('Please Wait ...', 2000)
        self.progressBar.setValue(10)
        self.statusBar.addWidget(self.statusLabel, 1)
        self.statusBar.addWidget(self.progressBar, 2)
        self.setStatusBar(self.statusBar)

    def setupZoneText(self):
        """Ajout du widget central (zone de texte)"""
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

    def setupMenu(self):
        """Ajout de menus contextuels"""
        self.createActions()
        self.createMenu()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    def setupToolBar(self):
        """Ajout de la barre d'outils"""
        self.mainToolBar = self.addToolBar('Main')
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

    def showProgress(self):
        """Avancement de la barre de progression"""
        while self.progressBar.value() < self.progressBar.maximum():
            self.progressBar.setValue(self.progressBar.value() + 10)
            time.sleep(1/10)
        # self.statusBar.showMessage('Ready', 2000)
        self.statusLabel.setText('Ready !!')

    def createMenu(self):
        """Création de la barre de menu avec 3 menus"""
        self.fileMenu = self.menuBar().addMenu('&Fichier')
        self.editMenu = self.menuBar().addMenu('&Edition')
        self.helpMenu = self.menuBar().addMenu('&About')

    def createActions(self):
        """Création des différentes actions du menu
           '&' permet de surligner une lettre pour acès rapide Alt+lettre
           'shortcut' permet de définir le raccourci de l'action du menu
           'statusTip' permet de modifier l'affichage dans la barre de status
           'triggered' permet de définir l'action à réaliser"""
        self.newAction = QAction('&New', self, shortcut=QKeySequence.New,
                                 statusTip="Créer un nouveau fichier",
                                 triggered=self.newFile)
        self.exitAction = QAction('&Exit', self, shortcut="Ctrl+Q",
                                  statusTip="Quitter l'application",
                                  triggered=self.exitFile)
        self.copyAction = QAction('&Copy', self, shortcut="Ctrl+C",
                                  statusTip="Copier",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction('&Paste', self, shortcut="Ctrl+V",
                                   statusTip="Coller",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction('&About', self,
                                   statusTip="Infos à propos de l'éditeur",
                                   triggered=self.aboutHelp)

    def newFile(self):
        """Efface le contenu du widget de text"""
        self.textEdit.setText('')

    def exitFile(self):
        """Ferme le programme"""
        self.close()

    def aboutHelp(self):
        """Affiche des renseignements sur le logiciel"""
        QMessageBox.about(self, "About this application",
                          "Just a simple text editor using Menu Bar")
Beispiel #19
0
class MainWindow(QMainWindow):
    """ Our Main Window class
    """
    def __init__(self):
        """ Constructor Function
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("A Simple Text Editor")
        self.setWindowIcon(QIcon('appicon.png'))
        self.setGeometry(300, 250, 400, 300)

    def SetupComponents(self):
        """ Function to setup status bar, central widget, menu bar
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.CreateActions()
        self.CreateMenus()
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.fileMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    # slots called when the menu actions are triggered
    def newFile(self):
        self.textEdit.setText('')

    def exitFile(self):
        self.close()

    def aboutHelp(self):
        QMessageBox.about(
            self, "about a simple Text Editor",
            "This example demostrates the sue "
            " of the menu bar")

    def CreateActions(self):
        """ Function to create actions for menus
        """
        self.newAction = QAction(QIcon('new.png'),
                                 '&New',
                                 self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Create a New File",
                                 triggered=self.newFile)
        self.copyAction = QAction(QIcon('copy.png'),
                                  'C&opy',
                                  self,
                                  shortcut="Ctrl+C",
                                  statusTip="Copy",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction(QIcon('paste.png'),
                                   '&Paste',
                                   self,
                                   shortcut="Ctrl+V",
                                   statusTip="Paste",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction(QIcon('about.png'),
                                   'A&bout',
                                   self,
                                   statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)

        self.exitAction = QAction(QIcon('exit.png'),
                                  'E&xit',
                                  self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Exit the Application",
                                  triggered=self.exitFile)

    # Actual menu bar item creation
    def CreateMenus(self):
        """ Function to create actual menu bar
        """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.helpMenu = self.menuBar().addMenu("&Help")
Beispiel #20
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initGUI()

    def initGUI(self):
        self.setWindowTitle("A Simple Text Editor")
        self.setWindowIcon(QIcon('appicon.png'))
        self.setGeometry(100, 100, 800, 600)
        self.center()

        # Text Editor
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.fileName = None

        self.filters = "Text files (*.txt)"
        # Setup and Show
        self.setupComponents()
        self.show()

    def center(self):
        """ Function to center the application """
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())

    #=================================================================#
    # Create Central Widget Component to use QTextEdit
    #=================================================================#
    def setupComponents(self):
        """ Setting the central widget """

        # Progress Bar
        #self.progressBar = QProgressBar()
        #self.progressBar.setMinimum(0)
        #self.progressBar.setMaximum(100)

        # Status Label
        #self.statusLabel = QLabel('Status', self)

        # Status Bar
        self.myStatusBar = QStatusBar()
        #self.myStatusBar.addWidget(self.statusLabel, 1)
        #self.myStatusBar.addWidget(self.progressBar, 5)
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 1000)

        self.createActions()
        self.createMenus()
        self.createToolBar()

        # File Menu
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        # Edit Menu
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.undoAction)
        self.editMenu.addAction(self.redoAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.selectAllAction)

        # Format Menu
        self.formatMenu.addAction(self.fontAction)

        # Help Menu
        self.helpMenu.addAction(self.aboutAction)
        self.helpMenu.addSeparator()
        self.helpMenu.addAction(self.aboutQtAction)

        # Tool Bar
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addAction(self.openAction)
        self.mainToolBar.addAction(self.saveAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.cutAction)
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.undoAction)
        self.mainToolBar.addAction(self.redoAction)

    # NOT-NEEDED : For progress bar
    def showProgress(self, progress):
        """ Function to show progress """
        self.progressBar.setValue(progress)
        if progress == 100:
            self.statusLabel.setText('Ready')
            return

    #=================================================================#
    # Helper Functions
    #=================================================================#
    def msgApp(self, title, message):
        """ Fuction to show dialog box with message """
        userInfo = QMessageBox.question(self, title, message,
                                        QMessageBox.Yes | QMessageBox.No)
        if userInfo == QMessageBox.Yes:
            return "Y"
        if userInfo == QMessageBox.No:
            return "N"
        self.close()

    #=================================================================#
    # Slots: called when the menu actions are triggered
    #=================================================================#
    def newFile(self):
        response = self.msgApp("Confirmation",
                               "Do you want to save the current file?")

        if response == "Y":
            self.saveFile()

        self.textEdit.setText('')
        self.fileName = None

    def openFile(self):
        response = self.msgApp("Confirmation",
                               "Save the current file before open a new one?")

        if response == "Y":
            self.saveFile()

        (self.fileName, self.filterName) = QFileDialog.getOpenFileName(self)
        self.textEdit.setText(open(self.fileName).read())

    def saveFile(self):
        if self.fileName == None or self.fileName == '':
            (self.fileName, self.filterName) = \
                           QFileDialog.getSaveFileName(self, filter=self.filters)

        if (self.fileName != ''):
            file = open(self.fileName, 'w')
            file.write(self.textEdit.toPlainText())
            self.statusBar().showMessage("File saved", 2000)

    def exitFile(self):
        response = self.msgApp("Confirmation",
                               "This will quit the application, continue?")
        if response == "Y":
            myApp.quit()
        else:
            pass

    def fontChange(self):
        (font, ok) = QFontDialog.getFont(QFont("Helvetica [Cronyx]", 10), self)
        if ok:
            self.textEdit.setCurrentFont(font)

    def aboutHelp(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use of " + \
                          "a Menu Bar")

    def aboutQt(self):
        QMessageBox.aboutQt(self, title="Qt Version")

    #=================================================================#
    # Actions: send signals to slots
    #=================================================================#
    def createActions(self):
        """ Function to create actions for menus """
        # Parameters are as follows
        # 1. Icon to be displayed on the left
        # 2. The name, '&' means the the letter following
        #    will the be underlined (press 'Alt' to see)
        # 3. Implies the parent, which is the main window
        # 4. Shortcut key
        # 5. status tip in bottom status bar
        # 6. slot to be called
        self.newAction = QAction(QIcon('new.png'),
                                 '&New File',
                                 self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Create a New File",
                                 triggered=self.newFile)

        self.openAction = QAction(QIcon('open.png'),
                                  '&Open File',
                                  self,
                                  shortcut=QKeySequence.Open,
                                  statusTip="Open an existing file",
                                  triggered=self.openFile)

        self.saveAction = QAction(QIcon('save.png'),
                                  '&Save File',
                                  self,
                                  shortcut=QKeySequence.Save,
                                  statusTip="Save the current file",
                                  triggered=self.saveFile)

        self.cutAction = QAction(
            QIcon('cut.png'),
            '&Cut',
            self,
            shortcut=QKeySequence.Cut,
            statusTip="Cut the current selection to clipboard",
            triggered=self.textEdit.cut)

        self.copyAction = QAction(QIcon('copy.png'),
                                  '&Copy',
                                  self,
                                  shortcut="Ctrl+C",
                                  statusTip="Copy",
                                  triggered=self.textEdit.copy)

        self.pasteAction = QAction(QIcon('paste.png'),
                                   '&Paste',
                                   self,
                                   shortcut="Ctrl+V",
                                   statusTip="Paste",
                                   triggered=self.textEdit.paste)

        self.selectAllAction = QAction(QIcon('selectAll.png'),
                                       '&Select All',
                                       self,
                                       statusTip="Select All",
                                       triggered=self.textEdit.selectAll)

        self.redoAction = QAction(QIcon('redo.png'),
                                  '&Redo',
                                  self,
                                  shortcut=QKeySequence.Redo,
                                  statusTip="Redo previous action",
                                  triggered=self.textEdit.redo)

        self.undoAction = QAction(QIcon('undo.png'),
                                  '&Undo',
                                  self,
                                  shortcut=QKeySequence.Undo,
                                  statusTip="Undo previous action",
                                  triggered=self.textEdit.undo)

        self.fontAction = QAction('F&ont',
                                  self,
                                  statusTip="Modify font properties",
                                  triggered=self.fontChange)

        self.aboutAction = QAction(QIcon('about.png'),
                                   '&About',
                                   self,
                                   statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)

        self.aboutQtAction = QAction(
            'About &Qt',
            self,
            statusTip="Show the Qt library's About box",
            triggered=self.aboutQt)

        self.exitAction = QAction(QIcon('exit.png'),
                                  '&Exit',
                                  self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Exit the program",
                                  triggered=self.exitFile)

    #=================================================================#
    # Actual menu bar item creation
    #=================================================================#
    def createMenus(self):
        """ Function to create actual menu bar """
        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.formatMenu = self.menuBar().addMenu("&Format")
        self.helpMenu = self.menuBar().addMenu("&Help")

    #=================================================================#
    # Tool Bar
    #=================================================================#
    def createToolBar(self):
        """ Function to create tool bar """
        self.mainToolBar = self.addToolBar('Main Tool Bar')
Beispiel #21
0
class Ui_MainWindow(QMainWindow):
    """Cette classe contient tous les widgets de notre application."""
    
    defaultPalette = QPalette()
    defaultPalette.setColor(QPalette.Base, QColor("#151515"))
    defaultPalette.setColor(QPalette.Text, Qt.white)

    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        # initialise la GUI avec un exemple
        self.text = "Ceci est un petit texte d'exemple."
        # les variables sont en place, initialise la GUI
        self.initUI()
        # exécute l'exemple
        self.orgText.setText(self.text)
        self.encode_text(False)
        self.logLab.setText(
            u"Saisir du texte ou importer un fichier, puis pousser \n"
            u"le bouton correspondant à l'opération souhaitée.")

    def initUI(self):
        """Met en place les éléments de l'interface."""
        # -+++++++------------------- main window -------------------+++++++- #
        self.setWindowTitle(u"Encodage / Décodage de Huffman")
        self.centerAndResize()
        centralwidget = QWidget(self)
        mainGrid = QGridLayout(centralwidget)
        mainGrid.setColumnMinimumWidth(0, 450)
        # -+++++++------------------ groupe analyse -----------------+++++++- #
        analysGroup = QGroupBox(u"Analyse", centralwidget)
        self.analysGrid = QGridLayout(analysGroup)
        #         ----------- groupe de la table des codes ----------         #
        codeTableGroup = QGroupBox(u"Table des codes", analysGroup)
        codeTableGrid = QGridLayout(codeTableGroup)
        # un tableau pour les codes
        self.codesTableModel = MyTableModel()
        self.codesTable = QTableView(codeTableGroup)
        self.codesTable.setModel(self.codesTableModel)
        self.codesTable.setFont(QFont("Mono", 8))
        self.codesTable.resizeColumnsToContents()
        self.codesTable.setSortingEnabled(True)
        codeTableGrid.addWidget(self.codesTable, 0, 0, 1, 1)
        self.analysGrid.addWidget(codeTableGroup, 1, 0, 1, 1)
        #        ----------- label du ratio de compression ----------         #
        self.ratioLab = QLabel(u"Ratio de compression: ", analysGroup)
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        font.setKerning(True)
        self.ratioLab.setFont(font)
        self.analysGrid.addWidget(self.ratioLab, 2, 0, 1, 1)
        # -+++++++-------- groupe de la table de comparaison --------+++++++- #
        self.compGroup = QGroupBox(analysGroup)
        self.compGroup.setTitle(u"Comparaisons")
        compGrid = QGridLayout(self.compGroup)
        # un tableau pour le ratio
        self.compTable = QTableWidget(self.compGroup)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.compTable.sizePolicy().hasHeightForWidth())
        self.compTable.setSizePolicy(sizePolicy)
        self.compTable.setBaseSize(QSize(0, 0))
        font = QFont()
        font.setWeight(50)
        self.compTable.setFont(font)
        self.compTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.compTable.setShowGrid(True)
        self.compTable.setGridStyle(Qt.SolidLine)
        # lignes / colonnes
        self.compTable.setColumnCount(2)
        self.compTable.setRowCount(3)
        self.compTable.setVerticalHeaderItem(0, QTableWidgetItem("Taille (bits)"))
        self.compTable.setVerticalHeaderItem(1, QTableWidgetItem("Entropie"))
        self.compTable.setVerticalHeaderItem(2, QTableWidgetItem("Taille moy. (bits)"))
        for i in range(2):
            self.compTable.verticalHeaderItem(i).setTextAlignment(
                Qt.AlignRight)
        self.compTable.setHorizontalHeaderItem(0, QTableWidgetItem("ASCII"))
        self.compTable.setHorizontalHeaderItem(1, QTableWidgetItem("Huffman"))
        
        # nom des items
        self.compTabASCIIMem = QTableWidgetItem()
        self.compTable.setItem(0, 0, self.compTabASCIIMem)
        self.compTabASCIIEnt = QTableWidgetItem()
        self.compTable.setItem(1, 0, self.compTabASCIIEnt)
        self.compTabASCIIAvg = QTableWidgetItem()
        self.compTable.setItem(2, 0, self.compTabASCIIAvg)
        self.compTabHuffMem = QTableWidgetItem()
        self.compTable.setItem(0, 1, self.compTabHuffMem)
        self.compTabHuffEnt = QTableWidgetItem()
        self.compTable.setItem(1, 1, self.compTabHuffEnt)
        self.compTabHuffAvg = QTableWidgetItem()
        self.compTable.setItem(2, 1, self.compTabHuffAvg)
        # parem du tableau
        self.compTable.horizontalHeader().setCascadingSectionResizes(False)
        self.compTable.verticalHeader().setVisible(True)
        font = QFont("Mono", 8)
        self.compTable.setFont(font)
        compGrid.addWidget(self.compTable, 1, 0, 1, 1)
        self.analysGrid.addWidget(self.compGroup, 0, 0, 1, 1)
        mainGrid.addWidget(analysGroup, 0, 1, 1, 1)
        # -+++++++----------------- groupe du texte -----------------+++++++- #
        groupBox = QGroupBox(u"Texte", centralwidget)
        textGrid = QGridLayout(groupBox)
        # -+++++++------------- groupe du texte original ------------+++++++- #
        orgTextGroup = QGroupBox(u"Texte original (Ctrl+T)", groupBox)
        orgTextGrid = QGridLayout(orgTextGroup)
        self.orgText = QTextEdit(orgTextGroup)
        self.orgText.setPalette(self.defaultPalette)
        orgTextGrid.addWidget(self.orgText, 0, 0, 1, 1)
        textGrid.addWidget(orgTextGroup, 0, 0, 1, 2)
        # -+++++++------------ groupe du texte compressé ------------+++++++- #
        compressedTextGroup = QGroupBox(u"Texte compressé (Ctrl+H)", groupBox)
        compressedTextGrid = QGridLayout(compressedTextGroup)
        self.compressedText = QTextEdit(compressedTextGroup)
        self.compressedText.setPalette(self.defaultPalette)
        compressedTextGrid.addWidget(self.compressedText, 0, 0, 1, 1)
        textGrid.addWidget(compressedTextGroup, 1, 0, 1, 2)
        # -+++++++------------ groupe pour le texte ascii -----------+++++++- #
        asciiTextGroup = QGroupBox(u"Texte ASCII", groupBox)
        asciiTextGrid = QGridLayout(asciiTextGroup)
        self.asciiText = QTextBrowser(asciiTextGroup)
        self.asciiText.setPalette(self.defaultPalette)
        asciiTextGrid.addWidget(self.asciiText, 0, 0, 1, 1)
        textGrid.addWidget(asciiTextGroup, 2, 0, 1, 2)
        # -+++++++-------------------- label de log -----------------+++++++- #
        self.logLab = QLabel(analysGroup)
        textGrid.addWidget(self.logLab, 3, 0, 1, 2)
        # -+++++++----------- bouton pour encoder le texte ----------+++++++- #
        self.encodeBut = QPushButton(groupBox)
        self.encodeBut.setStatusTip(
            u"Cliquez sur ce bouton pour encoder le texte original.")
        self.encodeBut.setText(u"ENCODER")
        self.encodeBut.clicked.connect(self.encode_text)
        textGrid.addWidget(self.encodeBut, 4, 0, 1, 1)
        # -+++++++----------- bouton pour décoder le texte ----------+++++++- #
        self.decodeBut = QPushButton(groupBox)
        self.decodeBut.setStatusTip(
            u"Cliquez sur ce bouton pour décoder le texte compressé.")
        self.decodeBut.setText(u"DÉCODER")
        self.decodeBut.clicked.connect(self.decode_text)
        textGrid.addWidget(self.decodeBut, 4, 1, 1, 1)
        mainGrid.addWidget(groupBox, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        # -+++++++--------------- une barre de statut ---------------+++++++- #
        self.setStatusBar(QStatusBar(self))
        # -+++++++--------------------- le menu ---------------------+++++++- #
        self.fileMenu = QMenu(u"Fichier")
        self.fileMenu.addAction(u"Importer un texte...", self.open_text)
        self.fileMenu.addAction(
            u"Importer un texte encodé...", lambda: self.open_text(True))
        self.fileMenu.addAction(u"Importer un dictionnaire...", self.open_dict)
        self.fileMenu.addAction(u"Enregistrer le dictionnaire...", self.save_dict)
        self.fileMenu.addAction(u"Quitter", self.close)
        self.menuBar().addMenu(self.fileMenu)
        QMetaObject.connectSlotsByName(self)

    def open_text(self, compressed=False):
        """Ouvrir un fichier contenant un texte compressé ou non."""
        fname, _ = QFileDialog.getOpenFileName(self, u'Ouvrir')
        f = open(fname, 'r')
        with f:
            data = f.read()
            if compressed:
                self.compressedText.setText(data)
            else:
                self.orgText.setText(data)

    def open_dict(self):
        """Ouvrir un dictionnaire de codes Huffman."""
        fname, _ = QFileDialog.getOpenFileName(self, u'Ouvrir')
        self.occ = {}
        self.hCodes = {}
        self.aCodes = {}
        self.hCost = {}
        self.aCost = {}
        self.hCodes = create_dict_from_file(fname)
        self.update_codes_table()
        self.logLab.setText(u"Dictionnaire de Huffman importé.")
        return self.hCodes

    def save_dict(self):
        """Enregistrer le dictionnaire de codes Huffman."""
        fname, _ = QFileDialog.getSaveFileName(self, "Enregistrer sous")
        save_dict_to_file(fname, self.hCodes)

    def make_tab_rows(self):
        """Génère le remplissage des lignes du tableau des codes."""
        dictList = [self.occ, self.aCodes, self.hCodes, self.aCost, self.hCost]
        tabList = []
        charList = self.hCodes.keys() if self.hCodes else self.occ.keys()
        for char in charList:
            l = ["'" + char + "'"]
            for dic in dictList:
                try:
                    l.append(dic[char])
                except KeyError:
                    l.append('')
            tabList.append(l)
        return tabList

    def encode_text(self, wizard=True):
        """Encode le texte original."""
        self.text = self.orgText.toPlainText().encode('utf-8')
        if not self.text:
            self.compressedText.setText(u"")
            self.asciiText.setText(u"")
            self.logLab.setText(
                u"<font color=#A52A2A>Rien à compresser.</font>")
            return
        self.occ = {}
        self.tree = ()
        self.hCodes = {}
        self.aCodes = {}
        self.hCost = {}
        self.aCost = {}
        self.hSqueezed = []
        self.aSqueezed = []
        self.stringHSqueezed = ''
        self.stringASqueezed = ''
        if wizard:
            self.launch_wizard(
                EncodeWizard(self),
                u"<font color=#008000>Compression achevée.</font>")
        else:
            self.make_occ()
            self.make_tree()
            self.make_codes()
            self.make_cost()
            self.make_encoded_text()
            self.make_comp()

    def decode_text(self, wizard=True):
        """Décode le texte compressé."""
        self.codeString = str(
            self.compressedText.toPlainText().replace(' ', ''))
        if not self.codeString or not self.hCodes:
            self.orgText.setText(u"")
            self.asciiText.setText(u"")
            if not self.codeString:
                self.logLab.setText(
                    u"<font color=#A52A2A>Rien à décompresser.</font>")
            if not self.hCodes:
                self.logLab.setText(
                    u"<font color=#A52A2A>Dictionnaire indisponible pour la décompression.</font>")
            return
        self.text = ''
        self.stringASqueezed = ''
        if wizard:
            self.launch_wizard(
                DecodeWizard(self),
                u"<font color=#008000>Texte décompressé.</font>")
        else:
            self.make_code_map()
            self.make_decoded_text()

    def launch_wizard(self, wizard, finishString):
        """Lance l'assistant d'en/décodage pour guider l'utilisateur.
        Cache les options inaccessibles pendant l'assistant.
        """
        self.logLab.setText(
            u"<font color=#9E6A00>Opération en cours. "
            u"Suivre les indications.</font>")
        disItems = [self.orgText, self.compressedText, self.encodeBut,
                    self.decodeBut, self.fileMenu.actions()[1],
                    self.fileMenu.actions()[2], self.fileMenu.actions()[3]]
        for item in disItems:
            item.setEnabled(False)
        self.compGroup.setVisible(False)
        self.analysGrid.addWidget(wizard, 0, 0, 1, 1)
        res = wizard.exec_()
        if res:
            self.logLab.setText(finishString)
        else:
            self.logLab.setText(
                u"<font color=#A52A2A>Opération interrompue.</font>")
        for item in disItems:
            item.setEnabled(True)
        self.compGroup.setVisible(True)

    def update_ratio_lab(self):
        """Replace la valeur du label du ratio de compression."""
        if not self.stringASqueezed:
            val = '/'
        else:
            val = (len(self.stringHSqueezed.replace(' ', '')) /
                   float(len(self.stringASqueezed.replace(' ', ''))))
        self.ratioLab.setText(unicode('Taux de compression:  ' + str(val)))

    def update_comp_table(self):
        """Met à jour le tableau de comparaison ASCII VS Huffman."""
        self.compTabASCIIMem.setText(unicode(len(''.join(self.aSqueezed))))
        self.compTabHuffMem.setText(unicode(len(''.join(self.hSqueezed))))
        # entropie ?
        self.compTabASCIIEnt.setText('0')
        self.compTabHuffEnt.setText('0')
        self.compTabASCIIAvg.setText(unicode(8))
        self.compTabHuffAvg.setText(unicode(
            average_code_length(self.hSqueezed)))
        self.compTable.resizeColumnsToContents()

    def update_codes_table(self, hlRow=[]):
        """Met à jour le tableau des codes et surligne les lignes de hlRow."""
        self.codesTableModel.hlRow = hlRow
        self.codesTableModel.emptyTable()
        self.codesTableModel.fillTable(self.make_tab_rows())
        self.codesTable.resizeColumnsToContents()

    def centerAndResize(self):
        """Centre et redimmensionne le widget.""" 
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 1.6, screen.height() / 1.4)
        size = self.geometry()
        self.move(
            (screen.width() - size.width()) / 2,
            (screen.height() - size.height()) / 2)

    #===================== METHODS FOR EN/DECODE WIZARDS =====================#
    def make_encode_init(self):
        self.compressedText.setText(unicode(self.stringHSqueezed))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.orgText.setTextColor(QColor(Qt.darkGreen))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.update_codes_table()

    def make_occ(self):
        self.orgText.setTextColor(QColor(Qt.white))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.occ = occurences(self.text)
        self.update_codes_table([0, 1])

    def make_tree(self):
        self.tree = make_trie(self.occ)
        self.update_codes_table()

    def make_codes(self):
        self.hCodes = make_codes(self.tree, {})
        self.aCodes = make_ascii_codes(self.occ.keys(), {})
        self.update_codes_table([2, 3])

    def make_cost(self):
        self.hCost = tree_cost(self.hCodes, self.occ)
        self.aCost = tree_cost(self.aCodes, self.occ)
        self.update_codes_table([4, 5])

    def make_encoded_text(self):
        self.hSqueezed = squeeze(self.text, self.hCodes)
        self.aSqueezed = squeeze(self.text, self.aCodes)
        self.stringHSqueezed = ' '.join(self.hSqueezed)
        self.stringASqueezed = ' '.join(self.aSqueezed)
        self.compressedText.setTextColor(QColor(Qt.darkGreen))
        self.asciiText.setTextColor(QColor(Qt.darkYellow))
        self.compressedText.setText(unicode(self.stringHSqueezed))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table()

    def make_comp(self):
        self.compressedText.setTextColor(QColor(Qt.white))
        self.asciiText.setTextColor(QColor(Qt.white))
        self.compressedText.setText(unicode(self.stringHSqueezed))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table()
        self.update_comp_table()
        self.update_ratio_lab()

    def make_decode_init(self):
        self.orgText.setText(unicode(self.text))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.compressedText.setTextColor(QColor(Qt.darkGreen))
        self.compressedText.setText(self.compressedText.toPlainText())

    def make_code_map(self):
        self.compressedText.setTextColor(QColor(Qt.white))
        self.compressedText.setText(self.compressedText.toPlainText())
        self.orgText.setText(unicode(self.text))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.codeMap = dict(zip(self.hCodes.values(), self.hCodes.keys()))
        self.update_codes_table([0, 3])

    def make_decoded_text(self):
        self.unSqueezed = unsqueeze(self.codeString, self.codeMap)
        self.text = ''.join(self.unSqueezed)
        self.orgText.setTextColor(QColor(Qt.darkGreen))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table()

    def make_ascii_decode(self):
        self.orgText.setTextColor(QColor(Qt.white))
        self.orgText.setText(unicode(self.text.decode('utf-8')))
        self.aCodes = make_ascii_codes(self.codeMap.values(), {})
        self.aSqueezed = squeeze(self.text, self.aCodes)
        self.stringASqueezed = ' '.join(self.aSqueezed)
        self.occ = occurences(self.text)
        self.hCost = tree_cost(self.hCodes, self.occ)
        self.aCost = tree_cost(self.aCodes, self.occ)
        self.asciiText.setTextColor(QColor(Qt.darkGreen))
        self.asciiText.setText(unicode(self.stringASqueezed))
        self.update_codes_table([1, 2, 4, 5])
Beispiel #22
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(730, 475)
        self.setWindowTitle('Combine Code Blocks.')
        centralwidget = QWidget(self)
        gridLayout = QGridLayout(centralwidget)
        # textEdit needs to be a class variable.
        self.textEdit = QTextEdit(centralwidget)
        gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 731, 29))
        menu_File = QMenu(menubar)
        self.setMenuBar(menubar)
        statusbar = QStatusBar(self)
        self.setStatusBar(statusbar)
        actionShow_GPL = QAction(self)
        actionShow_GPL.triggered.connect(self.showGPL)
        action_About = QAction(self)
        action_About.triggered.connect(self.about)        
        iconToolBar = self.addToolBar("iconBar.png")
#------------------------------------------------------
# Add icons to appear in tool bar - step 1
        actionShow_GPL.setIcon(QIcon(":/showgpl.png"))
        action_About.setIcon(QIcon(":/about.png"))
        action_Close = QAction(self)
        action_Close.setCheckable(False)
        action_Close.setObjectName("action_Close")        
        action_Close.setIcon(QIcon(":/quit.png"))
#------------------------------------------------------
# Show a tip on the Status Bar - step 2
        actionShow_GPL.setStatusTip("Show CC Licence")
        action_About.setStatusTip("Pop up the About dialog.")
        action_Close.setStatusTip("Close the program.")
#------------------------------------------------------
        menu_File.addAction(actionShow_GPL)
        menu_File.addAction(action_About)
        menu_File.addAction(action_Close)
        menubar.addAction(menu_File.menuAction())
     
        iconToolBar.addAction(actionShow_GPL)
        iconToolBar.addAction(action_About)
        iconToolBar.addAction(action_Close)
        action_Close.triggered.connect(self.close)
                 
    def showGPL(self):
        '''Read and display CCPL licence.'''
        with open('CCPL.txt') as nonamefile:
            self.textEdit.setText(nonamefile.read())               
           
    def about(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PySide, Platform and version.",
                """<b> about.py version %s </b> 
                <p>Copyright &copy; 2013 by Algis Kabaila. 
                This work is made available under  the terms of
                Creative Commons Attribution-ShareAlike 3.0 license,
                http://creativecommons.org/licenses/by-sa/3.0/.
                <p>This application is useful for displaying  
                Qt version and other details.
                <p>Python %s -  PySide version %s - Qt version %s on %s""" %
                (__version__, platform.python_version(), PySide.__version__,
                 PySide.QtCore.__version__, platform.system()))                        
Beispiel #23
0
class FoamDictWidget(QWidget):
    "QWidget to view and edit simple Foam Dictionary"
    def __init__(self, variable_setting, parent=None):
        super(FoamDictWidget, self).__init__(parent)

        self.buttonLayout = QHBoxLayout()
        self.pushButtonInsert = QPushButton("Insert")
        #self.pushButtonLoad = QPushButton("Load default")
        self.pushButtonRestore = QPushButton("Restore")
        self.pushButtonClear = QPushButton("Clear")
        self.buttonLayout.addWidget(self.pushButtonInsert)
        #self.buttonLayout.addWidget(self.pushButtonLoad)
        self.buttonLayout.addWidget(self.pushButtonRestore)
        self.buttonLayout.addWidget(self.pushButtonClear)

        self.buttonPreview = QPushButton('Preview FoamFile write-out')
        self.textPreview = QTextEdit('')
        self.textPreview.setVisible(False)
        self.textPreview.setEnabled(False)

        self.tableWidget = QTableWidget()
        #header, should not sort, has vertical scrollbar
        # set column count, fixed to 2, size of TableItem
        self.tableWidget.setColumnCount(2)
        #5self.tableWidget.setHorizontalHeaderItem(0, )
        self.tableWidget.setHorizontalHeaderLabels(['key', 'value text'])
        # set a default row count, insert as needed
        self.tableWidget.setRowCount(0)

        #PySide has different name other than @QtCore.pyqtSlot, but PySide.QtCore.SLOT
        QtCore.QObject.connect(self.pushButtonInsert, QtCore.SIGNAL("clicked()"), self.insertRow)
        QtCore.QObject.connect(self.pushButtonRestore, QtCore.SIGNAL("clicked()"), self.restoreDict)
        QtCore.QObject.connect(self.pushButtonClear, QtCore.SIGNAL("clicked()"), self.clearDict)
        #
        QtCore.QObject.connect(self.tableWidget, QtCore.SIGNAL("doubleClicked()"), self.showPreview)  # does not work for PySide
        QtCore.QObject.connect(self.buttonPreview, QtCore.SIGNAL("clicked()"), self.showPreview)
        self._previewing = False

        self.settings = variable_setting
        self.restoreDict()

        self.myLayout = QVBoxLayout()
        self.myLayout.addLayout(self.buttonLayout)
        self.myLayout.addWidget(self.tableWidget)
        self.myLayout.addWidget(self.buttonPreview)
        self.myLayout.addWidget(self.textPreview)
        self.setLayout(self.myLayout)

    def dict(self):
        _settings = OrderedDict()
        for i in range(self.tableWidget.rowCount()):
            k = self.tableWidget.item(i, 0).text()
            v = self.tableWidget.item(i, 1).text()  # data() will return QVariant type-> python type
            # validated by non-empty string
            if k and v:
                _settings[k] = v
        return _settings

    def setDict(self, settings):
        self.settings = settings
        self.updateDictView(self.settings)

    def restoreDict(self):
        self.updateDictView(self.settings)

    def updateDictView(self, varible_settings):
        i = 0
        self.clearDict()  # will clear contents, but leave row text empty
        N = self.tableWidget.rowCount()
        for k,v in varible_settings.items():
            # translate seq into unicode
            if i>=N:
                self.tableWidget.insertRow(i)
            kitem = QTableWidgetItem(k)  # also set flags and state, type
            vitem = QTableWidgetItem(v)  # automaticall convert str to unicode to feed QWidget?
            self.tableWidget.setItem(i, 0, kitem)
            self.tableWidget.setItem(i, 1, vitem)  # currently only works for string value !
            i += 1

    #@pyqtSlot()  # PySide use another name "QtCore.Slot()"
    def insertRow(self):
        nRows = self.tableWidget.rowCount()
        self.tableWidget.insertRow(nRows)  # inset one row at the end
        kitem = QTableWidgetItem("")  # also set flags and state, type
        vitem = QTableWidgetItem("")
        self.tableWidget.setItem(nRows, 0, kitem)
        self.tableWidget.setItem(nRows, 1, vitem)

    def clearDict(self):
        self.tableWidget.clearContents()  # keep the header, clear all items

    def showPreview(self):
        if self._previewing:
            self._previewing = False
            self.textPreview.setVisible(False)
            self.buttonPreview.setText('click to preview write out')
        else:
            self._previewing = True
            self.buttonPreview.setText('click on text to hide preview')
            # enable scrollbar ?
            self.textPreview.setText(self.printDict())
            self.textPreview.setVisible(True)

    def loadDefault(self):
        pass

    def printDict(self):
        dictText = "{\n"
        for k,v in self.dict().items():
            dictText += "   {}  {};\n".format(str(k), str(v))
        dictText += "}"
        return dictText
Beispiel #24
0
class App(QMainWindow):

    def __init__(self, parent=None):
        """Create Qt widgets, connect event handlers."""

        super(App, self).__init__(parent)
        
        self.windowTitle = 'DMD | '
        self.fileName = ''
        
        self.setWindowTitle(self.windowTitle + 'Unsaved File')
        
        exitAction = QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        
        openAction = QAction('Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open Markdown File')
        openAction.triggered.connect(self.openFile)
        
        newAction = QAction('New', self)
        newAction.setShortcut('Ctrl+N')
        newAction.setStatusTip('New Markdown File')
        newAction.triggered.connect(self.newFile)

        saveAction = QAction('Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save File')
        saveAction.triggered.connect(self.saveFile)
        
        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        
        fileMenu.addAction(newAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(exitAction)

        self.setGeometry(300, 300, 1024, 768)
        
        self.show()

        self.txtInput = QTextEdit()
        self.txtInput.setTabStopWidth(20)
        self.webPreview = QWebView()
        self.webPreview.setHtml('Start typing...', baseUrl=QUrl('preview'))
        
        self.txtInput.textChanged.connect(self.loadPreview)
        
        splitter = QSplitter()
        splitter.addWidget(self.txtInput)
        splitter.addWidget(self.webPreview)


        self.setCentralWidget(splitter)
        

    def loadPreview(self):
        """Set the QWebView to the value of the parsed document."""
    
        html = markdown2.markdown(self.txtInput.toPlainText())
        self.webPreview.setHtml(html, baseUrl=QUrl('preview'))
        

    def openFile(self):
        """Handles opening a file, just like any other text editor."""
    
        self.fileName = QFileDialog.getOpenFileName()[0]
    
        fh = open(self.fileName, 'r')
        
        contents = fh.read()
        
        fh.close()
    
        self.txtInput.setText(contents)
        self.setWindowTitle(self.windowTitle + self.fileName)
       

    def newFile(self):
        """Creates a new file, just like any other text editor."""
           
        self.fileName = ''
        self.setWindowTitle(self.windowTitle + 'Unsaved File')
        self.txtInput.setText('')
        
        
    def saveFile(self):
        """Saves the file, just like any other text editor."""
    
        if not self.fileName == '':
            fh = open(self.fileName, 'w')
            fh.write(self.txtInput.toPlainText())
            fh.close()
            self.setWindowTitle(self.windowTitle + self.fileName)
            
        else:
            self.fileName = QFileDialog.getSaveFileName()[0]
            self.saveFile()
Beispiel #25
0
class AppWindow(QMainWindow):

    # =====================
    # The Main Window Class
    # =====================

    def __init__(self):
        # ====================
        # Constructor Function
        # ====================

        QMainWindow.__init__(self)
        self.setWindowTitle("Virtua Text Editor")
        self.setGeometry(300, 300, 1024, 768)

        QToolTip.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.setToolTip('Application Window')

        # ================================
        # Function to setup menus, etc etc
        # ================================
        self.textEdit = QTextEdit()
        self.textEdit.setFont(QFont("Ubuntu", 12, QFont.Normal))
        self.setCentralWidget(self.textEdit)
        self.create_menus()
        self.create_actions()

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveasAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.printAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        self.editMenu.addAction(self.undoAction)
        self.editMenu.addAction(self.redoAction)
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.selectallAction)
        self.editMenu.addAction(self.deselectallAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.findAction)
        self.editMenu.addAction(self.findReplaceAction)

        self.helpMenu.addAction(self.aboutAction)

        self.app_status_bar = QStatusBar()
        self.app_status_bar.showMessage('Ready, v0.2', 10000)
        self.setStatusBar(self.app_status_bar)

        self.create_toolbar()
        self.toolbar.addAction(self.newAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.cutAction)
        self.toolbar.addAction(self.copyAction)
        self.toolbar.addAction(self.pasteAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.printAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.undoAction)
        self.toolbar.addAction(self.redoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.findAction)
        self.toolbar.addAction(self.findReplaceAction)


    def create_toolbar(self):
        # ===============================
        # Function to create the toolbar.
        # ===============================
        self.toolbar = self.addToolBar('Main')
        self.toolbar.setToolButtonStyle(PySide.QtCore.Qt.ToolButtonTextUnderIcon)

    def newfile(self):
        self.textEdit.setText('')

    # TODO: Create the file/open method
    def openfile(self):
        print "Open File Menu Selected"

    # TODO: Create the file/save method
    def savefile(self):
        print "Save File Menu Selected"

    # TODO: Create the file/saveas method
    def saveasfile(self):
        print "Save As File Menu Selected"

    # TODO: Create the print method
    def print_page(self):
        print "Print Page Selected"

    # TODO: Create the find method
    def find_text(self):
        print "Find text option selected"

    # TODO: Create the replace method
    def find_replace_text(self):
        print "Replace text selected"

    def create_actions(self):
        # =========================================
        # Function to create actions for menu items
        # =========================================

        self.newAction = QAction(QIcon('digital_assets/document-new.svg'), 'New', self)
        self.newAction.setShortcut(QKeySequence.New)
        self.newAction.setStatusTip("Create a New File")
        self.newAction.setIconText("New")
        self.newAction.triggered.connect(self.newfile)

        self.openAction = QAction(QIcon('digital_assets/document-open.svg'), 'Open', self)
        self.openAction.setShortcut(QKeySequence.Open)
        self.openAction.setStatusTip("Open a file")
        self.openAction.triggered.connect(self.openfile)

        self.saveAction = QAction(QIcon('digital_assets/document-save.svg'), 'Save', self)
        self.saveAction.setShortcut(QKeySequence.Save)
        self.saveAction.setStatusTip("Save a file")
        self.saveAction.triggered.connect(self.savefile)

        self.saveasAction = QAction(QIcon('digital_assets/document-save-as.svg'), 'Save As', self)
        self.saveasAction.setShortcut(QKeySequence.SaveAs)
        self.saveasAction.setStatusTip("Save a File As....")
        self.saveasAction.triggered.connect(self.saveasfile)

        self.printAction = QAction(QIcon('digital_assets/document-print.svg'), 'Print', self)
        self.printAction.setShortcut(QKeySequence.Print)
        self.printAction.setStatusTip("Print")
        self.printAction.triggered.connect(self.print_page)

        self.exitAction = QAction(QIcon('digital_assets/application-exit.svg'), 'Exit', self)
        self.exitAction.setShortcut(QKeySequence.Quit)
        self.exitAction.setStatusTip("Exit the Application")
        self.exitAction.triggered.connect(self.quit_application)

        self.undoAction = QAction(QIcon('digital_assets/undo.svg'), 'Undo', self)
        self.undoAction.setShortcut(QKeySequence.Undo)
        self.undoAction.setStatusTip("Undo")
        self.undoAction.triggered.connect(self.textEdit.undo)

        self.redoAction = QAction(QIcon('digital_assets/redo.svg'), 'Redo', self)
        self.redoAction.setShortcut(QKeySequence.Redo)
        self.redoAction.setStatusTip("Redo")
        self.redoAction.triggered.connect(self.textEdit.redo)

        self.cutAction = QAction(QIcon('digital_assets/edit-cut.svg'), 'Cut', self)
        self.cutAction.setShortcut(QKeySequence.Cut)
        self.cutAction.setStatusTip("Cut")
        self.cutAction.setEnabled(False)
        self.cutAction.triggered.connect(self.textEdit.cut)

        self.copyAction = QAction(QIcon('digital_assets/edit-copy.svg'), 'Copy', self)
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.copyAction.setStatusTip("Copy")
        self.copyAction.setEnabled(False)
        self.copyAction.triggered.connect(self.textEdit.copy)

        self.pasteAction = QAction(QIcon('digital_assets/edit-paste.svg'), 'Paste', self)
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.pasteAction.setStatusTip("Paste")
        self.pasteAction.setEnabled(False)
        self.pasteAction.triggered.connect(self.textEdit.paste)

        self.selectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Select All', self)
        self.selectallAction.setShortcut(QKeySequence.SelectAll)
        self.selectallAction.setStatusTip("Select All")
        self.selectallAction.triggered.connect(self.textEdit.selectAll)

        self.deselectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Deselect All', self)
        self.deselectallAction.setShortcut("Shift+Ctrl+A")
        self.deselectallAction.setStatusTip("Deselect All")
        self.deselectallAction.triggered.connect(self.deselect_all_text)

        self.findAction = QAction(QIcon('digital_assets/edit-find.svg'), 'Find', self)
        self.findAction.setShortcut(QKeySequence.Find)
        self.findAction.setStatusTip("Find")
        self.findAction.triggered.connect(self.find_text)

        self.findReplaceAction = QAction(QIcon('digital_assets/edit-find-replace.svg'), 'Replace', self)
        self.findReplaceAction.setShortcut(QKeySequence.Replace)
        self.findReplaceAction.setShortcut("Replace")
        self.findReplaceAction.triggered.connect(self.find_replace_text)

        self.aboutAction = QAction(QIcon('digital_assets/AppIcon.png'), 'About', self)
        self.aboutAction.setStatusTip("Displays info about the application")
        self.aboutAction.triggered.connect(self.show_about)


    def deselect_all_text(self):
        text_cursor = self.textEdit.textCursor()
        text_cursor.clearSelection()
        self.textEdit.setTextCursor(text_cursor)

    def create_menus(self):
        # ================================
        # Function to create the menu bar.
        # ================================
        self.fileMenu = self.menuBar().addMenu("File")
        self.fileMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.editMenu = self.menuBar().addMenu("Edit")
        self.editMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.helpMenu = self.menuBar().addMenu("Help")
        self.helpMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))

    def set_icon(self):
        # ===============================
        # Function to set the Window Icon
        # ===============================
        appicon = QIcon('digital_assets/AppIcon.png')
        self.setWindowIcon(appicon)

    def quit_application(self):
        # ================================
        # Function to quit the application
        # ================================
        userinfo = QMessageBox.question(self, "Confirmation", "This will quit, Do you want to continue?",
                                        QMessageBox.Yes | QMessageBox.No)
        if userinfo == QMessageBox.Yes:
            templateApp.quit()
        if userinfo == QMessageBox.No:
            pass

    def show_about(self):
        QMessageBox.about(self, "About Virtua Text Editor",
                          "<b><h3>Virtua Text Editor</h3></b>"
                          "<p><h4>Virtua Text Editor has been written to serve as a template"
                          " that can be used as a basis for creating a working application."
                          " All of the components that make up the core functions of an"
                          " application, the main window, a status bar, menus and dialogs"
                          " are provided here as a basis for writing something new and interesting</h4></p>")

    def center_application(self):
        # ============================================
        # Function to center the Application on screen
        # ============================================
        qrect = self.frameGeometry()
        centerpoint = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(centerpoint)
        self.move(qrect.topLeft())
Beispiel #26
0
    def get_info(self):

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

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

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

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

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

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

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

        def save_info(self):

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

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

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

            recdir = data_save_dir + current_whose_animal + '/' + current_animal_number

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

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

            self.experiment_info = self.experiment_info.encode()

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

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

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

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

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

        self.info_window.show()
Beispiel #27
0
class SupplyOrderOverview(HorsePanel):
    def close_panel(self):
        self.filter_widget.remember_current_selection(configuration)

    def _selected_supply_order_part(self):
        cur_ndx = self.search_results_view.currentIndex()
        if cur_ndx.row() >= 0:
            return cur_ndx.model().object_at(cur_ndx.row())
        return None

    @Slot()
    def show_actions(self):
        button = self.action_menu.parent()
        p = button.mapToGlobal(QPoint(0, button.height()))
        self.action_menu.exec_(p)

    SECTION_REFERENCE = 0
    SECTION_SUPPLIER = 1
    SECTION_DEADLINE = 2
    SECTION_DESCRIPTION = 3
    SECTION_CREATION_DATE = 6

    def _make_sort_criteria(self, section_sorted, sort_order):

        sort_criteria = None

        if section_sorted == self.SECTION_REFERENCE:
            if sort_order == Qt.AscendingOrder:

                def ordering_key(p):
                    return p.accounting_label * 1000 + p.position

                sort_criteria = lambda a, b: cmp(ordering_key(a),
                                                 ordering_key(b))
            else:

                def ordering_key(p):
                    return p.accounting_label * 1000 + 999 - p.position

                sort_criteria = lambda a, b: cmp(ordering_key(a),
                                                 ordering_key(b))
        elif section_sorted == self.SECTION_SUPPLIER:
            order_correction = +1
            if sort_order == Qt.DescendingOrder:
                order_correction = -1

            sort_criteria = lambda a,b: cmp(a.supplier_fullname, b.supplier_fullname) or \
                            cmp(a.accounting_label,b.accounting_label) or order_correction * cmp(a.position,b.position)
        elif section_sorted == self.SECTION_DEADLINE:  # Deadline
            sort_criteria = lambda a, b: cmp(
                a.expected_delivery_date or date(2100, 1, 1), b.
                expected_delivery_date or date(2100, 1, 1))

        return sort_criteria

    def _fill_model(self, parts_data=None):
        """ Refills the list of parts data with given parts
        data. If no parts data are given, then the last
        data set is reused.

        This thake into account the currently selected sort
        indicator and, if any, the currently selected filter.
        """

        if parts_data is not None:
            self.parts_data = parts_data
        else:
            parts_data = self.parts_data

        view = self.search_results_view
        model = self.search_results_model
        headers = view.horizontalHeader()
        sort_order = headers.sortIndicatorOrder()
        section_sorted = headers.sortIndicatorSection()

        sort_criteria = self._make_sort_criteria(section_sorted, sort_order)
        if sort_criteria:
            sort_order = headers.sortIndicatorOrder()

            if sys.version[0] == '3':
                parts_data = sorted(parts_data,
                                    key=cmp_to_key(sort_criteria),
                                    reverse=sort_order == Qt.DescendingOrder)
            else:
                parts_data = sorted(parts_data,
                                    sort_criteria,
                                    reverse=sort_order == Qt.DescendingOrder)

        model.buildModelFromObjects(parts_data)

        if sort_criteria:
            # Changing the model removes the sort order (which makes sense because
            # changing the model may alter the order of rows)
            # => I have to reset it
            headers.setSortIndicator(section_sorted, sort_order)

        if len(parts_data) == 0:
            # Must do this because when the model is empty
            # the slection is not updated, so no signal
            # is sent
            self._fill_order_part_detail(None)
        else:
            view.selectionModel().reset()
            view.selectionModel().select(
                view.model().index(0, 0),
                QItemSelectionModel.Select | QItemSelectionModel.Rows)

        view.horizontalHeader().setResizeMode(self.SECTION_DESCRIPTION,
                                              QHeaderView.Stretch)

    @Slot()
    def refresh_action(self):
        mainlog.debug("refresh_action")
        self._apply_filter(self.filter_widget.current_filter())

    @Slot(int)
    def section_clicked(self, logical_ndx):
        self._fill_model()

    @Slot(str)
    def _apply_filter(self, filter_text):
        mainlog.debug(u"_apply_filter : {}".format(filter_text))

        parts = []
        len_check = False

        if " " in filter_text.strip():
            # More than one word in the filter => I assume it's the full
            # fledged filtering

            check = check_parse(filter_text)
            if check == True:
                parts = supply_order_service.find_parts_expression_filter(
                    filter_text)
                len_check = True
            else:
                showErrorBox(_("Error in the filter !"),
                             check,
                             object_name="filter_is_wrong")

        elif filter_text:
            parts = supply_order_service.find_parts_filtered(filter_text)
            len_check = True
        else:
            parts = supply_order_service.find_recent_parts()
            len_check = False

        if len_check and len(parts) >= supply_order_service.MAX_RESULTS:
            showWarningBox(
                _("Too many results"),
                _("The query you've given brought back too many results. Only a part of them is displayed. Consider refining your query"
                  ))
        self._fill_model(parts)
        self.search_results_view.setFocus(Qt.OtherFocusReason)

    def _make_supply_order_detail_view(self):

        # There's a self.proto somewhere, don't mess with it :-)

        # proto = []
        # proto.append( TextLinePrototype('description',_('Description'), editable=True,nullable=False))
        # proto.append( FloatNumberPrototype('quantity',_('Quantity'), editable=True,nullable=False))
        # proto.append( FloatNumberPrototype('unit_price',_('Unit price'), editable=True,nullable=False))

        # self.detail_model = PrototypedModelView(proto, self)
        # self.detail_view = PrototypedQuickView(proto, self)
        # self.detail_view.setModel(self.detail_model)
        # self.detail_view.verticalHeader().hide()

        self.detail_description = QTextEdit()
        self.detail_description.setTextInteractionFlags(
            Qt.TextBrowserInteraction)

        self.delivery_date_widget = QLabel()
        self.creation_date_widget = QLabel()
        self.supplier_reference_widget = QLabel()

        hlayout = QHBoxLayout()
        hlayout.addWidget(QLabel(_("Delivery date")))
        hlayout.addWidget(self.delivery_date_widget)
        hlayout.addStretch()

        hlayout3 = QHBoxLayout()
        hlayout3.addWidget(QLabel(_("Creation date")))
        hlayout3.addWidget(self.creation_date_widget)
        hlayout3.addStretch()

        hlayout2 = QHBoxLayout()
        hlayout2.addWidget(QLabel(_("Supplier's reference")))
        hlayout2.addWidget(self.supplier_reference_widget)
        hlayout2.addStretch()

        layout = QVBoxLayout()
        layout.addLayout(hlayout)
        layout.addLayout(hlayout3)
        layout.addLayout(hlayout2)
        layout.addWidget(self.detail_description)
        layout.addStretch()

        # layout.addWidget(self.detail_view)
        # layout.setStretch(0,1)
        # layout.setStretch(1,3)

        return layout

    @Slot()
    def _toggle_edit_filters(self):
        self.filter_widget.setVisible(not self.filter_widget.isVisible())

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

        initialize_supplier_cache()

        self.set_panel_title(_("Supply Orders"))

        # navigation = NavBar( self,
        #                      [ (_("Action"),self.show_actions) ] )
        # self.action_menu = QMenu(navigation.buttons[0])

        title = _("Supply orders")
        # self.setWindowTitle(title)

        filter_family = FilterQuery.SUPPLIER_ORDER_SLIPS_FAMILY
        self.filter_widget = PersistentFilter(filter_family)
        self.filter_widget.apply_filter.connect(self._apply_filter)
        self.filter_widget.hide()

        self.proto = []
        self.proto.append(
            TextLinePrototype('human_identifier', _("Part Nr"),
                              editable=False))
        self.proto.append(
            TextLinePrototype('supplier_fullname',
                              _('Supplier'),
                              editable=False))
        self.proto.append(
            DatePrototype('expected_delivery_date',
                          _('Deadline'),
                          editable=True,
                          nullable=False))
        self.proto.append(
            TextLinePrototype('description',
                              _('Description'),
                              editable=True,
                              nullable=False))
        self.proto.append(
            FloatNumberPrototype('quantity',
                                 _('Quantity'),
                                 editable=True,
                                 nullable=False))
        self.proto.append(
            FloatNumberPrototype('unit_price',
                                 _('Unit price'),
                                 editable=True,
                                 nullable=False))
        self.proto.append(
            DatePrototype('creation_date',
                          _('Creation date'),
                          editable=False,
                          nullable=False))

        # self.proto.append( DatePrototype('creation_date',_('Creation'), editable=False))
        # self.proto.append( DatePrototype('expected_delivery_date',_('Expected\ndelivery'), editable=False))
        # self.proto.append( TextLinePrototype('supplier_fullname',_('Supplier'), editable=False))

        self.search_results_model = PrototypedModelView(self.proto, self)
        self.search_results_view = PrototypedQuickView(self.proto, self)
        self.search_results_view.setModel(self.search_results_model)
        self.search_results_view.horizontalHeader().setSortIndicatorShown(True)

        self.search_results_view.verticalHeader().hide()
        self.search_results_view.verticalHeader().setResizeMode(
            QHeaderView.ResizeToContents)
        self.search_results_view.doubleClicked.connect(
            self._supply_order_double_clicked)
        self.search_results_view.activated.connect(
            self._supply_order_double_clicked)
        self.search_results_view.horizontalHeader().sectionClicked.connect(
            self.section_clicked)

        top_layout = QVBoxLayout(self)

        navigation = NavBar(self,
                            [(self.filter_widget.get_filters_combo(), None),
                             (_("Edit filter"), self._toggle_edit_filters)])

        self.title_widget = TitleWidget(title, self, navigation)  # navigation)

        hlayout_results = QHBoxLayout()
        # w = SubFrame(_("Supply order parts"),self.search_results_view,None)
        hlayout_results.addWidget(self.search_results_view)

        w = SubFrame(_("Supply order detail"),
                     self._make_supply_order_detail_view(), None)
        hlayout_results.addWidget(w)

        hlayout_results.setStretch(0, 2)
        hlayout_results.setStretch(0, 1)

        top_layout.addWidget(self.title_widget)
        top_layout.addWidget(self.filter_widget)
        top_layout.addLayout(hlayout_results)
        top_layout.setStretch(3, 100)
        self.setLayout(top_layout)

        self.search_results_view.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.search_results_view.setSelectionMode(
            QAbstractItemView.SingleSelection)

        # self.search_results_view.activated.connect(self.row_activated)
        self.search_results_view.selectionModel().currentRowChanged.connect(
            self.row_selected)
        # self.detail_view.doubleClicked.connect(self._supply_order_double_clicked)

        # pub.subscribe(self.refresh_panel, 'supply_order.changed')
        # pub.subscribe(self.refresh_panel, 'supply_order.deleted')
        # self.filter_widget.select_default_filter()
        self.filter_widget.load_last_filter(configuration)

    supply_order_selected = Signal(object)

    @Slot(QModelIndex)
    def _supply_order_double_clicked(self, cur_ndx):
        mainlog.debug("_supply_order_double_clicked")
        supply_order = cur_ndx.model().object_at(cur_ndx.row())
        if supply_order:
            self.supply_order_selected.emit(supply_order)

    def _fill_order_part_detail(self, supply_order_part):
        if supply_order_part:
            supply_order_part_id = supply_order_part.supply_order_id
            supply_order, parts = supply_order_service.find_by_id(
                supply_order_part.supply_order_id)
            self.detail_description.setText(supply_order.description)
            self.delivery_date_widget.setText(
                date_to_s(supply_order.expected_delivery_date) or "-")
            self.supplier_reference_widget.setText(
                supply_order.supplier_reference or "-")
            self.creation_date_widget.setText(
                date_to_s(supply_order.creation_date) or "-")
        else:
            self.detail_description.setText("-")
            self.delivery_date_widget.setText("-")
            self.supplier_reference_widget.setText("-")
            self.creation_date_widget.setText("-")

    @Slot(QModelIndex, QModelIndex)
    def row_selected(self, cur_ndx, prev_ndx):
        if cur_ndx.model():
            supply_order_part = cur_ndx.model().object_at(cur_ndx.row())
            self._fill_order_part_detail(supply_order_part)
Beispiel #28
0
class RobocompDslGui(QMainWindow):
    def __init__(self, parent=None):
        super(RobocompDslGui, self).__init__(parent)
        self.setWindowTitle("Create new component")
        # self._idsl_paths = []
        self._communications = {
            "implements": [],
            "requires": [],
            "subscribesTo": [],
            "publishes": []
        }
        self._interfaces = {}
        self._cdsl_doc = CDSLDocument()
        self._command_process = QProcess()

        self._main_widget = QWidget()
        self._main_layout = QVBoxLayout()
        self.setCentralWidget(self._main_widget)

        self._name_layout = QHBoxLayout()
        self._name_line_edit = QLineEdit()
        self._name_line_edit.textEdited.connect(self.update_component_name)
        self._name_line_edit.setPlaceholderText("New component name")
        self._name_layout.addWidget(self._name_line_edit)
        self._name_layout.addStretch()

        # DIRECTORY SELECTION
        self._dir_line_edit = QLineEdit()
        # self._dir_line_edit.textEdited.connect(self.update_completer)
        self._dir_completer = QCompleter()
        self._dir_completer_model = QFileSystemModel()
        if os.path.isdir(ROBOCOMP_COMP_DIR):
            self._dir_line_edit.setText(ROBOCOMP_COMP_DIR)
            self._dir_completer_model.setRootPath(ROBOCOMP_COMP_DIR)
        self._dir_completer.setModel(self._dir_completer_model)
        self._dir_line_edit.setCompleter(self._dir_completer)

        self._dir_button = QPushButton("Select directory")
        self._dir_button.clicked.connect(self.set_output_directory)
        self._dir_layout = QHBoxLayout()
        self._dir_layout.addWidget(self._dir_line_edit)
        self._dir_layout.addWidget(self._dir_button)

        # LIST OF ROBOCOMP INTERFACES
        self._interface_list = QListWidget()
        self._interface_list.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self._interface_list.itemSelectionChanged.connect(
            self.set_comunication)

        # LIST OF CONNECTION TyPES
        self._type_combo_box = QComboBox()
        self._type_combo_box.addItems(
            ["publishes", "implements", "subscribesTo", "requires"])
        self._type_combo_box.currentIndexChanged.connect(
            self.reselect_existing)

        # BUTTON TO ADD A NEW CONNECTION
        # self._add_connection_button = QPushButton("Add")
        # self._add_connection_button.clicked.connect(self.add_new_comunication)
        self._add_connection_layout = QHBoxLayout()
        # self._add_connection_layout.addWidget(self._add_connection_button)
        self._language_combo_box = QComboBox()
        self._language_combo_box.addItems(["Python", "Cpp", "Cpp11"])
        self._language_combo_box.currentIndexChanged.connect(
            self.update_language)
        self._add_connection_layout.addWidget(self._language_combo_box)
        self._add_connection_layout.addStretch()
        self._gui_check_box = QCheckBox()
        self._gui_check_box.stateChanged.connect(self.update_gui_selection)
        self._gui_label = QLabel("Use Qt GUI")
        self._add_connection_layout.addWidget(self._gui_label)
        self._add_connection_layout.addWidget(self._gui_check_box)

        # WIDGET CONTAINING INTERFACES AND TYPES
        self._selection_layout = QVBoxLayout()
        self._selection_layout.addWidget(self._type_combo_box)
        self._selection_layout.addWidget(self._interface_list)
        self._selection_layout.addLayout(self._add_connection_layout)
        self._selection_widget = QWidget()
        self._selection_widget.setLayout(self._selection_layout)

        # TEXT EDITOR WITH THE RESULTING CDSL CODE
        self._editor = QTextEdit(self)
        self._editor.setHtml("")

        self._document = self._editor.document()
        self._component_directory = None

        # SPLITTER WITH THE SELECTION AND THE CODE
        self._body_splitter = QSplitter(Qt.Horizontal)
        self._body_splitter.addWidget(self._selection_widget)
        self._body_splitter.addWidget(self._editor)
        self._body_splitter.setStretchFactor(0, 2)
        self._body_splitter.setStretchFactor(1, 9)

        # CREATION BUTTONS
        self._create_button = QPushButton("Create .cdsl")
        self._create_button.clicked.connect(self.write_cdsl_file)
        self._creation_layout = QHBoxLayout()
        self._creation_layout.addStretch()
        self._creation_layout.addWidget(self._create_button)

        self._console = QConsole()
        self._command_process.readyReadStandardOutput.connect(
            self._console.standard_output)
        self._command_process.readyReadStandardError.connect(
            self._console.error_output)

        # ADDING WIDGETS TO MAIN LAYOUT
        self._main_widget.setLayout(self._main_layout)
        self._main_layout.addLayout(self._name_layout)
        self._main_layout.addLayout(self._dir_layout)
        self._main_layout.addWidget(self._body_splitter)
        self._main_layout.addLayout(self._creation_layout)
        self._main_layout.addWidget(self._console)
        self.setMinimumSize(800, 500)
        self._editor.setText(self._cdsl_doc.generate_doc())

    # self.editor->show();

    # def update_completer(self, path):
    # 	print "update_completer %s"%path
    # 	info = QFileInfo(path)
    # 	if info.exists() and info.isDir():
    # 			if not path.endswith(os.path.pathsep):
    # 				new_path = os.path.join(path, os.sep)
    # 				# self._dir_line_edit.setText(new_path)
    # 			all_dirs_output = [dI for dI in os.listdir(path) if os.path.isdir(os.path.join(path, dI))]
    # 			print all_dirs_output
    # 			self._dir_completer.complete()

    def load_idsl_files(self, fullpath=None):
        if fullpath is None:
            fullpath = ROBOCOMP_INTERFACES
        idsls_dir = os.path.join(ROBOCOMP_INTERFACES, "IDSLs")
        if os.path.isdir(idsls_dir):
            for full_filename in os.listdir(idsls_dir):
                file_name, file_extension = os.path.splitext(full_filename)
                if "idsl" in file_extension.lower():
                    full_idsl_path = os.path.join(idsls_dir, full_filename)
                    # self._idsl_paths.append(os.path.join(idsls_dir,full_filename))
                    self.parse_idsl_file(full_idsl_path)
        self._interface_list.addItems(self._interfaces.keys())

    def parse_idsl_file(self, fullpath):

        with open(fullpath, 'r') as fin:
            interface_name = None
            for line in fin:
                result = re.findall(r'^\s*interface\s+(\w+)\s*\{?\s*$',
                                    line,
                                    flags=re.MULTILINE)
                if len(result) > 0:
                    interface_name = result[0]
            print("%s for idsl %s" % (interface_name, fullpath))
            if interface_name is not None:
                self._interfaces[interface_name] = fullpath

    def add_new_comunication(self):
        interface_names = self._interface_list.selectedItems()
        com_type = str(self._type_combo_box.currentText())
        for iface_name_item in interface_names:
            iface_name = str(iface_name_item.text())
            self._communications[com_type].append(iface_name)
            idsl_full_path = self._interfaces[iface_name]
            idsl_full_filename = os.path.basename(idsl_full_path)
            self._cdsl_doc.add_comunication(com_type, iface_name)
            self._cdsl_doc.add_import(idsl_full_filename)
        self.update_editor()

    def set_comunication(self):
        interface_names = self._interface_list.selectedItems()
        com_type = str(self._type_combo_box.currentText())
        self._communications[com_type] = []
        self._cdsl_doc.clear_comunication(com_type)
        for iface_name_item in interface_names:
            iface_name = str(iface_name_item.text())
            self._communications[com_type].append(iface_name)
            self._cdsl_doc.add_comunication(com_type, iface_name)
        self.update_imports()
        self.update_editor()

    def update_imports(self):
        self._cdsl_doc.clear_imports()
        for com_type in self._communications:
            for iface_name in self._communications[com_type]:
                idsl_full_path = self._interfaces[iface_name]
                idsl_full_filename = os.path.basename(idsl_full_path)
                self._cdsl_doc.add_import(idsl_full_filename)

    def update_language(self):
        language = self._language_combo_box.currentText()
        self._cdsl_doc.set_language(str(language))
        self.update_editor()

    def update_gui_selection(self):
        checked = self._gui_check_box.isChecked()
        if checked:
            self._cdsl_doc.set_qui(True)
        else:
            self._cdsl_doc.set_qui(False)
        self.update_editor()

    def update_component_name(self, name):
        self._cdsl_doc.set_name(name)
        self.update_editor()

    def update_editor(self):
        self._editor.setText(self._cdsl_doc.generate_doc())

    def set_output_directory(self):
        dir_set = False
        while not dir_set:
            dir = QFileDialog.getExistingDirectory(
                self, "Select Directory", ROBOCOMP_COMP_DIR,
                QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
            if self.check_dir_is_empty(str(dir)):
                self._dir_line_edit.setText(dir)
                dir_set = True

    def write_cdsl_file(self):
        component_dir = str(self._dir_line_edit.text())
        text = self._cdsl_doc.generate_doc()
        if not self._name_line_edit.text():
            component_name, ok = QInputDialog.getText(self,
                                                      'No component name set',
                                                      'Enter component name:')
            if ok:
                self.update_component_name(component_name)
                self._name_line_edit.setText(component_name)
            else:
                return False

        if not os.path.exists(component_dir):
            if QMessageBox.Yes == QMessageBox.question(
                    self, "Directory doesn't exist.",
                    "Do you want create the directory %s?" % component_dir,
                    QMessageBox.Yes | QMessageBox.No):
                os.makedirs(component_dir)
            else:
                QMessageBox.question(
                    self, "Directory not exist",
                    "Can't create a component witout a valid directory")
                return False

        file_path = os.path.join(component_dir,
                                 str(self._name_line_edit.text()) + ".cdsl")
        if os.path.exists(file_path):
            if QMessageBox.No == QMessageBox.question(
                    self, "File already exists", "Do you want to overwrite?",
                    QMessageBox.Yes | QMessageBox.No):
                return False

        with open(file_path, 'w') as the_file:
            the_file.write(text)
        self.execute_robocomp_cdsl()
        return True

    def execute_robocomp_cdsl(self):
        cdsl_file_path = os.path.join(
            str(self._dir_line_edit.text()),
            str(self._name_line_edit.text()) + ".cdsl")
        command = "python -u %s/robocompdsl.py %s %s" % (
            ROBOCOMPDSL_DIR, cdsl_file_path,
            os.path.join(str(self._dir_line_edit.text())))
        self._console.append_custom_text("%s\n" % command)
        self._command_process.start(command,
                                    QProcess.Unbuffered | QProcess.ReadWrite)

    def reselect_existing(self):
        com_type = self._type_combo_box.currentText()
        selected = self._communications[com_type]
        self._interface_list.clearSelection()
        for iface in selected:
            items = self._interface_list.findItems(iface,
                                                   Qt.MatchFlag.MatchExactly)
            if len(items) > 0:
                item = items[0]
                item.setSelected(True)

    def check_dir_is_empty(self, dir_path):
        if len(os.listdir(dir_path)) > 0:
            msgBox = QMessageBox()
            msgBox.setWindowTitle("Directory not empty")
            msgBox.setText(
                "The selected directory is not empty.\n"
                "For a new Component you usually want a new directory.\n"
                "Do you want to use this directory anyway?")
            msgBox.setStandardButtons(QMessageBox.Yes)
            msgBox.addButton(QMessageBox.No)
            msgBox.setDefaultButton(QMessageBox.No)
            if msgBox.exec_() == QMessageBox.Yes:
                return True
            else:
                return False
        else:
            return True
Beispiel #29
0
class ConsoleWidget(QMainWindow):
    def __init__(self):
        super(ConsoleWidget, self).__init__()
        self.setWindowTitle('1c query')

        self._connection = None

        self._home = os.path.expanduser('~/%s' % QApplication.applicationName())
        if not os.path.isdir(self._home):
            os.mkdir(self._home)

        self.queryToolBar = self.addToolBar('Query')
        self.queryAction = self.queryToolBar.addAction('Run', self.executeQuery)
        self.queryAction.setDisabled(True)

        uri_history = list()
        path = os.path.join(self._home, 'uri_history.txt')
        if os.path.isfile(path):
            uri_history = open(path, 'r').read().split('\n')

        self.connectionToolBar = self.addToolBar('Connection')
        self.connectionUriCombo = QComboBox(self)
        self.connectionUriCombo.setEditable(True)
        if not uri_history:
            self.connectionUriCombo.addItem('File="";usr="";pwd="";')
            self.connectionUriCombo.addItem('Srvr="{host}";Ref="{ref}";Usr="******";Pwd="{password}";')
        else:
            self.connectionUriCombo.addItems(uri_history)
            self.connectionUriCombo.setCurrentIndex(len(uri_history) - 1)
        self.connectionUriCombo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
        self.connectionToolBar.addWidget(self.connectionUriCombo)

        self.onesVersionCombo = QComboBox(self)
        self.onesVersionCombo.addItems(['8.3', '8.2', '8.1', '8.0'])
        self.onesVersionCombo.setCurrentIndex(0)
        self.connectionToolBar.addWidget(self.onesVersionCombo)
        self.connectAction = self.connectionToolBar.addAction('Connect', self.connectOneS)
        self.disconnectAction = self.connectionToolBar.addAction('Disconnect', self.disconnectOneS)
        self.disconnectAction.setDisabled(True)

        self.logEdit = QPlainTextEdit(self)
        self.logDock = QDockWidget('Log', self)
        self.logDock.setWidget(self.logEdit)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.logDock, Qt.Horizontal)

        self.splitter = QSplitter(Qt.Vertical, self)
        self.setCentralWidget(self.splitter)

        self.sqlEdit = QTextEdit(self)
        self.sqlEdit.setLineWrapMode(QTextEdit.NoWrap)

        path = os.path.join(self._home, 'last-sql.txt')
        if os.path.isfile(path):
            sql = open(path, 'r').read()
            self.sqlEdit.setText(sql)

        self.model = QStandardItemModel(self)
        self.tableView = QTableView(self)
        self.tableView.setModel(self.model)

        self.splitter.addWidget(self.sqlEdit)
        self.splitter.addWidget(self.tableView)
        self.splitter.setStretchFactor(0, 3)
        self.splitter.setStretchFactor(1, 2)

    def query(self, sql):
        if not self._connection:
            self.logEdit.appendPlainText('No connection')
            return None

        try:
            query = self._connection.NewObject('Query', sql)
            result = query.Execute()
        except Exception as e:
            self.logEdit.appendPlainText(str(e))
            return None

        return result

    def refresh(self, result):
        self.model.clear()

        columns = list()
        result_columns = result.Columns
        for index in range(result_columns.Count()):
            name = result_columns.Get(index).Name
            columns.append(name)

        self.model.setColumnCount(len(columns))
        for section, name in enumerate(columns):
            self.model.setHeaderData(section, Qt.Horizontal, name)

        select = result.Choose()
        self.logEdit.appendPlainText('Selected %d records' % select.Count())
        while select.Next():
            items = list()
            for index in range(len(columns)):
                value = select.Get(index)

                item = QStandardItem('')
                if isinstance(value, bool):
                    item.setText(value and 'Yes' or 'No')

                elif isinstance(value, (int, str)):
                    item.setText(str(value))

                elif isinstance(value, datetime.datetime):
                    item.setText(value.strftime('%Y.%m.%d %H:%M:%S'))

                else:
                    item.setText(str(value))
                items.append(item)

            self.model.appendRow(items)

    @Slot()
    def executeQuery(self):
        sql = self.sqlEdit.toPlainText()
        result = self.query(sql)
        if result:
            path = os.path.join(self._home, 'last-sql.txt')
            open(path, 'w').write(sql)
            self.refresh(result)

    @Slot()
    def connectOneS(self):
        uri = self.connectionUriCombo.currentText().strip()
        if not uri:
            self.logEdit.appendPlainText('Need a connection string')
            return

        version = self.onesVersionCombo.currentText()
        comName = "V%s.COMConnector" % str(version).replace('.', '')

        pythoncom.CoInitialize()
        try:
            obj = win32com.client.Dispatch(comName)
            self._connection = obj.Connect(uri)
        except Exception as e:
            self.logEdit.appendPlainText(str(e))
            return

        self.connectAction.setDisabled(True)
        self.disconnectAction.setEnabled(True)
        self.queryAction.setEnabled(True)

        uri_history = list()
        for i in range(self.connectionUriCombo.count()):
            uri_history.append(self.connectionUriCombo.itemText(i))

        if uri not in uri_history:
            self.connectionUriCombo.clearEditText()
            self.connectionUriCombo.addItem(uri)
            self.connectionUriCombo.setCurrentIndex(len(uri_history))
            uri_history.append(uri)
            path = os.path.join(self._home, 'uri_history.txt')
            open(path, 'w').write('\n'.join(uri_history))

    @Slot()
    def disconnectOneS(self):
        pythoncom.CoUninitialize()
        self._connection = None
        self.connectAction.setEnabled(True)
        self.disconnectAction.setDisabled(True)
        self.queryAction.setDisabled(True)
Beispiel #30
0
class MainWindow(QMainWindow):
    """ Our Main Window class
    """
    def __init__(self):
        """ Constructor Function
        """
        QMainWindow.__init__(self)
        self.setWindowTitle("A Simple Text Editor")
        self.setWindowIcon(QIcon('iconos/prueba.png'))
        self.setGeometry(300, 250, 400, 300)

    def SetupComponents(self):
        """ Function to setup status bar, central widget, menu bar
        """
        self.myStatusBar = QStatusBar()
        self.setStatusBar(self.myStatusBar)
        self.myStatusBar.showMessage('Ready', 10000)
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()

        # Invoques toolbar creation and after that, reuses menu actions from
        # createActions() to create toolbar bottons.
        self.CreateToolBar()
        self.mainToolBar.addAction(self.newAction)
        self.mainToolBar.addSeparator()
        self.mainToolBar.addAction(self.copyAction)
        self.mainToolBar.addAction(self.pasteAction)

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)
        self.editMenu.addAction(self.copyAction)
        self.fileMenu.addSeparator()
        self.editMenu.addAction(self.pasteAction)
        self.helpMenu.addAction(self.aboutAction)

    # Slots called when the menu actions are triggered
    def newFile(self):
        self.textEdit.setText('')

    def exitFile(self):
        self.close()

    def aboutHelp(self):
        QMessageBox.about(self, "About Simple Text Editor",
                          "This example demonstrates the use " "of Menu Bar")

    def createActions(self):
        """ Function to create actions for menus
        """

        self.newAction = QAction(QIcon('iconos/new.png'), '&New', self,
                                 shortcut=QKeySequence.New,
                                 statusTip="Create a New File",
                                 triggered=self.newFile)
        self.exitAction = QAction(QIcon('iconos/exit.png'), 'E&xit', self,
                                  shortcut="Ctrl+Q",
                                  statusTip="Exit the Application",
                                  triggered=self.exitFile)
        self.copyAction = QAction(QIcon('iconos/copy.png'), 'C&opy', self,
                                  shortcut="Ctrl+C", statusTip="Copy",
                                  triggered=self.textEdit.copy)
        self.pasteAction = QAction(QIcon('iconos/paste.png'), '&Paste', self,
                                   shortcut="Ctrl+V", statusTip="Paste",
                                   triggered=self.textEdit.paste)
        self.aboutAction = QAction(QIcon('iconos/about.png'), 'A&bout', self,
                                   statusTip="Displays info about text editor",
                                   triggered=self.aboutHelp)

    # Actual menu bar item creation
    def createMenus(self):
        """ Function to create actual menu bar
        """
        # self.menubar() invoca una funcion nativa de la clase padre
        # QMainWindow la cual crea una barra de menu nativa al sistema de
        # ventanas en el que se ejecuta el programa, recordar el problema de
        # no buscar los menus en la barra de menus de Unity, donde estaban
        # "escondidos". El primer llamado a la funcion crea la barra y las
        # multiples invocaciones subsiguientes añaden los nuevos menus

        self.fileMenu = self.menuBar().addMenu("&File")
        self.editMenu = self.menuBar().addMenu("&Edit")
        self.helpMenu = self.menuBar().addMenu("&Help")

    def CreateToolBar(self):
        """ Function to create tool bar
        """
        self.mainToolBar = self.addToolBar('Main')
Beispiel #31
0
class EditConfigurationDialog(QWidget):
    def __init__(self, log, parent=None):
        super(EditConfigurationDialog, self).__init__(parent)
        layout = QVBoxLayout()
        self._log = log
        self.text_edit_widget = QTextEdit()
        layout.addWidget(self.text_edit_widget)

        buttons = QDialogButtonBox()
        # buttons.addButton( QDialogButtonBox.StandardButton.Cancel)
        buttons.addButton(QDialogButtonBox.StandardButton.Save)
        layout.addWidget(buttons)

        buttons.button(QDialogButtonBox.StandardButton.Save).clicked.connect(
            self._save)

        self.setLayout(layout)

    def _save(self):

        try:
            old_server_ip = configuration.get("DEFAULT", "public_ip")

            cfg_path = os.path.join(get_data_dir(), "server.cfg")
            f = open(cfg_path, "w")
            f.write(self.text_edit_widget.toPlainText())
            f.close()
            self._log._log_success(
                "Server configuration saved in {}".format(cfg_path))

            load_configuration(cfg_path, "server_config_check.cfg")
            self._log._log_success("Server configuration reloaded")

            server_ip = configuration.get("DEFAULT", "public_ip")
            if old_server_ip != server_ip:
                self._log._log_success(
                    "Updating IP address in the downloadable delivery_slips")
                inject_public_ip_in_client(server_ip)

        except Exception as ex:
            self._log._log_error(
                "Something went wrong while saving the configuration : {}".
                format(ex))

        self._log._log("Reloading server configuration")
        import threading

        def open_server(url):
            try:
                urlopen(url)
            except ConnectionResetError as ex:
                pass

        threading.Thread(target=open_server,
                         args=['http://127.0.0.1:8079/reload']).start()

    def load_configuration(self):
        cfg_path = os.path.join(get_data_dir(), "server.cfg")

        # try:
        f = open(cfg_path, "r")
        t = f.read()
        f.close()
        self.text_edit_widget.setText(t)
Beispiel #32
0
class CCParsedTab(QWidget):
    def __init__(self, parser_result):
        QWidget.__init__(self)
        self._parser_result = parser_result

        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSizeConstraint(QHBoxLayout.SetMinimumSize)

        self.table_widget = QTableWidget()
        self.table_widget.setSelectionMode(QAbstractItemView.NoSelection)
        self.table_widget.setRowCount(2)
        self.table_widget.setColumnCount(2)
        self.table_widget.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.table_widget.setHorizontalHeaderLabels(["Dimension", "Choice"])
        self.table_widget.verticalHeader().setVisible(False)
        self.table_widget.verticalHeader().setResizeMode(QHeaderView.Fixed)
        self.table_widget.verticalHeader().setDefaultSectionSize(20)
        sp_table = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sp_table.setHorizontalStretch(1)
        self.table_widget.setSizePolicy(sp_table)

        layout.addWidget(self.table_widget)

        self.text_widget = QTextEdit()
        sp_text = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sp_text.setHorizontalStretch(4)
        self.text_widget.setReadOnly(True)
        self.text_widget.setSizePolicy(sp_text)
        self.text_widget.setStyleSheet('font: 9pt "Courier";')
        self.text_widget.setText(self._parser_result.get_text())

        layout.addWidget(self.text_widget)

        self.setLayout(layout)

        self._fill_table()

    def _fill_table(self):
        colors = ["yellow", "orange", "green", "red"]

        dimensions = self._parser_result.get_dimensions()
        row = 0
        for dimension in dimensions:
            dimension_name = QLabel(dimension[0])
            dimension_name.setStyleSheet("background: %s" % colors[row % len(colors)])
            self.table_widget.setCellWidget(row, 0, dimension_name)
            choices_widget = QComboBox()
            choices = dimension[1]
            choices.insert(0, "No choice")
            choices_widget.addItems(choices)
            choices_widget.setStyleSheet("background: white")
            choices_widget.setStyleSheet("border: none")
            choices_widget.currentIndexChanged.connect(self.on_choice_change)
            self.table_widget.setCellWidget(row, 1, choices_widget)
            row += 1

    @Slot()
    def on_choice_change(self):
        text = self._parser_result.get_text()
        for row in range(self.table_widget.rowCount()):
            label = self.table_widget.cellWidget(row, 0)
            choices = self.table_widget.cellWidget(row, 1)
            if choices.currentIndex() == 0:
                continue
            regex = self._build_regex(label.text(), choices.count() - 1)
            pattern = re.compile(regex)
            matches = pattern.search(text)
            for match in matches.groups():
                results = re.search("<(.+)>", match)
                variants = [s.strip() for s in results.groups()[0].split(",")]
                text = text.replace(match, variants[choices.currentIndex() - 1])
        self.text_widget.setText(text)

    @staticmethod
    def _build_regex(dim, count):
        regex = "(" + dim + "<"
        for i in range(count):
            regex += ".+,[ ]?"
        regex = regex[:-5]
        regex += ">)"
        return regex
Beispiel #33
0
class MainWindow(QMainWindow):
	"""docstring for MainWindow"""
	def __init__(self):
		super(MainWindow,self).__init__()
		self.initGui()

	def initGui(self):
		self.setWindowTitle('Aeneid Text Editor')
		self.setWindowIcon(QIcon())
		self.setGeometry(300,300, 400,300)
		self.setupComponents()
		self.show()

	def setupComponents(self):
		""" Function to setup status bar, central widget
			and menu bar
		"""
		self.myStatusBar = QStatusBar()
		self.setStatusBar(self.myStatusBar)
		self.myStatusBar.showMessage('Ready', 10000)
		self.textEdit=QTextEdit()
		self.setCentralWidget(self.textEdit)

		# 
		self.createActions()
		self.createMenus()

		#
		self.fileMenu.addAction(self.newAction)
		self.fileMenu.addSeparator()
		self.fileMenu.addAction(self.exitAction)
		self.fileMenu.addSeparator()
		self.editMenu.addAction(self.copyAction)
		self.editMenu.addSeparator()
		self.editMenu.addAction(self.pasteAction)
		self.helpMenu.addAction(self.aboutAction)

	# slots called when the menu actions are triggered
	def newFile(self):
		self.textEdit.setText('Aeneid Applicatioon')

	def exitFile(self):
		self.close()

	def aboutHelp(self):
		QMessageBox.about( self, 
						   "About Simple Text Editor", 
						   "Demonstrate use of menu bar")

	def createActions(self):
		""" Function to create actions for menus
		"""
		self.newAction=QAction( QIcon(), '&New', 
								self, 
								shortcut=QKeySequence.New, 
								statusTip="Create a New file" )
		self.exitAction=QAction( QIcon(), '&Exit',
								 self,
								 shortcut="Ctrl+Q",
								 statusTip="Exit the application",
								 triggered=self.exitFile )
		self.copyAction=QAction( QIcon(), '&Copy',
								 self,
								 shortcut="Ctrl+C",
								 statusTip="Copy",
								 triggered=self.textEdit.copy )
		self.pasteAction=QAction( QIcon(), '&Paste',
								  self,
								  shortcut="Ctrl+V",
								  triggered=self.textEdit.paste)
		self.aboutAction=QAction( QIcon(), '&About',
								  self,
								  statusTip="Displays info",
								  triggered=self.aboutHelp )

	# Actual menu bar item creation
	def createMenus(self):
		""" Function to create actual menu bar
		"""
		self.fileMenu = self.menuBar().addMenu("&File")
		self.editMenu = self.menuBar().addMenu("&Edit")
		self.helpMenu = self.menuBar().addMenu("&Help")