Esempio n. 1
0
class CategoriesScreen(QWidget):

    '''
    Class: CategoriesScreen
    Purpose: Contains the category buttons
    '''

    def __init__(self, categories, parent):
        super(CategoriesScreen, self).__init__(parent=parent)

        self.setGeometry(0,0,700,100)
        layout = QHBoxLayout()
        layout.setSpacing(0)

        self.buttons = QButtonGroup()
        self.buttons.setExclusive(True)
        for cat in categories:
            button = QPushButton(cat)
            button.setFixedSize(700*1.0/len(categories), 100)
            self.buttons.addButton(button)
            button.setCheckable(True)
            layout.addWidget(button)

        self.buttons.buttonClicked.connect(parent.display_chores)

        self.setLayout(layout)
        button.setChecked(True)
        self.curr_active = button
Esempio n. 2
0
class NoteTypeSelectPanel(QWidget
                          ):  # need to change h size policy to not stretch
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        layout = QHBoxLayout()
        self.setLayout(layout)
        layout.setSpacing(0)

        noteDirNames = ['mine', 'red', 'blue']
        self.btnSize = QSize(40, 40)

        self.buttons = {}
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(True)
        for name in noteDirNames:
            if name == '':
                continue
            self.buttons[name] = QPushButton()
            btnIcon = QIcon()
            btnIcon.addPixmap(QPixmap(graphics_dir + name + ".png"),
                              QIcon.Normal, QIcon.Off)
            self.buttons[name].setIconSize(QSize(32, 32))
            self.buttons[name].setFixedSize(self.btnSize)
            self.buttons[name].setCheckable(True)
            self.buttons[name].setIcon(btnIcon)
            self.buttons[name].setText("")
            self.buttonGroup.addButton(self.buttons[name])
            layout.addWidget(self.buttons[name])
Esempio n. 3
0
def loadbutton():
    tbl = dbsearchui.datatable
    tbl.setRowCount(1)
    tbl.setColumnCount(11)
    bval = [
        'stock code ^', 'current price ^', 'abs change ^', 'per change ^',
        'open price ^', 'high price ^', 'low price ^', 'prev close ^',
        'company ^', 'market capital ^', 'pe ratio ^'
    ]
    btn_grp = QButtonGroup()
    btn_grp.setExclusive(True)
    for i in range(0, 11):
        btn = QPushButton()
        btn.setText(bval[i])
        btn.setCheckable(True)
        btn.setChecked(False)
        btn.setStyleSheet('''
        background-color:rgb(28,130,255);
        font-variant:small-caps;
        font-size:18px;
        ''')

        btn.clicked.connect(lambda: getcommand(btn_grp))
        tbl.setCellWidget(0, i, btn)
        btn_grp.addButton(btn)
    return btn_grp
Esempio n. 4
0
class SignChoiceDialog(QDialog):
    def __init__(self, sign_list):
        super().__init__()

        self.result_idx = -1
        self.label = QLabel("Choose the sign:")

        layout = QGridLayout()
        layout.addWidget(self.label, 0, 0)

        self.btn_grp = QButtonGroup()
        self.btn_grp.setExclusive(True)

        for idx, sign_info in enumerate(sign_list):
            btn = SignSelectButton(sign_info[0], idx, self)
            btn.setIcon(QIcon(sign_info[1]))
            btn.setIconSize(QSize(24, 24))
            layout.addWidget(btn, idx + 1, 0)

            self.btn_grp.addButton(btn)
            self.btn_grp.setId(btn, idx)

        self.btn_grp.buttonClicked.connect(self.on_click)

        self.setLayout(layout)
        self.show()

    def on_click(self, btn):
        self.result_idx = btn.idx
        self.close()

    def get_result(self):
        # -1 - no selection
        return self.result_idx
Esempio n. 5
0
    def __init__(self, filelist):
        super().__init__()
        self.filelist = filelist
        self.setWindowTitle('Global search')

        self.main_widget = QWidget()
        self.layout = QGridLayout()

        search_button = QPushButton('Search')
        search_button.clicked.connect(self.search)
        self.search_input = QLineEdit()
        self.search_input.returnPressed.connect(search_button.click)

        button_group = QButtonGroup(self)
        button_group.setExclusive(True)
        check_1 = QCheckBox('File name')
        check_1.setChecked(True)
        button_group.addButton(check_1)

        self.layout.addWidget(self.search_input, 0, 0)
        self.layout.addWidget(search_button, 0, 1)
        self.layout.addWidget(check_1, 1, 0)

        self.main_widget.setLayout(self.layout)
        self.setWidget(self.main_widget)
Esempio n. 6
0
    def createBottomView(self):
        rememberPsdBtn = QRadioButton()
        rememberPsdBtn.setText('记住密码')
        rememberPsdBtn.hide()

        autoLoginBtn = QRadioButton()
        autoLoginBtn.setText('自动登录')
        autoLoginBtn.hide()

        gourp = QButtonGroup(rememberPsdBtn)
        gourp.addButton(rememberPsdBtn)
        gourp.addButton(autoLoginBtn)
        gourp.setExclusive(False)

        forgetPsdBtn = QPushButton()
        forgetPsdBtn.setText('忘记密码')
        forgetPsdBtn.clicked.connect(lambda: self.btnAction(forgetPsdBtn))
        forgetPsdBtn.hide()

        registeredBtn = QPushButton()
        registeredBtn.setText('注册账号')
        registeredBtn.hide()
        self.bottomLayout.addWidget(rememberPsdBtn, 1, 1)
        self.bottomLayout.addWidget(forgetPsdBtn, 1, 2)
        self.bottomLayout.addWidget(autoLoginBtn, 2, 1)
        self.bottomLayout.addWidget(registeredBtn, 2, 2)
Esempio n. 7
0
    def _createSecondScreen(self):
        vLayout = QVBoxLayout(self.centralWidget())
        vLayout.setAlignment(Qt.AlignTop)
        vLayout.addWidget(QLabel())
        hLayout = QHBoxLayout()
        hLayout.setSpacing(0)
        hLayout.setAlignment(Qt.AlignHCenter)
        formLayout = QFormLayout(self.centralWidget())
        formLayout.setFormAlignment(Qt.AlignHCenter)
        formLayout.setLabelAlignment(Qt.AlignRight)

        btnGroup = QButtonGroup()
        btnGroup.setExclusive(True)
        title = QLabel()
        tPng = QPixmap("./graphics/ManageCraft.png")
        title.setPixmap(tPng)
        btn1 = QPushButton()
        btn1.setFixedSize(130, 40)
        btn1.setCheckable(True)
        btn1.setChecked(False)
        rcPng = QIcon("./graphics/RemoteBtn.png")
        btn1.setIcon(rcPng)
        btn1.setIconSize(QSize(170, 40))
        btn2 = QPushButton()
        btn2.setFixedSize(130, 40)
        btn2.setCheckable(True)
        btn2.setChecked(True)
        lcPng = QIcon("./graphics/LocalBtnChecked.png")
        btn2.setIcon(lcPng)
        btn2.setIconSize(QSize(170, 40))
        btn3 = QPushButton()
        btn3.setFixedSize(130, 40)
        bPng = QIcon("./graphics/BrowseBtn.png")
        btn3.setIcon(bPng)
        btn3.setIconSize(QSize(200, 40))
        btn1.toggled.connect(self.remote)
        btnGroup.addButton(btn1)
        btn2.toggled.connect(self.local)
        btnGroup.addButton(btn2)
        btn3.clicked.connect(self.browseL)
        btn1.pressed.connect(
            partial(self.btnPressToggle, btn1, "RemoteBtnChecked.png"))
        btn1.released.connect(
            partial(self.btnPressToggle, btn1, "RemoteBtn.png"))
        btn3.pressed.connect(
            partial(self.btnPressToggle, btn3, "BrowseBtnChecked.png"))
        btn3.released.connect(
            partial(self.btnPressToggle, btn3, "BrowseBtn.png"))

        vLayout.addWidget(title, alignment=Qt.AlignCenter)
        hLayout.addWidget(btn1, alignment=Qt.AlignHCenter)
        hLayout.addWidget(btn2, alignment=Qt.AlignHCenter)
        vLayout.addLayout(hLayout)
        vLayout.addWidget(self.path, alignment=Qt.AlignHCenter)
        vLayout.addWidget(btn3, alignment=Qt.AlignCenter)

        self.frameL.setLayout(vLayout)
        self.mainMenu = False
        self.frameL.hide()
    def __init__(self, parent):
        # ,data was removed from __init__()
        super().__init__()  #Removed "parent" from super().__init__()

        #Define Radio buttons
        self.radioMale = QRadioButton("male")
        self.radioFemale = QRadioButton("female")
        self.radioOther = QRadioButton("other")

        #Group needed so only one radio option can be selected at once
        genderButtons = QButtonGroup()
        genderButtons.setExclusive(True)
        genderButtons.addButton(self.radioMale)
        genderButtons.addButton(self.radioFemale)
        genderButtons.addButton(self.radioOther)

        self.radioMale.setChecked(
            True)  #In case they don't select an option during 'Add'

        #Layout for Radio buttons
        radioButtons = QGridLayout()
        radioButtons.addWidget(self.radioMale, 0, 0)
        radioButtons.addWidget(self.radioFemale, 0, 1)
        radioButtons.addWidget(self.radioOther, 0, 2)

        #Widgets to be used for the Dialog box layout
        self.patientName = QLineEdit()
        self.birthYear = QSpinBox()
        self.birthYear.setRange(1900, 2017)
        self.symptoms = QLineEdit()

        #Define Ok and Cancel buttons and which functions they call
        okButton = QDialogButtonBox(QDialogButtonBox.Ok)
        cancelButton = QDialogButtonBox(QDialogButtonBox.Cancel)
        okButton.accepted.connect(self.accept)
        cancelButton.rejected.connect(self.reject)

        #Layout for the OK and Cancel buttons (horizontal)
        dialogButtons = QHBoxLayout()
        dialogButtons.addWidget(okButton)
        dialogButtons.addWidget(cancelButton)

        #Dialog box information input layout
        info_layout = QFormLayout()
        info_layout.addRow(QLabel("Name"), self.patientName)
        info_layout.addRow(QLabel("Year"), self.birthYear)
        info_layout.addRow(QLabel("Gender"), radioButtons)
        info_layout.addRow(QLabel("Symptoms"), self.symptoms)

        #Compiled layout for the Dialog box
        self.dialogInfoLayout = QVBoxLayout()
        self.dialogInfoLayout.addLayout(info_layout)
        self.dialogInfoLayout.addLayout(dialogButtons)
        self.setLayout(self.dialogInfoLayout)

        #Title and window location/dimensions
        self.setGeometry(100, 100, 250, 200)
        self.setWindowTitle('Subject Information')
        self.show()  #Activates window
Esempio n. 9
0
class TopicsPopup(QWidget):
    """This class will show a popup window to select topics to be recorded in a rosbag

    Attributes:
        active_topics {list} -- List of topcis to be recorded"""
    def __init__(self):
        """Construtctor of the class"""
        QWidget.__init__(self)
        self.setFixedSize(800, 600)
        self.setWindowTitle("Select your topics")
        self.active_topics = []
        self.hide()
        self.initUI()

    def initUI(self):
        """Initialize GUI elements"""
        self.setStyleSheet('background-color: rgb(51, 51, 51); color: white;')

        self.main_layout = QVBoxLayout()
        self.setLayout(self.main_layout)
        self.button_group = QButtonGroup()
        self.button_group.buttonClicked.connect(self.add_topic)
        self.button_group.setExclusive(False)

        scroll = QScrollArea(self)
        self.main_layout.addWidget(scroll)
        scroll.setWidgetResizable(True)
        scroll_content = QWidget(scroll)

        self.scroll_layout = QVBoxLayout(scroll_content)
        scroll_content.setLayout(self.scroll_layout)
        scroll.setWidget(scroll_content)

    def fill_topics(self):
        """Fill the active_topics with all the topics selected by the user"""
        topics = rospy.get_published_topics()
        for idx, topic in enumerate(topics):
            cont = QFrame()
            ll = QHBoxLayout()
            cont.setLayout(ll)
            topic_check = QCheckBox(str(topic[0]))
            self.button_group.addButton(topic_check)
            ll.addWidget(topic_check)
            self.scroll_layout.addWidget(cont)
            if idx % 2 == 0:
                cont.setStyleSheet('background-color: rgb(51,51,51)')
            else:
                cont.setStyleSheet('background-color: rgb(71, 71, 71)')

    def show_updated(self):
        """Update the window"""
        self.show()
        self.fill_topics()
        self.active_topics = []

    def add_topic(self, btn):
        """Callback that adds topic to the active_topics list"""
        self.active_topics.append(btn.text())
Esempio n. 10
0
class LocalButtonsConf(OptionsDialogGroupBox):
    def __init__(self, name, main):
        self.main = main
        OptionsDialogGroupBox.__init__(self, name, main)
        self.buttonBox = QGroupBox("Pins")
        self.buttonBoxLayout = QVBoxLayout()
        self.buttonBox.setLayout(self.buttonBoxLayout)

    def initUI(self):
        vbox = QVBoxLayout()
        self.polBox = QCheckBox("Invert")
        vbox.addWidget(self.polBox)
        self.buttongroup = QButtonGroup()
        self.buttongroup.setExclusive(False)
        vbox.addWidget(self.buttonBox)

        self.setLayout(vbox)

    def initButtons(self, num):
        #delete buttons
        self.num = num

        # Remove buttons
        for i in range(self.buttonBoxLayout.count()):
            b = self.buttonBoxLayout.takeAt(0)
            self.buttonBoxLayout.removeItem(b)
            b.widget().deleteLater()
        for b in self.buttongroup.buttons():
            self.buttongroup.removeButton(b)

        self.buttonBox.update()

        for i in range(self.num):
            cb = QCheckBox(str(i + 1))
            self.buttongroup.addButton(cb, i)
            self.buttonBoxLayout.addWidget(cb)

        def localcb(mask):
            for i in range(self.num):
                self.buttongroup.button(i).setChecked(mask & (1 << i))

        self.main.comms.serialGetAsync("local_btnmask?", localcb, int)

    def apply(self):
        mask = 0
        for i in range(self.num):
            if (self.buttongroup.button(i).isChecked()):
                mask |= 1 << i
        self.main.comms.serialWrite("local_btnmask=" + str(mask))
        self.main.comms.serialWrite("local_btnpol=" +
                                    ("1" if self.polBox.isChecked() else "0"))

    def readValues(self):
        self.main.comms.serialGetAsync("local_btnpins?", self.initButtons, int)

        self.main.comms.serialGetAsync("local_btnpol?", self.polBox.setChecked,
                                       int)
Esempio n. 11
0
class ButtonListWidget(QGroupBox):
    selectionChanged = pyqtSignal(object)

    def __init__(self, name, parent=None):
        QGroupBox.__init__(self, name, parent)
        self.setLayout(FloatingLayout())

        self.name = name
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(False)
        self.buttons = {}

    def create_button(self, button_name):
        button = QPushButton(button_name)
        button.setFlat(True)
        button.setCheckable(True)
        button.clicked.connect(self.clickedButton)
        return button

    def add_button(self, button_name):
        button = self.create_button(button_name)
        self.buttons[button_name] = button
        self.layout().addWidget(button)
        self.button_group.addButton(button)
        return button

    def get_button(self, button_name):
        return self.buttons[button_name]

    def toggleChecked(self, button_name, apply=True):
        selection = None

        for button in self.button_group.buttons():
            if button.text() != button_name:
                button.setChecked(False)
            else:
                if apply:
                    button.setChecked(not button.isChecked())
                if button.isChecked():
                    selection = button_name

        self.selectionChanged.emit(selection)

    def clickedButton(self):
        button_name = str(self.sender().text())
        self.toggleChecked(button_name, False)

        #for button in self.button_group.buttons():
        #if button is not self.sender():
        #button.setChecked(False)
        #print "sender:", label_name

    def get_checked_button(self):
        return self.button_group.checkedButton()
Esempio n. 12
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     # ---- UI ----
     self.setSpacing(80)
     # ---- Content ----
     bttngroup = QButtonGroup(self)
     bttngroup.setExclusive(True)
     self.bttns = []
     for lang in self.LANGUAGES:
         lang_bttn = PreferenceButton(lang, f"language_{lang}")
         bttngroup.addButton(lang_bttn)
         self.bttns.append(lang_bttn)
         self.addWidget(lang_bttn)
Esempio n. 13
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     # ---- UI ----
     self.setSpacing(80)
     # ---- Content ----
     bttngroup = QButtonGroup(self)
     bttngroup.setExclusive(True)
     self.bttns = []
     for cur in self.CURRENCIES:
         curr_bttn = PreferenceButton(cur, f"currency_{cur}")
         bttngroup.addButton(curr_bttn)
         self.bttns.append(curr_bttn)
         self.addWidget(curr_bttn)
Esempio n. 14
0
class WelcomeScreen(Login.Ui_MainWindow):
    """ Launches the Welcome Screen that prompts the user to declare whether they are a regular user 
        or an administrator.
    """

    _welcomescreen = None
    _root = None

    def __init__(self, MainWindow: QtWidgets.QMainWindow) -> None:
        if WelcomeScreen._welcomescreen is None:
            self.screen = MainWindow
            self.setupUi(self.screen)
            self._buttonGroup = QButtonGroup()
            self._buttonGroup.setExclusive(True)
            self._buttonGroup.addButton(self.adminButton)
            self._buttonGroup.addButton(self.userButton)
            self._buttonGroup.buttonClicked.connect(self._showLogin)
            WelcomeScreen._welcomescreen = self

        else:
            raise Exception("Unable to create another instance.")

    @classmethod
    def getWelcomeScreen(cls, MainWindow: QtWidgets.QMainWindow):
        """Returns the welcome screen.
           :param MainWindow (QMainWindow): A mainwindow.

        """

        if not cls._welcomescreen:
            cls(MainWindow)

        return cls._welcomescreen

    def _showLogin(self, clickedButton: QtWidgets.QPushButton) -> None:
        """Shows the login screen.
           :param clickedButton (QPushButton): Either the User or Administrator button clicked.
        
        """

        if clickedButton == self.adminButton:
            WelcomeScreen._welcomescreen.screen.destroy()
            MainWindow = QtWidgets.QMainWindow()
            self._login = SignInScreen.getSignInScreen(MainWindow,
                                                       "Administrator")
            self._login.screen.show()
        else:
            WelcomeScreen._welcomescreen.screen.destroy()
            MainWindow = QtWidgets.QMainWindow()
            self._login = SignInScreen.getSignInScreen(MainWindow, "User")
            self._login.screen.show()
Esempio n. 15
0
File: gui.py Progetto: TheBB/ct
    def __init__(self, main):
        super(DisciplineChoiceWidget, self).__init__()
        self.main = main
        self.blind = False
        self.one_handed = False
        self.feet = False
        self.setMaximumWidth(70)
        self.setLayout(QVBoxLayout())

        group = QButtonGroup(self)
        group.setExclusive(True)

        ICON_PATH = join(dirname(abspath(__file__)), 'data')
        for pid, p in puzzles.items():
            btn = QPushButton()
            pixmap = QPixmap(join(ICON_PATH, pid) + '.png')
            btn.setIcon(QIcon(pixmap))
            btn.setIconSize(pixmap.rect().size())
            btn.setCheckable(True)
            if 'default' in p and p['default']:
                btn.setChecked(True)
                self.puzzle = pid
            btn.pressed.connect(lambda q=pid: self.set_puzzle(q))
            group.addButton(btn)
            self.layout().addWidget(btn)

        frame = QFrame()
        frame.setFrameShape(QFrame.HLine)
        frame.setFrameShadow(QFrame.Sunken)
        self.layout().addWidget(frame)

        btn = QPushButton('BLD')
        btn.setCheckable(True)
        btn.pressed.connect(self.set_bld)
        self.layout().addWidget(btn)

        btn = QPushButton('OH')
        btn.setCheckable(True)
        btn.pressed.connect(self.set_one_handed)
        self.layout().addWidget(btn)

        btn = QPushButton('FEET')
        btn.setCheckable(True)
        btn.pressed.connect(self.set_feet)
        self.layout().addWidget(btn)

        self.layout().addStretch()

        timing.state_changed.register(self.state_changed)
Esempio n. 16
0
    def initUI(self):

        # create menus
        menu.GuiMenu()
        menu.WidgetMenu()
        menu.SettingsMenu()
        menu.LoggingMenu()

        # main layout
        mainVLayout = QVBoxLayout()
        elementHLayouts = []

        # top element: toolbar, status
        t = QLabel("Toolbar")
        s = QLabel("Status")
        toolbarStatusHLayout = QHBoxLayout()
        toolbarStatusHLayout.addWidget(t)
        toolbarStatusHLayout.addWidget(s)
        elementHLayouts.append(toolbarStatusHLayout)

        # mid element: menu buttons
        menubuttonsHLayout = QHBoxLayout()
        stackedButtonsWidget = QStackedWidget()
        buttonGroup = QButtonGroup(self)
        buttonGroup.setExclusive(True)

        for m in menu.Menu.menus:
            btn = QPushButton(m.name)
            btn.setCheckable(True)
            btn.pressed.connect(lambda m=m: stackedButtonsWidget.setCurrentWidget(m))
            menubuttonsHLayout.addWidget(btn)
            buttonGroup.addButton(btn)
            stackedButtonsWidget.addWidget(m)

        elementHLayouts.append(menubuttonsHLayout)

        # bot element: menu specific widgets
        menuwidgetsHLayout = QHBoxLayout()
        menuwidgetsHLayout.addWidget(stackedButtonsWidget)
        elementHLayouts.append(menuwidgetsHLayout)

        # click first button for defined initial state
        if len(buttonGroup.buttons()) > 0:
            buttonGroup.buttons()[0].click()

        for l in elementHLayouts:
            mainVLayout.addLayout(l)

        self.setLayout(mainVLayout)
Esempio n. 17
0
class MyPopup(QDialog, Ui_dialog):
    def __init__(self, parent=None, dobot=None):
        super(MyPopup, self).__init__(parent)
        self.setupUi(self)
        self.btn_grp = QButtonGroup(self)
        self.btn_grp.setExclusive(True)

        #self.btn_detect.clicked.connect(dobot.single_detect)
        #self.btn_always_detect.clicked.connect(dobot.always_detect)

        self.btn_grp.buttonClicked[int].connect(dobot.get_items)
        self.objArr = []
        self.show()

    def add_obj(self, name, objList):
        """_translate = QtCore.QCoreApplication.translate
Esempio n. 18
0
class IngresarPaciente(QDialog):
    def __init__(self):
        super(IngresarPaciente, self).__init__()
        loadUi('ingresar_p.ui', self)
        self.ingresar_pa.clicked.connect(self.on_clicked)
        self.cedula.setValidator(QtGui.QDoubleValidator())
        self.edad.setValidator(QtGui.QDoubleValidator())
        self.grupo1 = QButtonGroup()
        self.grupo1.addButton(self.femenino)
        self.grupo1.addButton(self.masculino)

    def generoP(self):
        if self.masculino.isChecked():
            genero = 1
        elif self.femenino.isChecked():
            genero = 2
        else:
            genero = None
        return genero

    def on_clicked(self):
        nombre = self.nombre_paciente.text()
        cedula = self.cedula.text()
        edad = self.edad.text()
        genero = self.generoP()
        dalt = 'Falta por ingresar'
        correo = self.correo.text()
        if cedula == '' or genero == None:  #Ciclo para comprobar que se ingresen los datos obligatorios, aun no funciona no se porque, sin el guarda el paciente
            QMessageBox.about(
                self, 'AVISO',
                'Faltaron seleccionar datos obligatorios, intentelo nuevamente.'
            )
        else:
            paciente = Paciente(nombre, cedula, edad, genero, dalt, correo)
            if medico.agregarPaciente(paciente):
                self.grupo1.setExclusive(False)
                self.femenino.setChecked(False)
                self.masculino.setChecked(False)
                self.grupo1.setExclusive(True)
                QMessageBox.about(self, 'Aviso',
                                  'El paciente fue agregado con exito')
            else:
                QMessageBox.about(self, 'Aviso', 'El paciente ya existe')
        self.nombre_paciente.setText('')
        self.cedula.setText('')
        self.edad.setText('')
Esempio n. 19
0
class ImportTypeWidget(QtWidgets.QWidget):

    def __init__(self, session, parent=None):
        """
        Initialize the base information box.
        :type session: Session
        :type parent: QtWidgets.QWidget
        """
        super().__init__(parent)
        self.session = session

        self.fileSystemRadioButton = QRadioButton('Import an ontology from a local document',self)
        self.fileSystemRadioButton.setChecked(True)
        self.checkedId = 0
        self.webRadioButton = QRadioButton('Import an ontology from a document on the web',self)

        self.buttonGroup = QButtonGroup(self)
        self.buttonGroup.addButton(self.fileSystemRadioButton,id=0)
        self.buttonGroup.addButton(self.webRadioButton, id=1)
        self.buttonGroup.setExclusive(True)
        connect(self.buttonGroup.buttonClicked, self.onButtonClicked)

        formlayout = QtWidgets.QFormLayout()
        formlayout.addRow(self.fileSystemRadioButton)
        formlayout.addRow(self.webRadioButton)

        groupbox = QtWidgets.QGroupBox('Import type', self)
        groupbox.setLayout(formlayout)
        outerFormLayout = QtWidgets.QFormLayout()
        outerFormLayout.addRow(groupbox)
        self.setLayout(outerFormLayout)


    #############################################
    #   SLOTS
    #################################
    @QtCore.pyqtSlot(QAbstractButton)
    def onButtonClicked(self, button):
        """
        Executed when a radio button is clicked
        """
        self.checkedId = self.buttonGroup.checkedId()

    def getSelectedRadioId(self):
        return self.buttonGroup.checkedId()
Esempio n. 20
0
    def display_patient_data(self, patient_identifier, data):
        tab = QWidget()
        tab_layout = QHBoxLayout()
        vbox1 = QVBoxLayout()
        vbox2 = QVBoxLayout()
        self.patient_data_UIs[patient_identifier] = [vbox1, vbox2]
        small_hbox = QHBoxLayout()
        title_box = QVBoxLayout()

        # Patient Label
        patient_identifier_label = self.create_title(
            f'Patient: {patient_identifier}', Qt.AlignCenter)
        title_box.addWidget(patient_identifier_label, 0, Qt.AlignLeft)

        small_hbox.addLayout(title_box)
        vbox1.addLayout(small_hbox)

        # Overall Summary Table
        vbox1.addWidget(self.create_label("Global", Qt.AlignCenter))
        summary_table = QTableView()
        summary_table.setSelectionMode(QAbstractItemView.ExtendedSelection)
        summary_table.installEventFilter(self)
        vbox1.addWidget(summary_table)

        # Regions Summary Table
        vbox1.addWidget(self.create_label("Selected Regions", Qt.AlignCenter))
        regions_summary_table = QTableView()
        regions_summary_table.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        regions_summary_table.installEventFilter(self)
        vbox1.addWidget(regions_summary_table)

        # Regions Selection
        region_select_buttons = QButtonGroup()
        region_select_buttons.setExclusive(False)

        vbox2.addStretch(1)
        self.create_region_selection(vbox2, region_select_buttons,
                                     regions_summary_table, patient_identifier)
        self.load_table_view(data, summary_table)
        tab_layout.addLayout(vbox1)
        tab_layout.addLayout(vbox2)
        tab.setLayout(tab_layout)
        self.tabs.addTab(tab, patient_identifier)
Esempio n. 21
0
	def _createNavBar(self):
		navbar = QFrame()
		navbar.setFixedWidth(200)
		navbar.setSizePolicy(QSizePolicy(0, 1))
		navbar.setLayout(QVBoxLayout())
		navbar.layout().setContentsMargins(0, 0, 0, 0)
		navbar.layout().setAlignment(Qt.AlignTop)
		navbar.setObjectName("navbar")
		navbar.layout().setSpacing(0)

		logo = self._createNavButton("Finanças", "icon_app.png")
		logo.setObjectName("logo")
		logo.setFixedHeight(50)
		navbar.layout().addWidget(logo)

		#Criando os Botoes da navbar
		#Botao Vendas
		self.sellsBtn = self._createNavButton("Vendas", "sales.png")
		self.sellsBtn.setChecked(True)

		#Botao Produto
		self.productBtn = self._createNavButton("Produtos", "products.png")
		
		#Botao Clients
		self.clientBtn = self._createNavButton("Clientes", "clientes.png")

		#Botao Categoria
		self.tagBtn = self._createNavButton("Categorias", "category.png")

		#GroupButton para criar uma exclusão entre os botoes
		#Para que não fique selecionado dois de uma vez
		group = QButtonGroup(self)
		group.setExclusive(True)
		group.addButton(self.sellsBtn)
		group.addButton(self.productBtn)
		group.addButton(self.clientBtn)
		group.addButton(self.tagBtn)

		#Adicionando os botoes à Layout da NavBar
		navbar.layout().addWidget(self.sellsBtn)
		navbar.layout().addWidget(self.productBtn)
		navbar.layout().addWidget(self.clientBtn)
		navbar.layout().addWidget(self.tagBtn)
		return navbar
Esempio n. 22
0
def radioButtonTest(p):
    btn1 = QRadioButton("男")
    btn1.setChecked(True)
    # btn1.setCheckable(False)
    btn1.toggled.connect(lambda: radioButtonHandler(btn1))
    btn1.setParent(p)
    btn1.setGeometry(10, 20, 80, 30)
    btn1.setShortcut("Alt+M")  # 设置快捷
    btn2 = QRadioButton("女")
    btn2.setParent(p)
    btn2.setGeometry(10, 60, 80, 30)
    btn2.setShortcut("Alt+F")  # 设置快捷
    # 创建分组
    zu1 = QButtonGroup(p)  # 创建一个按钮分组实例
    # 参数2 给按钮设置一个id,不同分组的id可以重复
    # 如果id为-1,则将为该按钮分配一个id。自动分配的ID保证为负数,从-2开始。
    zu1.addButton(btn1, 1)  # 给按钮分组实例添加按钮
    zu1.addButton(btn2, 2)  # 给按钮分组实例添加按钮
    zu1.setExclusive(False)  #是否独占
    zu1.buttonToggled[int, bool].connect(zuButtonToggledHandler)
Esempio n. 23
0
    def initModeModule(self):
        m_lbl = QLabel('Mode:', self)
        self.h_mode = QRadioButton('Horizon', self)
        self.h_mode.clicked.connect(self.modeRespond)
        self.o_mode = QRadioButton('Obstacle', self)
        self.o_mode.clicked.connect(self.modeRespond)

        self.h_mode.setChecked(True)

        m_btn_group = QButtonGroup(self)
        m_btn_group.addButton(self.h_mode)
        m_btn_group.addButton(self.o_mode)
        m_btn_group.setExclusive(True)

        self.mode_hbox = QHBoxLayout()
        self.mode_hbox.addWidget(m_lbl)
        self.mode_hbox.addStretch(1)
        self.mode_hbox.addWidget(self.h_mode)
        self.mode_hbox.addStretch(1)
        self.mode_hbox.addWidget(self.o_mode)
        self.mode_hbox.addStretch(1)
Esempio n. 24
0
class StackedPage(QWidget):
    def __init__(self, parent=None):
        super(StackedPage, self).__init__(parent)
        layout = QHBoxLayout(self)
        leftpane = QVBoxLayout()
        self.buttongroup = QButtonGroup(self)
        self.buttongroup.setExclusive(True)
        self.groupbox = QGroupBox(self)
        self.groupbox.setMinimumWidth(200)
        QVBoxLayout(self.groupbox)
        leftpane.addWidget(self.groupbox)
        leftpane.addStretch(1)
        layout.addLayout(leftpane)
        self.rightpane = QStackedWidget(self)
        layout.addWidget(self.rightpane)
        self.buttongroup.buttonClicked[int].connect(
            self.rightpane.setCurrentIndex)
        self.rightpane.currentChanged[int].connect(self.activate)

    def addPage(self, buttontext, widget):
        button = QPushButton(buttontext)
        button.setCheckable(True)
        button.setChecked(self.rightpane.count() == 0)
        self.buttongroup.addButton(button, self.rightpane.count())
        self.groupbox.layout().addWidget(button)
        self.rightpane.addWidget(widget)

    def pages(self):
        return [
            self.rightpane.widget(i) for i in range(self.rightpane.count())
        ]

    def activate(self, ix):
        page = self.rightpane.currentWidget()
        if hasattr(page, "activate") and callable(page.activate):
            page.activate()

    def showEvent(self, *args, **kwargs):
        self.activate(0)
        return QWidget.showEvent(self, *args, **kwargs)
Esempio n. 25
0
    def __init__(self, config):
        self.config = config

        super().__init__(None)

        # Setup UI
        self.setupUi(self)
        self.save_to.setText(self.config['download_path'])

        checkbox_group = QButtonGroup(self)
        checkbox_group.setExclusive(True)
        checkbox_group.addButton(self.normal)
        checkbox_group.addButton(self.split)
        checkbox_group.addButton(self.audio_only)

        # Setup subprocess
        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)

        self.process.started.connect(self.on_process_started)
        self.process.readyReadStandardOutput.connect(
            self.on_process_readyReadStandardOutput)
        self.process.finished.connect(self.on_process_finished)

        # Setup subprocess for getting stdout
        self.text_process = QProcess(self)
        self.text_process.setProcessChannelMode(QProcess.MergedChannels)

        # Setup program helper
        self.ytdl_helper = YTDLHelper(self.config['ytdl_path'],
                                      self.config['ffmpeg_path'], self.process,
                                      self.text_process)
        self.ffprobe_helper = FFProbeHelper(self.config['ffprobe_path'],
                                            self.text_process)
        self.ffmpeg_helper = FFMPEGHelper(self.config['ffmpeg_path'],
                                          self.process)

        # Object status keeper
        self.object_status = {}
Esempio n. 26
0
class NoteDirSelectPanel(QWidget
                         ):  # need to change h size policy to not stretch
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        layout = QGridLayout()
        layout.setSpacing(0)
        self.setLayout(layout)

        noteDirNames = [
            'downRight', 'down', 'downLeft', 'Right', 'circle', 'left',
            'upRight', 'up', 'upLeft'
        ]
        positions = [(i, j) for i in range(3) for j in range(3)]
        self.btnSize = QSize(40, 40)

        self.buttons = {}
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(True)
        for position, name in zip(positions, noteDirNames):
            if name == '':
                continue
            self.buttons[name] = QPushButton()
            btnIcon = QIcon()
            btnIcon.addPixmap(QPixmap(graphics_dir + name + ".png"),
                              QIcon.Normal, QIcon.Off)
            self.buttons[name].setIconSize(QSize(32, 32))
            self.buttons[name].setFixedSize(self.btnSize)
            self.buttons[name].setCheckable(True)
            self.buttons[name].setIcon(btnIcon)
            self.buttons[name].setText("")
            self.buttonGroup.addButton(self.buttons[name])
            layout.addWidget(self.buttons[name], *position)
Esempio n. 27
0
class MainWindow(QMainWindow):
    InsertTextButton = 10
    items = {-2: "source", -3: "channel", -4: "sink"}

    def __init__(self):
        import _diagramscene_rc

        super(MainWindow, self).__init__()

        self.config_manipulations = FlumeConfig(self)
        properties_generator.dump_props()

        self.create_actions()
        self.create_menus()
        self.create_tool_box()
        self.clicked_button_id = 0

        self.scene = DiagramScene(self.item_menu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))

        self.scene.itemInserted.connect(self.item_inserted)
        self.scene.textInserted.connect(self.text_inserted)
        self.scene.itemSelected.connect(self.item_selected)

        self.create_tool_bars()
        # self.scene.enable_grid()

        layout = QHBoxLayout()
        layout.addWidget(self.tool_box)
        self.view = QGraphicsView(self.scene)
        self.view.centerOn(0, 0)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("The Flume Illustrator")

    # noinspection PyAttributeOutsideInit,PyArgumentList
    def create_actions(self):

        self.to_front_action = QAction(QIcon(':/images/bringtofront.png'),
                                       "Bring to &Front", self, shortcut="Ctrl+F",
                                       statusTip="Bring item to front", triggered=self.bring_to_front)
        self.send_back_action = QAction(QIcon(':/images/sendtoback.png'),
                                        "Send to &Back", self, shortcut="Ctrl+B",
                                        statusTip="Send item to back", triggered=self.send_to_back)
        self.bold_action = QAction(QIcon(':/images/bold.png'),
                                   "Bold", self, checkable=True, shortcut="Ctrl+B",
                                   triggered=self.handle_font_change)
        self.italic_action = QAction(QIcon(':/images/italic.png'),
                                     "Italic", self, checkable=True, shortcut="Ctrl+I",
                                     triggered=self.handle_font_change)
        self.underline_action = QAction(QIcon(':/images/underline.png'),
                                        "Underline", self, checkable=True, shortcut="Ctrl+U",
                                        triggered=self.handle_font_change)

        self.delete_action = QAction(QIcon(':/images/delete.png'),
                                     "Delete", self, shortcut="Delete", statusTip='Delete item from diagram',
                                     triggered=self.delete_item)
        self.exit_action = QAction("Exit", self, shortcut="Ctrl+X",
                                   statusTip="Quit program", triggered=self.close)
        self.about_action = QAction("About", self, shortcut="Ctrl+B",
                                    triggered=self.about)
        self.load_config_action = QAction("Load", self, shortcut="Ctrl+O",
                                          statusTip="Load config file", triggered=self.config_manipulations.load_config)

        self.enable_grid_action = QAction("Enable grid", self, checkable=True, triggered=self.enable_grid)

    # noinspection PyAttributeOutsideInit
    def create_menus(self):
        self.file_menu = self.menuBar().addMenu("File")
        self.file_menu.addAction(self.load_config_action)
        self.file_menu.addAction(self.exit_action)

        self.item_menu = self.menuBar().addMenu("Item")
        self.item_menu.addAction(self.delete_action)
        self.item_menu.addSeparator()
        self.item_menu.addAction(self.to_front_action)
        self.item_menu.addAction(self.send_back_action)

        self.about_menu = self.menuBar().addMenu("Help")
        self.about_menu.addAction(self.about_action)

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_box(self):
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(False)
        self.button_group.buttonClicked[int].connect(self.button_group_clicked)

        layout = QGridLayout()
        layout.addWidget(self.create_cell_widget("Source", "source"), 0, 0)
        layout.addWidget(self.create_cell_widget("Channel", "channel"), 0, 1)
        layout.addWidget(self.create_cell_widget("Sink", "sink"), 1, 0)

        text_button = QToolButton()
        text_button.setCheckable(True)
        self.button_group.addButton(text_button, self.InsertTextButton)
        text_button.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        text_button.setIconSize(QSize(50, 50))

        text_layout = QGridLayout()
        text_layout.addWidget(text_button, 0, 0, Qt.AlignHCenter)
        text_layout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        text_widget = QWidget()
        text_widget.setLayout(text_layout)
        layout.addWidget(text_widget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        item_widget = QWidget()
        item_widget.setLayout(layout)

        self.tool_box = QToolBox()
        self.tool_box.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.tool_box.setMinimumWidth(item_widget.sizeHint().width())
        self.tool_box.addItem(item_widget, "Basic Flume Items")

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_bars(self):

        self.edit_tool_bar = self.addToolBar("Edit")
        self.edit_tool_bar.addAction(self.delete_action)
        self.edit_tool_bar.addAction(self.to_front_action)
        self.edit_tool_bar.addAction(self.send_back_action)

        self.edit_tool_bar.addAction(self.enable_grid_action)

        self.font_combo = QFontComboBox()
        self.font_combo.currentFontChanged.connect(self.current_font_changed)

        self.font_size_combo = QComboBox()
        self.font_size_combo.setEditable(True)
        for i in range(8, 30, 2):
            self.font_size_combo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.font_size_combo.setValidator(validator)
        self.font_size_combo.currentIndexChanged.connect(self.font_size_changed)

        self.font_color_tool_button = QToolButton()
        self.font_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.font_color_tool_button.setMenu(
            self.create_color_menu(self.text_color_changed, Qt.black))
        self.text_action = self.font_color_tool_button.menu().defaultAction()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               Qt.black))
        self.font_color_tool_button.setAutoFillBackground(True)
        self.font_color_tool_button.clicked.connect(self.text_button_triggered)

        self.fill_color_tool_button = QToolButton()
        self.fill_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.fill_color_tool_button.setMenu(
            self.create_color_menu(self.item_color_changed, Qt.white))
        self.fillAction = self.fill_color_tool_button.menu().defaultAction()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               Qt.white))
        self.fill_color_tool_button.clicked.connect(self.fill_button_triggered)

        self.line_color_tool_button = QToolButton()
        self.line_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.line_color_tool_button.setMenu(
            self.create_color_menu(self.line_color_changed, Qt.black))
        self.lineAction = self.line_color_tool_button.menu().defaultAction()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               Qt.black))
        self.line_color_tool_button.clicked.connect(self.line_button_triggered)

        self.text_tool_bar = self.addToolBar("Font")
        self.text_tool_bar.addWidget(self.font_combo)
        self.text_tool_bar.addWidget(self.font_size_combo)
        self.text_tool_bar.addAction(self.bold_action)
        self.text_tool_bar.addAction(self.italic_action)
        self.text_tool_bar.addAction(self.underline_action)

        self.color_tool_bar = self.addToolBar("Color")
        self.color_tool_bar.addWidget(self.font_color_tool_button)
        self.color_tool_bar.addWidget(self.fill_color_tool_button)
        self.color_tool_bar.addWidget(self.line_color_tool_button)

        self.loading_tool_bar = self.addToolBar("Load")
        self.loading_tool_bar.addAction(self.load_config_action)

        pointer_button = QToolButton()
        pointer_button.setCheckable(True)
        pointer_button.setChecked(True)
        pointer_button.setIcon(QIcon(":/images/pointer.png"))
        line_pointer_button = QToolButton()
        line_pointer_button.setCheckable(True)
        line_pointer_button.setIcon(QIcon(":/images/linepointer.png"))

        self.pointer_type_group = QButtonGroup()
        self.pointer_type_group.addButton(pointer_button, DiagramScene.MoveItem)
        self.pointer_type_group.addButton(line_pointer_button, DiagramScene.InsertLine)
        self.pointer_type_group.buttonClicked[int].connect(self.pointer_group_clicked)

        self.scene_scale_combo = QComboBox()
        self.scene_scale_combo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.scene_scale_combo.setCurrentIndex(2)
        self.scene_scale_combo.currentIndexChanged[str].connect(self.scene_scale_changed)

        self.pointer_tool_bar = self.addToolBar("Pointer type")
        self.pointer_tool_bar.addWidget(pointer_button)
        self.pointer_tool_bar.addWidget(line_pointer_button)
        self.pointer_tool_bar.addWidget(self.scene_scale_combo)

    def button_group_clicked(self, button_id):
        buttons = self.button_group.buttons()
        self.clicked_button_id = button_id
        for button in buttons:
            if self.button_group.button(button_id) != button:
                button.setChecked(False)
        if button_id == self.InsertTextButton:
            self.scene.set_mode(DiagramScene.InsertText)
        else:
            self.scene.set_item_type(self.items[button_id])
            self.scene.set_mode(DiagramScene.InsertItem)

    def delete_item(self):
        for item in self.scene.selectedItems():
            if isinstance(item, FlumeDiagramItem):
                item.remove_arrows()
            self.scene.removeItem(item)

    # noinspection PyTypeChecker,PyCallByClass
    def about(self):

        # noinspection PyArgumentList
        QMessageBox.about(self, "About Flume Illustrator", "The Flume illustrator shows config-file details")

    def pointer_group_clicked(self):
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def bring_to_front(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() >= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() + 0.1
        selected_item.setZValue(z_value)

    def send_to_back(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() <= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() - 0.1
        selected_item.setZValue(z_value)

    def scene_scale_changed(self, scale):
        new_scale = float(scale[:scale.index("%")]) / 100
        old_transform = self.view.transform()
        self.view.resetTransform()
        self.view.translate(old_transform.dx(), old_transform.dy())
        self.view.scale(new_scale, new_scale)

    def item_inserted(self, diagram_type):
        self.pointer_type_group.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.set_mode(self.scene.DefaultMode)
        self.button_group.button(self.clicked_button_id).setChecked(False)

    def text_inserted(self, item):
        self.button_group.button(self.InsertTextButton).setChecked(False)
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def current_font_changed(self, font):
        self.handle_font_change()

    def font_size_changed(self, font=None):
        self.handle_font_change()

    def text_color_changed(self):
        self.text_action = self.sender()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               QColor(self.text_action.data())))
        self.text_button_triggered()

    def item_color_changed(self):
        self.fillAction = self.sender()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               QColor(self.fillAction.data())))
        self.fill_button_triggered()

    def line_color_changed(self):
        self.lineAction = self.sender()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               QColor(self.lineAction.data())))
        self.line_button_triggered()

    def text_button_triggered(self):
        self.scene.set_text_color(QColor(self.text_action.data()))

    def fill_button_triggered(self):
        self.scene.set_item_color(QColor(self.fillAction.data()))

    def line_button_triggered(self):
        self.scene.set_line_color(QColor(self.lineAction.data()))

    def handle_font_change(self):
        font = self.font_combo.currentFont()
        font.setPointSize(int(self.font_size_combo.currentText()))
        if self.bold_action.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italic_action.isChecked())
        font.setUnderline(self.underline_action.isChecked())

        self.scene.setFont(font)

    def item_selected(self, item):
        font = item.font()
        self.font_combo.setCurrentFont(font)
        self.font_size_combo.setEditText(str(font.pointSize()))
        self.bold_action.setChecked(font.weight() == QFont.Bold)
        self.italic_action.setChecked(font.italic())
        self.underline_action.setChecked(font.underline())

    def create_cell_widget(self, text, diagram_type):
        item = FlumeObject(diagram_type, "")
        icon = QIcon(item.pictogram.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.button_group.addButton(button)  # , diagram_type

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignHCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    # noinspection PyArgumentList
    def create_color_menu(self, slot, default_color):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        color_menu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.create_color_icon(color), name, self,
                             triggered=slot)
            action.setData(QColor(color))
            color_menu.addAction(action)
            if color == default_color:
                color_menu.setDefaultAction(action)
        return color_menu

    @staticmethod
    def create_color_tool_button_icon(image_file, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(image_file)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    @staticmethod
    def create_color_icon(color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)

    def enable_grid(self):
        if self.enable_grid_action.isChecked():
            color = Qt.black
        else:
            color = Qt.white
        for i in range(50):
            for j in range(50):
                self.scene.addEllipse(i * 100, j * 100, 2, 2, QPen(color))
Esempio n. 28
0
class Example(QWidget):
	def __init__(self):
		super().__init__()
		self.initUI()

	def initUI(self):
		label1 = QLabel("需要校验的数据:")
		label2 = QLabel("校验计算结果(HEX):")

		copy_btn1 = QPushButton('复制')
		copy_btn2 = QPushButton('复制')
		copy_btn1.setFixedWidth(60)
		copy_btn2.setFixedWidth(60)

		self.text1 = QTextEdit()
		self.text1.setAcceptRichText(False)
		self.text2 = QTextEdit()
		self.text2.setAcceptRichText(False)

		label3 = QLabel('输入格式:')
		self.formatGroup = QButtonGroup()
		self.format_ascii = QRadioButton('ASCII')
		self.format_hex = QRadioButton('HEX')
		self.format_hex.setChecked(True)
		self.formatGroup.addButton(self.format_ascii)
		self.formatGroup.addButton(self.format_hex)
		self.formatGroup.setExclusive(True)

		label4 = QLabel('校验长度:')
		# self.lengthGroup = QButtonGroup()
		# self.length_1 = QRadioButton('1')
		# self.length_1.setChecked(True)
		# self.length_2 = QRadioButton('2')
		# self.length_4 = QRadioButton('4')
		# self.lengthGroup.addButton(self.length_1)
		# self.lengthGroup.addButton(self.length_2)
		# self.lengthGroup.addButton(self.length_4)
		# self.lengthGroup.setExclusive(True)

		# self.format = QComboBox()
		# self.format.addItems(['ASCII', 'HEX'])
		# self.format.setCurrentIndex(1)

		self.length = QComboBox()
		self.length.addItems(['1','2','4'])

		btn1 = QPushButton('和校验 >>')
		btn1.setToolTip('不带进位')
		btn2 = QPushButton('异或校验 >>')
		btn3 = QPushButton('CRC校验 >>')
		btn3.setToolTip('目前只支持16位CRC校验,校验长度请选择2')
		btn4 = QPushButton('进位和校验 >>')
		btn5 = QPushButton('预留')
		btn6 = QPushButton('预留')
		btn_clr = QPushButton('清空')

		leftGrid = QGridLayout()
		leftGrid.setSpacing(10)
		leftGrid.addWidget(label1, 1, 0)
		leftGrid.addWidget(label2, 1, 1)
		leftGrid.addWidget(self.text1, 2, 0)
		leftGrid.addWidget(self.text2, 2, 1)
		leftGrid.addWidget(copy_btn1, 3, 0)
		leftGrid.addWidget(copy_btn2, 3, 1)

		rightVBox = QVBoxLayout()
		rightVBox.setAlignment(Qt.AlignVCenter)
		rightVBox.addStretch()
		rightVBox.addWidget(label3)
		rightVBox.addWidget(self.format_hex)
		rightVBox.addWidget(self.format_ascii)
		rightVBox.addStretch()
		rightVBox.addWidget(label4)
		# rightVBox.addWidget(self.length_1)
		# rightVBox.addWidget(self.length_2)
		# rightVBox.addWidget(self.length_4)
		# rightVBox.addWidget(self.format)
		rightVBox.addWidget(self.length)
		rightVBox.addStretch()
		rightVBox.addWidget(btn1)
		rightVBox.addWidget(btn4)
		rightVBox.addWidget(btn2)
		rightVBox.addWidget(btn3)
		# rightVBox.addWidget(btn5)
		# rightVBox.addWidget(btn6)
		rightVBox.addStretch()
		rightVBox.addWidget(btn_clr)

		mainBox = QHBoxLayout()
		mainBox.addLayout(leftGrid)
		mainBox.addLayout(rightVBox)

		self.setLayout(mainBox)

		# 按钮连接到槽
		btn1.clicked.connect(self.button1Clicked)
		btn2.clicked.connect(self.button2Clicked)
		btn3.clicked.connect(self.button3Clicked)
		btn4.clicked.connect(self.button4Clicked)
		btn5.clicked.connect(self.button5Clicked)
		btn6.clicked.connect(self.button6Clicked)
		btn_clr.clicked.connect(self.buttonClrClicked)

		copy_btn1.clicked.connect(self.copyButton1Clicked)
		# copy_btn2.clicked.connect(self.copyButton2Clicked)

		self.setGeometry(200, 300, 600, 350)
		self.setWindowTitle('校验码计算')
		self.show()

	def get_input(self):
		'''
		获取输入数据,按照选择的格式解析,得到输入数据的数值列表
		:return: 输入数据的数值列表
		例如:
		输入30 31 32,选择HEX,返回[48,49,50]
		输入abc,选择ASCII,返回[97,98,99]
		'''
		input_text = self.text1.toPlainText()
		if(input_text == ""):
			if self.format_ascii.isChecked(): # ASCII
				input_text = EXAMPLE_1
			elif self.format_hex.isChecked(): # HEX
				input_text = EXAMPLE_2
			self.text1.setPlainText(input_text)

		if self.format_ascii.isChecked(): # ASCII
			data = [ord(a) for a in input_text]
		elif self.format_hex.isChecked(): # HEX
			input_text = self.removeBlank(input_text)
			if len(input_text)%2 != 0: # 输入HEX数据必须是偶数长度
				self.text2.setPlainText('WRONG DATA!')
				return None
			input_text = self.addBlank(input_text)
			data = input_text.split()
			data = [int(a,16) for a in data]
		return data

	def set_output(self, output_result):
		length = int(self.length.currentText())
		if length == 1:
			result = output_result & 0xFF
			result_string = '0x%02X' % result
		elif length == 2:
			result = output_result & 0xFFFF
			result_string = '0x%04X' % result
		elif length == 4:
			result = output_result & 0xFFFFFFFF
			result_string = '0x%08X' % result
		return self.text2.setPlainText(result_string)

	def button1Clicked(self):  # 和
		try:
			string_origin = self.get_input()
			string_result = sum(string_origin)
			self.set_output(string_result)
		except Exception as e:
			self.text2.setPlainText(e)

	def button2Clicked(self):  # 异或
		try:
			string_origin = self.get_input()
			string_result = self.xor(string_origin, int(self.length.currentText()))
			self.set_output(string_result)
		except Exception as e:
			self.text2.setPlainText(e)

	def button3Clicked(self):  # CRC
		import crc16
		if int(self.length.currentText()) != 2:
			self.text2.setPlainText('目前只支持16位CRC校验,校验长度请选择2')
		else:
			try:
				string_origin = self.get_input()
				string_result = crc16.crc16_check(string_origin)
				self.set_output(string_result)
			except Exception as e:
				self.text2.setPlainText(e)

	def button4Clicked(self):  # 进位和校验
		pass

	def button5Clicked(self):  # 预留
		pass

	def button6Clicked(self):  # 预留
		pass

	def buttonClrClicked(self):
		self.text1.setPlainText("")
		self.text2.setPlainText("")

	def copyButton1Clicked(self):
		clipboard = QApplication.clipboard()
		clipboard.setText(self.text1.toPlainText())

	def u2c(self, data_str):
		'''
		转换unicode为字符
		unicode格式:每2个字节对应1个字符,字节间可以以空格、换行分隔,字节为十六进制,前面带或不带0x均可
		:param data_str:待转换内容
		:return:转换结果
		'''
		result = []

		if (len(data_str) < 3):
			return ''

		data = data_str.split()  # If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

		for i in range(0, len(data) - 1, 2):
			try:
				a = int(data[i], 16)
				b = int(data[i + 1], 16)
				res = b'\\u%02x%02x' % (a, b)
				res1 = res.decode('unicode_escape')
				result.append(res1)
			# print(res1,end='')
			except Exception as e:
				print(e)
		return result

	def a2c(self, data_str):
		'''
		转换ascii码为字符
		ascii格式:每1个字节对应1个字符,字节间可以以空格、换行分隔,字节为十六进制,前面带或不带0x均可
		:param data_str:待转换内容
		:return:转换结果
		'''
		result = []

		data = data_str.split()

		for i in data:
			try:
				a = int(i, 16)
				result.append(chr(a))
			except Exception as e:
				print(e)
		return result

	def c2a(self, data_str):
		'''
		转换字符为ascii码
		:param data_str: 待转换内容
		:return: 转换结果
		'''
		result = []

		data = data_str

		for i in data:
			try:
				a = ord(i)
				result.append('0x%x' % a)
			except Exception as e:
				print(e)
		return result

	def addBlank(self, message):
		# 每两个字符之间加一个空格
		chrstr = [message[i:i + 2] for i in range(0, len(message), 2)]
		return ' '.join(chrstr)

	def hex386(self, data_str):
		# 去掉第一行和最后两行
		# 每行格式为:LLAAAARRDD...DDDDCC,去掉开头9个字符和最后2个字符
		result = []
		data = data_str.split('\n')
		for i in data[1:-2]:  # 去掉第一行和最后两行
			try:
				a = i[9:-2]  # 去掉开头9个字符和最后2个字符
				result.append(a)
			except Exception as e:
				print(e)
		return result

	def removeBlank(self, message):
		# 去掉所有空字符(空格、换行)
		return ''.join(message.split())

	def xor(self, data, length=1):
		if length == 1:
			pass
		elif length == 2:
			if(len(data)%2 != 0):
				data.extend([0]) # 长度不为2的倍数时在末尾补0
			data = [(data[i]<<8)+data[i+1] for i in range(0, len(data), 2)] # 重新按长度为2字节解析数据
		elif length == 4:
			if(len(data)%4 != 0):
				data.extend([0] * (4-len(data)%4)) # 长度不为4的倍数时在末尾补0
			data = [(data[i]<<24)+(data[i+1]<<16)+(data[i+2]<<8)+data[i+3] for i in range(0, len(data), 4)] # 重新按长度为4字节解析数据
		result = 0
		for a in data:
			result = result ^ a
		return result
Esempio n. 29
0
class ToolbarTabManager(QObject):
    ""
    def __init__(self, toolbar, parent=None):
        super().__init__(parent)
        self.parent_widget = parent
        self.toolbar = toolbar
        self._actions = []
        self._last_selected = None
        self.idx_widget = self.toolbar.addWidget(QWidget(self.toolbar))
        self.idx_widget.setVisible(False)

        self.agroup = QButtonGroup(self)
        self.agroup.setExclusive(True)

        self.library_btn = None
        self.favorite_btn = self.addTab("Favorites", delegate_paint=False, icon=app_constants.STAR_ICON)
        self.library_btn = self.addTab("Library", delegate_paint=False, icon=app_constants.GRIDL_ICON)
        self.idx_widget = self.toolbar.addWidget(QWidget(self.toolbar))
        self.idx_widget.setVisible(False)
        self.toolbar.addSeparator()

    def _manage_selected(self, b):
        if self._last_selected == b:
            return
        if self._last_selected:
            self._last_selected.selected = False
            self._last_selected.view.list_view.sort_model.rowsInserted.disconnect(self.parent_widget.stat_row_info)
            self._last_selected.view.list_view.sort_model.rowsRemoved.disconnect(self.parent_widget.stat_row_info)
            self._last_selected.view.hide()
        b.selected = True
        self._last_selected = b
        self.parent_widget.current_manga_view = b.view
        b.view.list_view.sort_model.rowsInserted.connect(self.parent_widget.stat_row_info)
        b.view.list_view.sort_model.rowsRemoved.connect(self.parent_widget.stat_row_info)
        b.view.show()

    def addTab(self, name, view_type=app_constants.ViewType.Default, delegate_paint=True, allow_sidebarwidget=False, icon=None):
        if self.toolbar:
            t = misc.ToolbarButton(self.toolbar, name)
            if icon:
                t.setIcon(icon)
            else:
                t.setIcon(app_constants.CIRCLE_ICON)
            t.setCheckable(True)
            self.agroup.addButton(t)
            t.select.connect(self._manage_selected)
            t.close_tab.connect(self.removeTab)
            if self.library_btn:
                t.view = gallery.MangaViews(view_type, self.parent_widget, allow_sidebarwidget)
                t.view.hide()
                t.close_tab.connect(lambda:self.library_btn.click())
                if not allow_sidebarwidget:
                    t.clicked.connect(self.parent_widget.sidebar_list.arrow_handle.click)
            else:
                t.view = self.parent_widget.default_manga_view
            if delegate_paint:
                t.view.list_view.manga_delegate._paint_level = 9000 # over nine thousand!!!
            self._actions.append(self.toolbar.insertWidget(self.idx_widget, t))
            return t

    def removeTab(self, button_or_index):
        if self.toolbar:
            if isinstance(button_or_index, int):
                self.toolbar.removeAction(self._actions.pop(button_or_index))
            else:
                act_to_remove = None
                for act in self._actions:
                    w = self.toolbar.widgetForAction(act)
                    if w == button_or_index:
                        self.toolbar.removeAction(act)
                        act_to_remove = act
                        break
                if act_to_remove:
                    self._actions.remove(act)
Esempio n. 30
0
    def __init__(self, parent):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self.parent_widget = parent
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
        self._widget_layout = QHBoxLayout(self)

        # widget stuff
        self._d_widget = QWidget(self)
        self._d_widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
        self._widget_layout.addWidget(self._d_widget)
        self.main_layout = QVBoxLayout(self._d_widget)
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0,0,0,0)
        self.arrow_handle = misc.ArrowHandle(self)
        self.arrow_handle.CLICKED.connect(self.slide)

        self._widget_layout.addWidget(self.arrow_handle)
        self.setContentsMargins(0,0,-self.arrow_handle.width(),0)

        self.show_all_galleries_btn = QPushButton("Show all galleries")
        self.show_all_galleries_btn.clicked.connect(lambda:parent.manga_list_view.sort_model.set_gallery_list())
        self.show_all_galleries_btn.clicked.connect(self.show_all_galleries_btn.hide)
        self.show_all_galleries_btn.setIcon(app_constants.CROSS_ICON_WH)
        self.show_all_galleries_btn.hide()
        self.main_layout.addWidget(self.show_all_galleries_btn)
        self.main_buttons_layout = QHBoxLayout()
        self.main_layout.addLayout(self.main_buttons_layout)

        # buttons
        bgroup = QButtonGroup(self)
        bgroup.setExclusive(True)
        self.lists_btn = QPushButton("")
        self.lists_btn.setIcon(app_constants.G_LISTS_ICON_WH)
        self.lists_btn.setCheckable(True)
        bgroup.addButton(self.lists_btn)
        self.artist_btn = QPushButton("")
        self.artist_btn.setIcon(app_constants.ARTISTS_ICON)
        self.artist_btn.setCheckable(True)
        bgroup.addButton(self.artist_btn)
        self.ns_tags_btn = QPushButton("")
        self.ns_tags_btn.setIcon(app_constants.NSTAGS_ICON)
        self.ns_tags_btn.setCheckable(True)
        bgroup.addButton(self.ns_tags_btn)
        self.lists_btn.setChecked(True)


        self.main_buttons_layout.addWidget(self.lists_btn)
        self.main_buttons_layout.addWidget(self.artist_btn)
        self.main_buttons_layout.addWidget(self.ns_tags_btn)

        # buttons contents
        self.stacked_layout = QStackedLayout()
        self.main_layout.addLayout(self.stacked_layout)

        # lists
        gallery_lists_dummy = QWidget(self)
        self.lists = GalleryLists(self)
        create_new_list_btn = QPushButton()
        create_new_list_btn.setIcon(QIcon(app_constants.PLUS_ICON))
        create_new_list_btn.setIconSize(QSize(15, 15))
        create_new_list_btn.clicked.connect(lambda: self.lists.create_new_list())
        create_new_list_btn.adjustSize()
        create_new_list_btn.setFixedSize(create_new_list_btn.width(), create_new_list_btn.height())
        create_new_list_btn.setToolTip("Create a new list!")
        lists_l = QVBoxLayout(gallery_lists_dummy)
        lists_l.setContentsMargins(0,0,0,0)
        lists_l.setSpacing(0)
        lists_l.addWidget(self.lists)
        lists_l.addWidget(create_new_list_btn)
        lists_index = self.stacked_layout.addWidget(gallery_lists_dummy)
        self.lists.GALLERY_LIST_CLICKED.connect(parent.manga_list_view.sort_model.set_gallery_list)
        self.lists.GALLERY_LIST_CLICKED.connect(self.show_all_galleries_btn.show)
        self.lists.GALLERY_LIST_REMOVED.connect(self.show_all_galleries_btn.click)
        self.lists_btn.clicked.connect(lambda:self.stacked_layout.setCurrentIndex(lists_index))
        self.show_all_galleries_btn.clicked.connect(self.lists.clearSelection)
        self.show_all_galleries_btn.clicked.connect(self.lists._reset_selected)

        # artists
        self.artists_list = GalleryArtistsList(parent.manga_list_view.gallery_model, self)
        self.artists_list.artist_clicked.connect(lambda a: parent.search('artist:"{}"'.format(a)))
        artists_list_index = self.stacked_layout.addWidget(self.artists_list)
        self.artist_btn.clicked.connect(lambda:self.stacked_layout.setCurrentIndex(artists_list_index))
        #self.lists.GALLERY_LIST_CLICKED.connect(self.artists_list.set_current_glist)
        self.show_all_galleries_btn.clicked.connect(self.artists_list.clearSelection)
        #self.show_all_galleries_btn.clicked.connect(lambda:self.artists_list.set_current_glist())

        # ns_tags
        self.tags_tree = TagsTreeView(self)
        self.tags_tree.TAG_SEARCH.connect(parent.search)
        self.tags_tree.NEW_LIST.connect(self.lists.create_new_list)
        self.tags_tree.setHeaderHidden(True)
        self.show_all_galleries_btn.clicked.connect(self.tags_tree.clearSelection)
        self.tags_layout = QVBoxLayout(self.tags_tree)
        ns_tags_index = self.stacked_layout.addWidget(self.tags_tree)
        self.ns_tags_btn.clicked.connect(lambda:self.stacked_layout.setCurrentIndex(ns_tags_index))

        self.slide_animation = misc.create_animation(self, "maximumSize")
        self.slide_animation.stateChanged.connect(self._slide_hide)
        self.slide_animation.setEasingCurve(QEasingCurve.InOutQuad)
Esempio n. 31
0
class Ui_Widget(object):
    """ Klasa definiująca GUI """

    def setupUi(self, Widget):

        # widgety rysujące kształty, instancje klasy Ksztalt
        self.ksztalt1 = Ksztalt(self, Ksztalty.Polygon)
        self.ksztalt2 = Ksztalt(self, Ksztalty.Ellipse)
        self.ksztaltAktywny = self.ksztalt1

        # przyciski CheckBox ###
        uklad = QVBoxLayout()  # układ pionowy
        self.grupaChk = QButtonGroup()
        for i, v in enumerate(('Kwadrat', 'Koło', 'Trójkąt', 'Linia')):
            self.chk = QCheckBox(v)
            self.grupaChk.addButton(self.chk, i)
            uklad.addWidget(self.chk)
        self.grupaChk.buttons()[self.ksztaltAktywny.ksztalt].setChecked(True)
        # CheckBox do wyboru aktywnego kształtu
        self.ksztaltChk = QCheckBox('<=')
        self.ksztaltChk.setChecked(True)
        uklad.addWidget(self.ksztaltChk)

        # układ poziomy dla kształtów oraz przycisków CheckBox
        ukladH1 = QHBoxLayout()
        ukladH1.addWidget(self.ksztalt1)
        ukladH1.addLayout(uklad)
        ukladH1.addWidget(self.ksztalt2)
        # koniec CheckBox ###

        # Slider i LCDNumber ###
        self.suwak = QSlider(Qt.Horizontal)
        self.suwak.setMinimum(0)
        self.suwak.setMaximum(255)
        self.lcd = QLCDNumber()
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        # układ poziomy (splitter) dla slajdera i lcd
        ukladH2 = QSplitter(Qt.Horizontal, self)
        ukladH2.addWidget(self.suwak)
        ukladH2.addWidget(self.lcd)
        ukladH2.setSizes((125, 75))

        # przyciski RadioButton ###
        self.ukladR = QHBoxLayout()
        for v in ('R', 'G', 'B'):
            self.radio = QRadioButton(v)
            self.ukladR.addWidget(self.radio)
        self.ukladR.itemAt(0).widget().setChecked(True)
        # grupujemy przyciski
        self.grupaRBtn = QGroupBox('Opcje RGB')
        self.grupaRBtn.setLayout(self.ukladR)
        self.grupaRBtn.setObjectName('Radio')
        self.grupaRBtn.setCheckable(True)
        # układ poziomy dla grupy Radio
        ukladH3 = QHBoxLayout()
        ukladH3.addWidget(self.grupaRBtn)
        # koniec RadioButton ###

        # Lista ComboBox i SpinBox ###
        self.listaRGB = QComboBox(self)
        for v in ('R', 'G', 'B'):
            self.listaRGB.addItem(v)
        self.listaRGB.setEnabled(False)
        # SpinBox
        self.spinRGB = QSpinBox()
        self.spinRGB.setMinimum(0)
        self.spinRGB.setMaximum(255)
        self.spinRGB.setEnabled(False)
        # układ pionowy dla ComboBox i SpinBox
        uklad = QVBoxLayout()
        uklad.addWidget(self.listaRGB)
        uklad.addWidget(self.spinRGB)
        # do układu poziomego grupy Radio dodajemy układ ComboBox i SpinBox
        ukladH3.insertSpacing(1, 25)
        ukladH3.addLayout(uklad)
        # koniec ComboBox i SpinBox ###

        # przyciski PushButton ###
        uklad = QHBoxLayout()
        self.grupaP = QButtonGroup()
        self.grupaP.setExclusive(False)
        for v in ('R', 'G', 'B'):
            self.btn = QPushButton(v)
            self.btn.setCheckable(True)
            self.grupaP.addButton(self.btn)
            uklad.addWidget(self.btn)
        # grupujemy przyciski
        self.grupaPBtn = QGroupBox('Przyciski RGB')
        self.grupaPBtn.setLayout(uklad)
        self.grupaPBtn.setObjectName('Push')
        self.grupaPBtn.setCheckable(True)
        self.grupaPBtn.setChecked(False)
        # koniec PushButton ###

        # główny układ okna, wertykalny ###
        ukladOkna = QVBoxLayout()
        ukladOkna.addLayout(ukladH1)
        ukladOkna.addWidget(ukladH2)
        ukladOkna.addLayout(ukladH3)
        ukladOkna.addWidget(self.grupaPBtn)

        self.setLayout(ukladOkna)  # przypisanie układu do okna głównego
        self.setWindowTitle('Widżety')
Esempio n. 32
0
 def create_rows(self, layout, sarea):
     u"""Build the rows of the dialog box"""
     play_button_group = QButtonGroup(sarea)
     old_play_button_group = QButtonGroup(sarea)
     for num, entry in enumerate(self.entries_list, 2):
         tt_text = self.build_text_help_label(entry)
         ico_label = QLabel('', sarea)
         ico_label.setToolTip(tt_text)
         if entry.icon:
             ico_label.setPixmap(QPixmap.fromImage(entry.icon))
         layout.addWidget(ico_label, num, 0)
         tt_label = QLabel(entry.display_word, sarea)
         tt_label.setToolTip(tt_text)
         layout.addWidget(tt_label, num, 1)
         if self.hide_text:
             tt_label.hide()
         # Play button.
         t_play_button = QPushButton(sarea)
         play_button_group.addButton(t_play_button, num-2)
         t_play_button.setToolTip(self.play_help)
         t_play_button.setIcon(QIcon(os.path.join(icons_dir, 'play.png')))
         layout.addWidget(t_play_button, num, self.play_column)
         if self.note[entry.audio_field_name]:
             t_play_old_button = QPushButton(sarea)
             old_play_button_group.addButton(t_play_old_button, num-2)
             t_play_old_button.setIcon(
                 QIcon(os.path.join(icons_dir, 'play.png')))
             if not self.hide_text:
                 t_play_old_button.setToolTip(
                     self.note[entry.audio_field_name])
             else:
                 t_play_old_button.setToolTip(self.play_old_help_short)
             layout.addWidget(t_play_old_button, num, self.play_old_column)
         else:
             dummy_label = QLabel('', sarea)
             dummy_label.setToolTip(self.play_old_empty_line_help)
             layout.addWidget(dummy_label, num, self.play_old_column)
         # The group where we later look what to do:
         t_button_group = QButtonGroup(sarea)
         t_button_group.setExclusive(True)
         # Now the four buttons
         t_add_button = QPushButton(sarea)
         t_add_button.setCheckable(True)
         t_add_button.setFlat(True)
         t_add_button.setToolTip(self.add_help_text_short)
         t_add_button.setIcon(QIcon(os.path.join(icons_dir, 'add.png')))
         layout.addWidget(t_add_button, num, self.add_column)
         t_button_group.addButton(t_add_button, Action.Add)
         t_keep_button = QPushButton(sarea)
         t_keep_button.setCheckable(True)
         t_keep_button.setFlat(True)
         t_keep_button.setToolTip(self.keep_help_text_short)
         t_keep_button.setIcon(QIcon(os.path.join(icons_dir, 'keep.png')))
         layout.addWidget(t_keep_button, num, self.keep_column)
         t_button_group.addButton(t_keep_button, Action.Keep)
         t_delete_button = QPushButton(sarea)
         t_delete_button.setCheckable(True)
         t_delete_button.setFlat(True)
         t_delete_button.setToolTip(self.delete_help_text_short)
         t_delete_button.setIcon(
             QIcon(os.path.join(icons_dir, 'delete.png')))
         layout.addWidget(t_delete_button, num, self.delete_column)
         t_button_group.addButton(t_delete_button,  Action.Delete)
         t_blacklist_button = QPushButton(sarea)
         t_blacklist_button.setCheckable(True)
         t_blacklist_button.setFlat(True)
         t_blacklist_button.setToolTip(self.blacklist_help_text_short)
         t_blacklist_button.setIcon(
             QIcon(os.path.join(icons_dir, 'blacklist.png')))
         if entry.entry_hash:
             layout.addWidget(
                 t_blacklist_button, num, self.blacklist_column)
         else:
             t_blacklist_button.hide()
             dummy_label_bl = QLabel('', sarea)
             dummy_label_bl.setToolTip(self.blacklist_empty_line_help)
             layout.addWidget(dummy_label_bl, num, self.blacklist_column)
         t_button_group.button(entry.action).setChecked(True)
         # New: check a button based on how good the downloader is.
         t_button_group.addButton(t_blacklist_button, Action.Blacklist)
         self.buttons_groups.append(t_button_group)
     play_button_group.buttonClicked.connect(
         lambda button: play(
             self.entries_list[play_button_group.id(button)].file_path))
     # N.B.: anki.sound.play() plays files from anywhere, not just
     # from the colection.media folder. We should be good,
     # here. (This behaviour may be a security risk, idk.)
     old_play_button_group.buttonClicked.connect(
         lambda button: playFromText(
             self.note[
                 self.entries_list[
                     old_play_button_group.id(button)].audio_field_name]))
Esempio n. 33
0
class UnitConverter(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()

    def initUI(self):
    
        self.tab = QTabWidget(self)
        
        # Length Tab
        self.length = QWidget()
        
        self.lengthLabel = QLabel("Length Converter")
        self.lengthFrom = QLineEdit()
        self.lengthTo = QLineEdit()
        self.kilometersFrom = QRadioButton('Km',self)
        self.kilometersTo = QRadioButton('Km',self)
        self.metersFrom = QRadioButton('m', self)
        self.metersTo = QRadioButton('m', self)
        self.feetFrom = QRadioButton('ft', self)
        self.feetTo = QRadioButton('ft',self)
        self.inchesFrom = QRadioButton('in', self)
        self.inchesTo = QRadioButton('in', self)
        
        self.lengthButton = QPushButton("Convert")
        self.lengthButton.clicked.connect(self.convertLength)
        
        self.groupLength = QButtonGroup()
        self.groupLength.addButton(self.kilometersFrom)
        self.groupLength.addButton(self.kilometersTo)
        self.groupLength.addButton(self.metersFrom)
        self.groupLength.addButton(self.metersTo)
        self.groupLength.addButton(self.feetFrom)
        self.groupLength.addButton(self.feetTo)
        self.groupLength.addButton(self.inchesFrom)
        self.groupLength.addButton(self.inchesTo)
        self.groupLength.setExclusive(False)
        
        self.gridLength = QGridLayout()
        
        self.gridLength.addWidget(self.lengthLabel,0,1)
        self.gridLength.addWidget(self.lengthFrom,1,1)
        self.gridLength.addWidget(self.lengthTo,1,2)
        self.gridLength.addWidget(self.kilometersFrom,2,1)
        self.gridLength.addWidget(self.kilometersTo,2,2)
        self.gridLength.addWidget(self.metersFrom,3,1)
        self.gridLength.addWidget(self.metersTo,3,2)
        self.gridLength.addWidget(self.feetFrom,4,1)
        self.gridLength.addWidget(self.feetTo,4,2)
        self.gridLength.addWidget(self.inchesFrom,5,1)
        self.gridLength.addWidget(self.inchesTo,5,2)
        self.gridLength.addWidget(self.lengthButton,6,2)
        
        self.length.setLayout(self.gridLength)
        
        # Volume Tab
        self.volume = QWidget()
        
        self.volumeLabel = QLabel("Volume Converter")
        self.volumeFrom = QLineEdit()
        self.volumeTo = QLineEdit()
        self.litresFrom = QRadioButton('L',self)
        self.litresTo = QRadioButton('L', self)
        self.millilitresFrom = QRadioButton('mL', self)
        self.millilitresTo = QRadioButton('mL', self)
        self.fluidOuncesFrom = QRadioButton('fl oz', self)
        self.fluidOuncesTo = QRadioButton('fl oz', self) 
        
        self.volumeButton = QPushButton("Convert")
        self.volumeButton.clicked.connect(self.convertVolume)        
        
        self.groupVolume = QButtonGroup()
        self.groupVolume.addButton(self.litresFrom)
        self.groupVolume.addButton(self.litresTo)
        self.groupVolume.addButton(self.millilitresFrom)
        self.groupVolume.addButton(self.millilitresTo)
        self.groupVolume.addButton(self.fluidOuncesFrom)
        self.groupVolume.addButton(self.fluidOuncesTo)
        self.groupVolume.setExclusive(False)
        
        self.gridVolume = QGridLayout()
        
        self.gridVolume.addWidget(self.volumeLabel,0,1)
        self.gridVolume.addWidget(self.volumeFrom,1,1)
        self.gridVolume.addWidget(self.volumeTo,1,2)
        self.gridVolume.addWidget(self.litresFrom,2,1)
        self.gridVolume.addWidget(self.litresTo,2,2)
        self.gridVolume.addWidget(self.millilitresFrom,3,1)
        self.gridVolume.addWidget(self.millilitresTo,3,2)
        self.gridVolume.addWidget(self.fluidOuncesFrom,4,1)
        self.gridVolume.addWidget(self.fluidOuncesTo,4,2)
        self.gridVolume.addWidget(self.volumeButton,5,2)
        
        self.volume.setLayout(self.gridVolume)
        
        # Weight Tab
        self.weight = QWidget()
        
        self.weightLabel = QLabel("Weight Converter")
        self.weightFrom = QLineEdit()
        self.weightTo = QLineEdit()
        self.poundsFrom = QRadioButton('lbs',self)
        self.poundsTo = QRadioButton('lbs', self)
        self.kilogramFrom = QRadioButton('kg', self)
        self.kilogramTo = QRadioButton('kg', self)
        
        self.weightButton = QPushButton("Convert")
        self.weightButton.clicked.connect(self.convertWeight)
        
        self.groupWeight = QButtonGroup()
        self.groupWeight.addButton(self.poundsFrom)
        self.groupWeight.addButton(self.poundsTo)
        self.groupWeight.addButton(self.kilogramFrom)
        self.groupWeight.addButton(self.kilogramTo)
        self.groupWeight.setExclusive(False)
        
        self.gridWeight = QGridLayout()
        
        self.gridWeight.addWidget(self.weightLabel,0,1)
        self.gridWeight.addWidget(self.weightFrom,1,1)
        self.gridWeight.addWidget(self.weightTo,1,2)
        self.gridWeight.addWidget(self.poundsFrom,2,1)
        self.gridWeight.addWidget(self.poundsTo,2,2)
        self.gridWeight.addWidget(self.kilogramFrom,3,1)
        self.gridWeight.addWidget(self.kilogramTo,3,2)
        self.gridWeight.addWidget(self.weightButton,4,2)
        
        self.weight.setLayout(self.gridWeight)
        
        self.tab.addTab(self.length,"Length")
        self.tab.addTab(self.volume,"Volume")
        self.tab.addTab(self.weight, "Weight")
        
    
        self.setGeometry(300,300,300,200)
        self.setWindowTitle('Unit Converter')
        self.show()
    
    def convertLength(self):
        self.quantity = int(self.lengthFrom.text())
        
        if self.kilometersFrom.isChecked():
            km = Kilometer("Kilometer","km",self.quantity,"Length")
            if self.kilometersTo.isChecked():
                message = QMessageBox.warning(self,"Warning", "Can't convert km to km")
            elif self.metersTo.isChecked():
                converted = km.convert_to("meter",km.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.feetTo.isChecked():
                converted = km.convert_to("feet",km.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.inchesTo.isChecked():
                converted = km.convert_to("inches",km.magnitude)
                self.lengthTo.setText(str(converted))
        
        if self.metersFrom.isChecked():
            m = Meter("Meter", "m", self.quantity,"Length")
            if self.metersTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert m to m")
            elif self.kilometersTo.isChecked():
                converted = m.convert_to("kilometer",m.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.feetTo.isChecked():
                converted = m.convert_to("feet",m.magnitude) 
                self.lengthTo.setText(str(converted))
            elif self.inchesTo.isChecked():
                converted = m.convert_to("inches",m.magnitude)
                self.lengthTo.setText(str(converted))

        if self.feetFrom.isChecked():
            ft = Feet("Feet", "ft", self.quantity, "Length")
            if self.feetTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert ft to ft")
            elif self.kilometersTo.isChecked():
                converted = ft.convert_to("kilometer",ft.magnitude)  
                self.lengthTo.setText(str(converted))
            elif self.metersTo.isChecked():
                converted = ft.convert_to("meter",ft.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.inchesTo.isChecked():
                converted = ft.convert_to("inches",ft.magnitude)  
                self.lengthTo.setText(str(converted))  

        if self.inchesFrom.isChecked():
            inch = Inch("Inches", "in", self.quantity, "Length")
            if self.inchesTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert in to in")
            elif self.kilometersTo.isChecked():
                converted = inches.convert_to("kilometer",inches.magnitude) 
                self.lengthTo.setText(str(converted))
            elif self.metersTo.isChecked():
                converted = inches.convert_to("meters",inches.magnitude)
                self.lengthTo.setText(str(converted))
            elif self.feetTo.isChecked():
                converted = inches.convert_to("feet",inches.magnitude) 
                self.lengthTo.setText(str(converted))
    
    def convertVolume(self):
        self.quantity = int(self.volumeFrom.text())
        
        if self.litresFrom.isChecked():
            L = Litre("Litre", "L", self.quantity, "Volume")
            if self.litresTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert L to L")
            elif self.millilitresTo.isChecked():
                converted = L.convert_to("millilitres",L.magnitude)
                self.volumeTo.setText(str(converted))
            elif self.fluidOuncesTo.isChecked():
                converted = km.convert_to("fluid ounce",L.magnitude)
                self.volumeTo.setText(str(converted))
                
        if self.millilitresFrom.isChecked():
            mL = Millilitre("Millilitre", "mL", self.quantity, "Volume")
            if self.millilitresTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert mL to mL")
            elif self.litresTo.isChecked():
                converted = mL.convert_to("litre",mL.magnitude)
                self.volumeTo.setText(str(converted))
            elif self.fluidOuncesTo.isChecked():
                converted = mL.convert_to("fluid ounce",mL.magnitude)
                self.volumeTo.setText(str(converted))
                
        if self.fluidOuncesFrom.isChecked():
            flOz = FluidOunce("Fluid Ounce", "fl oz", self.quantity, "Volume")
            if self.fluidOuncesTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert fl oz to fl oz")
            elif self.litresTo.isChecked():
                converted = flOz.convert_to("litre",flOz.magnitude)
                self.volumeTo.setText(str(converted))
            elif self.millilitresTo.isChecked():
                converted = flOz.convert_to("millilitre",flOz.magnitude)
                self.volumeTo.setText(str(converted))
                
    def convertWeight(self):
        self.quantity = int(self.weightFrom.text())

        if self.kilogramFrom.isChecked():
            kg = Kilogram("Kilogram", "kg", self.quantity,"Weight")
            if self.kilogramTo.isChecked():
                message = QMessageBox.warning(self, "Warning", "Can't convert kg to kg")
            elif self.poundsTo.isChecked():
                converted = kg.convert_to("pound",kg.magnitude)
                self.weightTo.setText(str(converted))

        if self.poundsFrom.isChecked():
            lbs = Pound("Pound", "lbs", self.quantity, "Weight")
            if self.poundsTo.isChecked():
                message = QMessageBox.warning(self,"Warning", "Can't convert lbs to lbs")
            elif self.kilogramTo.isChecked():
                converted = lbs.convert_to("kilogram",lbs.magnitude)
                self.weightTo.setText(str(converted))                
Esempio n. 34
0
class MainWindow(QMainWindow):
    InsertTextButton = 10

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

        self.createActions()
        self.createMenus()
        self.createToolBox()

        self.scene = DiagramScene(self.itemMenu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))
        self.scene.itemInserted.connect(self.itemInserted)
        self.scene.textInserted.connect(self.textInserted)
        self.scene.itemSelected.connect(self.itemSelected)

        self.createToolbars()

        layout = QHBoxLayout()
        layout.addWidget(self.toolBox)
        self.view = QGraphicsView(self.scene)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("Diagramscene")

    def backgroundButtonGroupClicked(self, button):
        buttons = self.backgroundButtonGroup.buttons()
        for myButton in buttons:
            if myButton != button:
                button.setChecked(False)

        text = button.text()
        if text == "Blue Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background1.png')))
        elif text == "White Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background2.png')))
        elif text == "Gray Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background3.png')))
        else:
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background4.png')))

        self.scene.update()
        self.view.update()

    def buttonGroupClicked(self, id):
        buttons = self.buttonGroup.buttons()
        for button in buttons:
            if self.buttonGroup.button(id) != button:
                button.setChecked(False)

        if id == self.InsertTextButton:
            self.scene.setMode(DiagramScene.InsertText)
        else:
            self.scene.setItemType(id)
            self.scene.setMode(DiagramScene.InsertItem)

    def deleteItem(self):
        for item in self.scene.selectedItems():
            if isinstance(item, DiagramItem):
                item.removeArrows()
            self.scene.removeItem(item)

    def pointerGroupClicked(self, i):
        self.scene.setMode(self.pointerTypeGroup.checkedId())

    def bringToFront(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() >= zValue and isinstance(item, DiagramItem)):
                zValue = item.zValue() + 0.1
        selectedItem.setZValue(zValue)

    def sendToBack(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() <= zValue and isinstance(item, DiagramItem)):
                zValue = item.zValue() - 0.1
        selectedItem.setZValue(zValue)

    def itemInserted(self, item):
        self.pointerTypeGroup.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.buttonGroup.button(item.diagramType).setChecked(False)

    def textInserted(self, item):
        self.buttonGroup.button(self.InsertTextButton).setChecked(False)
        self.scene.setMode(self.pointerTypeGroup.checkedId())

    def currentFontChanged(self, font):
        self.handleFontChange()

    def fontSizeChanged(self, font):
        self.handleFontChange()

    def sceneScaleChanged(self, scale):
        newScale = scale.left(scale.indexOf("%")).toDouble()[0] / 100.0
        oldMatrix = self.view.matrix()
        self.view.resetMatrix()
        self.view.translate(oldMatrix.dx(), oldMatrix.dy())
        self.view.scale(newScale, newScale)

    def textColorChanged(self):
        self.textAction = self.sender()
        self.fontColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/textpointer.png',
                        QColor(self.textAction.data())))
        self.textButtonTriggered()

    def itemColorChanged(self):
        self.fillAction = self.sender()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon( ':/images/floodfill.png',
                        QColor(self.fillAction.data())))
        self.fillButtonTriggered()

    def lineColorChanged(self):
        self.lineAction = self.sender()
        self.lineColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/linecolor.png',
                        QColor(self.lineAction.data())))
        self.lineButtonTriggered()

    def textButtonTriggered(self):
        self.scene.setTextColor(QColor(self.textAction.data()))

    def fillButtonTriggered(self):
        self.scene.setItemColor(QColor(self.fillAction.data()))

    def lineButtonTriggered(self):
        self.scene.setLineColor(QColor(self.lineAction.data()))

    def handleFontChange(self):
        font = self.fontCombo.currentFont()
        font.setPointSize(self.fontSizeCombo.currentText().toInt()[0])
        if self.boldAction.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italicAction.isChecked())
        font.setUnderline(self.underlineAction.isChecked())

        self.scene.setFont(font)

    def itemSelected(self, item):
        font = item.font()
        color = item.defaultTextColor()
        self.fontCombo.setCurrentFont(font)
        self.fontSizeCombo.setEditText(str(font.pointSize()))
        self.boldAction.setChecked(font.weight() == QFont.Bold)
        self.italicAction.setChecked(font.italic())
        self.underlineAction.setChecked(font.underline())

    def about(self):
        QMessageBox.about(self, "About Diagram Scene",
                "The <b>Diagram Scene</b> example shows use of the graphics framework.")

    def createToolBox(self):
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonGroup.buttonClicked[int].connect(self.buttonGroupClicked)

        layout = QGridLayout()
        layout.addWidget(self.createCellWidget("Conditional", DiagramItem.Conditional),
                0, 0)
        layout.addWidget(self.createCellWidget("Process", DiagramItem.Step), 0,
                1)
        layout.addWidget(self.createCellWidget("Input/Output", DiagramItem.Io),
                1, 0)

        textButton = QToolButton()
        textButton.setCheckable(True)
        self.buttonGroup.addButton(textButton, self.InsertTextButton)
        textButton.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        textButton.setIconSize(QSize(50, 50))

        textLayout = QGridLayout()
        textLayout.addWidget(textButton, 0, 0, Qt.AlignHCenter)
        textLayout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        textWidget = QWidget()
        textWidget.setLayout(textLayout)
        layout.addWidget(textWidget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        itemWidget = QWidget()
        itemWidget.setLayout(layout)

        self.backgroundButtonGroup = QButtonGroup()
        self.backgroundButtonGroup.buttonClicked.connect(self.backgroundButtonGroupClicked)

        backgroundLayout = QGridLayout()
        backgroundLayout.addWidget(self.createBackgroundCellWidget("Blue Grid",
                ':/images/background1.png'), 0, 0)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("White Grid",
                ':/images/background2.png'), 0, 1)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("Gray Grid",
                ':/images/background3.png'), 1, 0)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("No Grid",
                ':/images/background4.png'), 1, 1)

        backgroundLayout.setRowStretch(2, 10)
        backgroundLayout.setColumnStretch(2, 10)

        backgroundWidget = QWidget()
        backgroundWidget.setLayout(backgroundLayout)

        self.toolBox = QToolBox()
        self.toolBox.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.toolBox.setMinimumWidth(itemWidget.sizeHint().width())
        self.toolBox.addItem(itemWidget, "Basic Flowchart Shapes")
        self.toolBox.addItem(backgroundWidget, "Backgrounds")

    def createActions(self):
        self.toFrontAction = QAction(
                QIcon(':/images/bringtofront.png'), "Bring to &Front",
                self, shortcut="Ctrl+F", statusTip="Bring item to front",
                triggered=self.bringToFront)

        self.sendBackAction = QAction(
                QIcon(':/images/sendtoback.png'), "Send to &Back", self,
                shortcut="Ctrl+B", statusTip="Send item to back",
                triggered=self.sendToBack)

        self.deleteAction = QAction(QIcon(':/images/delete.png'),
                "&Delete", self, shortcut="Delete",
                statusTip="Delete item from diagram",
                triggered=self.deleteItem)

        self.exitAction = QAction("E&xit", self, shortcut="Ctrl+X",
                statusTip="Quit Scenediagram example", triggered=self.close)

        self.boldAction = QAction(QIcon(':/images/bold.png'),
                "Bold", self, checkable=True, shortcut="Ctrl+B",
                triggered=self.handleFontChange)

        self.italicAction = QAction(QIcon(':/images/italic.png'),
                "Italic", self, checkable=True, shortcut="Ctrl+I",
                triggered=self.handleFontChange)

        self.underlineAction = QAction(
                QIcon(':/images/underline.png'), "Underline", self,
                checkable=True, shortcut="Ctrl+U",
                triggered=self.handleFontChange)

        self.aboutAction = QAction("A&bout", self, shortcut="Ctrl+B",
                triggered=self.about)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.exitAction)

        self.itemMenu = self.menuBar().addMenu("&Item")
        self.itemMenu.addAction(self.deleteAction)
        self.itemMenu.addSeparator()
        self.itemMenu.addAction(self.toFrontAction)
        self.itemMenu.addAction(self.sendBackAction)

        self.aboutMenu = self.menuBar().addMenu("&Help")
        self.aboutMenu.addAction(self.aboutAction)

    def createToolbars(self):
        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.deleteAction)
        self.editToolBar.addAction(self.toFrontAction)
        self.editToolBar.addAction(self.sendBackAction)

        self.fontCombo = QFontComboBox()
        self.fontCombo.currentFontChanged.connect(self.currentFontChanged)

        self.fontSizeCombo = QComboBox()
        self.fontSizeCombo.setEditable(True)
        for i in range(8, 30, 2):
            self.fontSizeCombo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.fontSizeCombo.setValidator(validator)
        self.fontSizeCombo.currentIndexChanged.connect(self.fontSizeChanged)

        self.fontColorToolButton = QToolButton()
        self.fontColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fontColorToolButton.setMenu(
                self.createColorMenu(self.textColorChanged, Qt.black))
        self.textAction = self.fontColorToolButton.menu().defaultAction()
        self.fontColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/textpointer.png',
                        Qt.black))
        self.fontColorToolButton.setAutoFillBackground(True)
        self.fontColorToolButton.clicked.connect(self.textButtonTriggered)

        self.fillColorToolButton = QToolButton()
        self.fillColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fillColorToolButton.setMenu(
                self.createColorMenu(self.itemColorChanged, Qt.white))
        self.fillAction = self.fillColorToolButton.menu().defaultAction()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/floodfill.png',
                        Qt.white))
        self.fillColorToolButton.clicked.connect(self.fillButtonTriggered)

        self.lineColorToolButton = QToolButton()
        self.lineColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.lineColorToolButton.setMenu(
                self.createColorMenu(self.lineColorChanged, Qt.black))
        self.lineAction = self.lineColorToolButton.menu().defaultAction()
        self.lineColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/linecolor.png',
                        Qt.black))
        self.lineColorToolButton.clicked.connect(self.lineButtonTriggered)

        self.textToolBar = self.addToolBar("Font")
        self.textToolBar.addWidget(self.fontCombo)
        self.textToolBar.addWidget(self.fontSizeCombo)
        self.textToolBar.addAction(self.boldAction)
        self.textToolBar.addAction(self.italicAction)
        self.textToolBar.addAction(self.underlineAction)

        self.colorToolBar = self.addToolBar("Color")
        self.colorToolBar.addWidget(self.fontColorToolButton)
        self.colorToolBar.addWidget(self.fillColorToolButton)
        self.colorToolBar.addWidget(self.lineColorToolButton)

        pointerButton = QToolButton()
        pointerButton.setCheckable(True)
        pointerButton.setChecked(True)
        pointerButton.setIcon(QIcon(':/images/pointer.png'))
        linePointerButton = QToolButton()
        linePointerButton.setCheckable(True)
        linePointerButton.setIcon(QIcon(':/images/linepointer.png'))

        self.pointerTypeGroup = QButtonGroup()
        self.pointerTypeGroup.addButton(pointerButton, DiagramScene.MoveItem)
        self.pointerTypeGroup.addButton(linePointerButton,
                DiagramScene.InsertLine)
        self.pointerTypeGroup.buttonClicked[int].connect(self.pointerGroupClicked)

        self.sceneScaleCombo = QComboBox()
        self.sceneScaleCombo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.sceneScaleCombo.setCurrentIndex(2)
        self.sceneScaleCombo.currentIndexChanged[str].connect(self.sceneScaleChanged)

        self.pointerToolbar = self.addToolBar("Pointer type")
        self.pointerToolbar.addWidget(pointerButton)
        self.pointerToolbar.addWidget(linePointerButton)
        self.pointerToolbar.addWidget(self.sceneScaleCombo)

    def createBackgroundCellWidget(self, text, image):
        button = QToolButton()
        button.setText(text)
        button.setIcon(QIcon(image))
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.backgroundButtonGroup.addButton(button)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createCellWidget(self, text, diagramType):
        item = DiagramItem(diagramType, self.itemMenu)
        icon = QIcon(item.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, diagramType)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createColorMenu(self, slot, defaultColor):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        colorMenu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.createColorIcon(color), name, self,
                    triggered=slot)
            action.setData(QColor(color)) 
            colorMenu.addAction(action)
            if color == defaultColor:
                colorMenu.setDefaultAction(action)
        return colorMenu

    def createColorToolButtonIcon(self, imageFile, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(imageFile)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    def createColorIcon(self, color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)
Esempio n. 35
0
class ToggleToolBar(QWidget):

	index = 0
	buttons = []
	rows = []
	maxRow = 7
	maxCol = 4
	selectedFrame = []
	selectedButtons = []
	def __init__(self):
		super(ToggleToolBar, self).__init__()
		self.setFixedSize(300,560)
		self.container = QVBoxLayout()
		self.container.setAlignment(Qt.AlignLeft)
		self.container.setSpacing(5)
		for i in range(0,self.maxRow):
			row = QHBoxLayout()
			row.setAlignment(Qt.AlignTop)
			row.setSpacing(5)
			self.container.addLayout(row)
			self.rows.append(row)
		self.buttonGroup = QButtonGroup()
		self.buttonGroup.setExclusive(False)
		self.setLayout(self.container)
		self.buttonGroup.buttonClicked[int].connect(self.imageSelected)
	
	def imageSelected(self,imgId):
		button = self.buttons[imgId]
		if button.pixMap in self.selectedFrame and (not button.isChecked()):
			self.selectedFrame.remove(button.pixMap)
			self.selectedButtons.remove(button)

		if (not (button.pixMap in self.selectedFrame)) and button.isChecked():
			self.selectedFrame.append(button.pixMap)
			self.selectedButtons.append(button)

	def getSelected(self):
		return self.selectedFrame

	def clearAllSelected(self):
		for button in self.selectedButtons:
			button.setChecked(False)
		self.selectedButtons = []
		self.selectedFrame = []

	def addImageButton(self,image):
		imageButton = ImageToggleButton(self.index,image)
		self.buttonGroup.addButton(imageButton,self.index)
		self.rows[self.index//self.maxCol].addWidget(imageButton)
		self.buttons.append(imageButton)
		self.index += 1

	def createImageButtons(self,imagePath):
		groupImg = QImage(imagePath)
		width = groupImg.width()
		height = groupImg.height()
		frameSize = width
		for i in range(0,height//width):
			img = groupImg.copy(0,i*frameSize,frameSize,frameSize);
			self.addImageButton(img)

	def removeAllButton(self):
		for i in range(0,self.index):
			row = self.rows[i // self.maxCol]
			row.removeWidget(self.buttons[i])
			self.buttonGroup.removeButton(self.buttons[i])
			self.buttons[i].close()
		self.buttons = []
		self.index = 0
Esempio n. 36
0
class FileDialogWizardDialog(QDialog, Ui_FileDialogWizardDialog):
    """
    Class implementing the color dialog wizard dialog.
    
    It displays a dialog for entering the parameters
    for the QFileDialog code generator.
    """
    def __init__(self, pyqtVariant, parent=None):
        """
        Constructor
        
        @param pyqtVariant variant of PyQt (integer; 0, 4 or 5)
        @param parent parent widget (QWidget)
        """
        super(FileDialogWizardDialog, self).__init__(parent)
        self.setupUi(self)
        
        self.eStartWithCompleter = E5FileCompleter(self.eStartWith)
        self.eWorkDirCompleter = E5DirCompleter(self.eWorkDir)
        
        self.__pyqtVariant = pyqtVariant
        
        self.__typeButtonsGroup = QButtonGroup(self)
        self.__typeButtonsGroup.setExclusive(True)
        self.__typeButtonsGroup.addButton(self.rOpenFile, 1)
        self.__typeButtonsGroup.addButton(self.rOpenFiles, 2)
        self.__typeButtonsGroup.addButton(self.rSaveFile, 3)
        self.__typeButtonsGroup.addButton(self.rfOpenFile, 11)
        self.__typeButtonsGroup.addButton(self.rfOpenFiles, 12)
        self.__typeButtonsGroup.addButton(self.rfSaveFile, 13)
        self.__typeButtonsGroup.addButton(self.rDirectory, 20)
        self.__typeButtonsGroup.buttonClicked[int].connect(
            self.__toggleInitialFilterAndResult)
        self.__toggleInitialFilterAndResult(1)
        
        self.pyqtComboBox.addItems(["PyQt4", "PyQt5"])
        if self.__pyqtVariant == 5:
            self.pyqtComboBox.setCurrentIndex(1)
        else:
            self.pyqtComboBox.setCurrentIndex(0)
        
        self.rSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rfSaveFile.toggled[bool].connect(self.__toggleConfirmCheckBox)
        self.rDirectory.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cStartWith.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cWorkDir.toggled[bool].connect(self.__toggleGroupsAndTest)
        self.cFilters.toggled[bool].connect(self.__toggleGroupsAndTest)
        
        self.bTest = self.buttonBox.addButton(
            self.tr("Test"), QDialogButtonBox.ActionRole)
        
        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())
    
    def __adjustOptions(self, options):
        """
        Private method to adjust the file dialog options.
        
        @param options file dialog options (QFileDialog.Options)
        @return modified options (QFileDialog.Options)
        """
        if Globals.isLinuxPlatform():
            options |= QFileDialog.DontUseNativeDialog
        return options
    
    @pyqtSlot(str)
    def on_pyqtComboBox_currentIndexChanged(self, txt):
        """
        Private slot to setup the dialog for the selected PyQt variant.
        
        @param txt text of the selected combo box entry (string)
        """
        self.rfOpenFile.setEnabled(txt == "PyQt5")
        self.rfOpenFiles.setEnabled(txt == "PyQt5")
        self.rfSaveFile.setEnabled(txt == "PyQt5")
        
        if txt == "PyQt5":
            if self.rfOpenFile.isChecked():
                self.rOpenFile.setChecked(True)
            elif self.rfOpenFiles.isChecked():
                self.rOpenFiles.setChecked(True)
            elif self.rfSaveFile.isChecked():
                self.rSaveFile.setChecked(True)
        
        self.__pyqtVariant = 5 if txt == "PyQt5" else 4
        
        self.__toggleInitialFilterAndResult(
            self.__typeButtonsGroup.checkedId())
    
    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.bTest:
            self.on_bTest_clicked()
    
    @pyqtSlot()
    def on_bTest_clicked(self):
        """
        Private method to test the selected options.
        """
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rOpenFile.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getOpenFileName(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    options)
            else:
                QFileDialog.getOpenFileNameAndFilter(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    self.eInitialFilter.text(),
                    options)
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rOpenFiles.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getOpenFileNames(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    options)
            else:
                QFileDialog.getOpenFileNamesAndFilter(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    self.eInitialFilter.text(),
                    options)
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if not self.cSymlinks.isChecked():
                options = QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            else:
                options = QFileDialog.Options()
            options = self.__adjustOptions(options)
            if self.rSaveFile.isChecked() and self.__pyqtVariant == 4:
                QFileDialog.getSaveFileName(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    options)
            else:
                QFileDialog.getSaveFileNameAndFilter(
                    None,
                    self.eCaption.text(),
                    self.eStartWith.text(),
                    self.eFilters.text(),
                    self.eInitialFilter.text(),
                    options)
        elif self.rDirectory.isChecked():
            options = QFileDialog.Options()
            if not self.cSymlinks.isChecked():
                options |= QFileDialog.Options(QFileDialog.DontResolveSymlinks)
            if self.cDirOnly.isChecked():
                options |= QFileDialog.Options(QFileDialog.ShowDirsOnly)
            else:
                options |= QFileDialog.Options(QFileDialog.Option(0))
            options = self.__adjustOptions(options)
            QFileDialog.getExistingDirectory(
                None,
                self.eCaption.text(),
                self.eWorkDir.text(),
                options)
    
    def __toggleConfirmCheckBox(self):
        """
        Private slot to enable/disable the confirmation check box.
        """
        self.cConfirmOverwrite.setEnabled(
            self.rSaveFile.isChecked() or self.rfSaveFile.isChecked())
    
    def __toggleGroupsAndTest(self):
        """
        Private slot to enable/disable certain groups and the test button.
        """
        if self.rDirectory.isChecked():
            self.filePropertiesGroup.setEnabled(False)
            self.dirPropertiesGroup.setEnabled(True)
            self.bTest.setDisabled(self.cWorkDir.isChecked())
        else:
            self.filePropertiesGroup.setEnabled(True)
            self.dirPropertiesGroup.setEnabled(False)
            self.bTest.setDisabled(
                self.cStartWith.isChecked() or self.cFilters.isChecked())
    
    def __toggleInitialFilterAndResult(self, id):
        """
        Private slot to enable/disable the initial filter elements and the
        results entries.
        
        @param id id of the clicked button (integer)
        """
        if (self.__pyqtVariant == 4 and id in [11, 12, 13]) or \
                (self.__pyqtVariant == 5 and id in [1, 2, 3]):
            enable = True
        else:
            enable = False
        self.lInitialFilter.setEnabled(enable)
        self.eInitialFilter.setEnabled(enable)
        self.cInitialFilter.setEnabled(enable)
        
        self.lFilterVariable.setEnabled(enable)
        self.eFilterVariable.setEnabled(enable)
    
    def getCode(self, indLevel, indString):
        """
        Public method to get the source code for Qt4 and Qt5.
        
        @param indLevel indentation level (int)
        @param indString string used for indentation (space or tab) (string)
        @return generated code (string)
        """
        # calculate our indentation level and the indentation string
        il = indLevel + 1
        istring = il * indString
        estring = os.linesep + indLevel * indString
        
        # now generate the code
        if self.parentSelf.isChecked():
            parent = "self"
        elif self.parentNone.isChecked():
            parent = "None"
        elif self.parentOther.isChecked():
            parent = self.parentEdit.text()
            if parent == "":
                parent = "None"
        
        # prepare the result variables
        nameVariable = self.eNameVariable.text()
        if not nameVariable:
            if self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFile, self.rfOpenFile,
                    self.rSaveFile, self.rfSaveFile]:
                nameVariable = "fileName"
            elif self.__typeButtonsGroup.checkedButton() in [
                    self.rOpenFiles, self.rfOpenFiles]:
                nameVariable = "fileNames"
            elif self.__typeButtonsGroup.checkedButton() == self.rDirectory:
                nameVariable = "dirName"
            else:
                nameVariable = "res"
        filterVariable = self.eFilterVariable.text()
        if not filterVariable:
            if (self.__pyqtVariant == 4 and
                self.__typeButtonsGroup.checkedButton() in [
                    self.rfOpenFile, self.rfOpenFiles, self.rfSaveFile]) or \
                    (self.__pyqtVariant == 5 and
                        self.__typeButtonsGroup.checkedButton() in [
                            self.rOpenFile, self.rOpenFiles, self.rSaveFile]):
                filterVariable = ", selectedFilter"
            else:
                filterVariable = ""
        
        code = '{0}{1} = QFileDialog.'.format(nameVariable, filterVariable)
        if self.rOpenFile.isChecked() or self.rfOpenFile.isChecked():
            if self.rOpenFile.isChecked():
                code += 'getOpenFileName({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if self.eFilters.text() == "":
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFile.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if not self.cSymlinks.isChecked():
                code += \
                    ',{0}{1}QFileDialog.Options(' \
                    'QFileDialog.DontResolveSymlinks)' \
                    .format(os.linesep, istring)
            code += '){0}'.format(estring)
        elif self.rOpenFiles.isChecked() or self.rfOpenFiles.isChecked():
            if self.rOpenFiles.isChecked():
                code += 'getOpenFileNames({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getOpenFileNamesAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfOpenFiles.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if not self.cSymlinks.isChecked():
                code += \
                    ',{0}{1}QFileDialog.Options(' \
                    'QFileDialog.DontResolveSymlinks)' \
                    .format(os.linesep, istring)
            code += '){0}'.format(estring)
        elif self.rSaveFile.isChecked() or self.rfSaveFile.isChecked():
            if self.rSaveFile.isChecked():
                code += 'getSaveFileName({0}{1}'.format(os.linesep, istring)
            else:
                code += 'getSaveFileNameAndFilter({0}{1}'.format(
                    os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eStartWith.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                if self.cStartWith.isChecked():
                    fmt = '{0},{1}{2}'
                else:
                    fmt = 'self.tr("{0}"),{1}{2}'
                code += fmt.format(self.eStartWith.text(), os.linesep, istring)
            if not self.eFilters.text():
                code += '""'
            else:
                if self.cFilters.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eFilters.text())
            if self.rfSaveFile.isChecked() or self.__pyqtVariant == 5:
                if self.eInitialFilter.text() == "":
                    filter = "None"
                else:
                    if self.cInitialFilter.isChecked():
                        fmt = '{0}'
                    else:
                        fmt = 'self.tr("{0}")'
                    filter = fmt.format(self.eInitialFilter.text())
                code += ',{0}{1}{2}'.format(os.linesep, istring, filter)
            if (not self.cSymlinks.isChecked()) or \
               (not self.cConfirmOverwrite.isChecked()):
                code += ',{0}{1}QFileDialog.Options('.format(
                    os.linesep, istring)
                if not self.cSymlinks.isChecked():
                    code += 'QFileDialog.DontResolveSymlinks'
                if (not self.cSymlinks.isChecked()) and \
                   (not self.cConfirmOverwrite.isChecked()):
                    code += ' | '
                if not self.cConfirmOverwrite.isChecked():
                    code += 'QFileDialog.DontConfirmOverwrite'
                code += ')'
            code += '){0}'.format(estring)
        elif self.rDirectory.isChecked():
            code += 'getExistingDirectory({0}{1}'.format(os.linesep, istring)
            code += '{0},{1}{2}'.format(parent, os.linesep, istring)
            if not self.eCaption.text():
                code += '"",{0}{1}'.format(os.linesep, istring)
            else:
                code += 'self.tr("{0}"),{1}{2}'.format(
                    self.eCaption.text(), os.linesep, istring)
            if not self.eWorkDir.text():
                code += '""'
            else:
                if self.cWorkDir.isChecked():
                    fmt = '{0}'
                else:
                    fmt = 'self.tr("{0}")'
                code += fmt.format(self.eWorkDir.text())
            code += ',{0}{1}QFileDialog.Options('.format(os.linesep, istring)
            if not self.cSymlinks.isChecked():
                code += 'QFileDialog.DontResolveSymlinks | '
            if self.cDirOnly.isChecked():
                code += 'QFileDialog.ShowDirsOnly'
            else:
                code += 'QFileDialog.Option(0)'
            code += ')){0}'.format(estring)
            
        return code
Esempio n. 37
0
class MainWindow(QMainWindow):

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

        self.createActions()
        self.createMenus()
        self.createToolBox()
        self.createStatusBar()
        
        self.scene = ITGScene(self.itemMenu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))
        self.scene.itemInserted.connect(self.itemInserted)
        self.scene.itemSelected.connect(self.itemSelected)
        
        # ================================================================
        #         THIS IS THE PROBLEM SECTION 
        # THIS CAUSES TypeError: native Qt signal is not callable
        # To reproduce the error, run the program, click on one of the 
        # shapes, then click on the scene area
        # ================================================================
        self.scene.selectionChanged.connect(self.print_item_info) # this one doesn't work

        self.createToolbars()

        layout = QHBoxLayout()
        layout.addWidget(self.toolBox)
        self.view = QGraphicsView(self.scene) # view and scene established together
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("ITG: Illegitimate Template Generator")

    #@pyqtSlot() # Adding this does not change the error
    def print_item_info(self):
        for item in self.scene.selectedItems():
            print(item)

    def buttonGroupClicked(self, id):
        buttons = self.buttonGroup.buttons()
        for button in buttons:
            if self.buttonGroup.button(id) != button:
                button.setChecked(False)

        self.scene.setItemType(id)
        self.scene.setMode(ITGScene.InsertItem)
        self.updateStatusBar()
        

    def deleteItem(self):
        for item in self.scene.selectedItems():
            self.scene.removeItem(item)

    def pointerGroupClicked(self, i):
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.updateStatusBar()

    def bringToFront(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() >= zValue and isinstance(item, ITGItem)):
                zValue = item.zValue() + 0.1
        selectedItem.setZValue(zValue)

    def sendToBack(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() <= zValue and isinstance(item, ITGItem)):
                zValue = item.zValue() - 0.1
        selectedItem.setZValue(zValue)

    def itemInserted(self, item):
        self.pointerTypeGroup.button(ITGScene.MoveItem).setChecked(True)
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.updateStatusBar()
        self.buttonGroup.button(item.ITGType).setChecked(False)

    def sceneScaleChanged(self, scale):
        newScale = scale.left(scale.indexOf("%")).toDouble()[0] / 100.0
        oldMatrix = self.view.matrix()
        self.view.resetMatrix()
        self.view.translate(oldMatrix.dx(), oldMatrix.dy())
        self.view.scale(newScale, newScale)

    def itemColorChanged(self):
        self.fillAction = self.sender()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon( ':/images/floodfill.png',
                        QColor(self.fillAction.data())))
        self.fillButtonTriggered()


    def fillButtonTriggered(self):
        self.scene.setItemColor(QColor(self.fillAction.data()))


    def itemSelected(self, item):
        font = item.font()
        color = item.defaultTextColor()
        self.fontCombo.setCurrentFont(font)
        self.fontSizeCombo.setEditText(str(font.pointSize()))
        self.boldAction.setChecked(font.weight() == QFont.Bold)
        self.italicAction.setChecked(font.italic())
        self.underlineAction.setChecked(font.underline())



    def about(self):
        QMessageBox.about(self, "About ITG Scene",
                "The <b>ITG Scene</b> example shows use of the graphics framework.")

    def createToolBox(self):
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonGroup.buttonClicked[int].connect(self.buttonGroupClicked)

        layout = QGridLayout()
        layout.addWidget(self.createCellWidget("Diamond", ITGItem.Diamond),
                0, 0)
        layout.addWidget(self.createCellWidget("Square", ITGItem.Square), 0,
                1)
        layout.addWidget(self.createCellWidget("Parallelogram", ITGItem.Parallelogram),
                1, 0)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        itemWidget = QWidget()
        itemWidget.setLayout(layout)

        self.backgroundButtonGroup = QButtonGroup()
        
        self.toolBox = QToolBox()
        self.toolBox.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.toolBox.setMinimumWidth(itemWidget.sizeHint().width())
        self.toolBox.addItem(itemWidget, "Basic Components")

    def createActions(self):
        self.toFrontAction = QAction(
                QIcon(':/images/bringtofront.png'), "Bring to &Front",
                self, shortcut="Ctrl+F", statusTip="Bring item to front",
                triggered=self.bringToFront)

        self.sendBackAction = QAction(
                QIcon(':/images/sendtoback.png'), "Send to &Back", self,
                shortcut="Ctrl+B", statusTip="Send item to back",
                triggered=self.sendToBack)

        self.deleteAction = QAction(QIcon(':/images/delete.png'),
                "&Delete", self, shortcut="Delete",
                statusTip="Delete item from ITG",
                triggered=self.deleteItem)

        self.exitAction = QAction("E&xit", self, shortcut="Ctrl+X",
                statusTip="Quit SceneITG example", triggered=self.close)

        self.aboutAction = QAction("A&bout", self, shortcut="Ctrl+B",
                triggered=self.about)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.exitAction)

        self.itemMenu = self.menuBar().addMenu("&Item")
        self.itemMenu.addAction(self.deleteAction)
        self.itemMenu.addSeparator()
        self.itemMenu.addAction(self.toFrontAction)
        self.itemMenu.addAction(self.sendBackAction)

        self.aboutMenu = self.menuBar().addMenu("&Help")
        self.aboutMenu.addAction(self.aboutAction)

    def createToolbars(self):
        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.deleteAction)
        self.editToolBar.addAction(self.toFrontAction)
        self.editToolBar.addAction(self.sendBackAction)

        self.fillColorToolButton = QToolButton()
        self.fillColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fillColorToolButton.setMenu(
                self.createColorMenu(self.itemColorChanged, Qt.red))
        self.fillAction = self.fillColorToolButton.menu().defaultAction()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/floodfill.png',
                        Qt.red))
        self.fillColorToolButton.clicked.connect(self.fillButtonTriggered)

        self.colorToolBar = self.addToolBar("Color")
        self.colorToolBar.addWidget(self.fillColorToolButton)
        

        pointerButton = QToolButton()
        pointerButton.setCheckable(True)
        pointerButton.setChecked(True)
        pointerButton.setIcon(QIcon(':/images/pointer.png'))

        self.pointerTypeGroup = QButtonGroup()
        self.pointerTypeGroup.addButton(pointerButton, ITGScene.MoveItem)
        self.pointerTypeGroup.buttonClicked[int].connect(self.pointerGroupClicked)

        self.sceneScaleCombo = QComboBox()
        self.sceneScaleCombo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.sceneScaleCombo.setCurrentIndex(2)
        self.sceneScaleCombo.currentIndexChanged[str].connect(self.sceneScaleChanged)

        self.pointerToolbar = self.addToolBar("Pointer type")
        self.pointerToolbar.addWidget(pointerButton)
        self.pointerToolbar.addWidget(self.sceneScaleCombo)

    def createBackgroundCellWidget(self, text, image):
        button = QToolButton()
        button.setText(text)
        button.setIcon(QIcon(image))
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.backgroundButtonGroup.addButton(button)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createCellWidget(self, text, ITGType):
        item = ITGItem(ITGType, self.itemMenu)
        icon = QIcon(item.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, ITGType)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createColorMenu(self, slot, defaultColor):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        colorMenu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.createColorIcon(color), name, self,
                    triggered=slot)
            action.setData(QColor(color)) 
            colorMenu.addAction(action)
            if color == defaultColor:
                colorMenu.setDefaultAction(action)
        return colorMenu

    def createColorToolButtonIcon(self, imageFile, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(imageFile)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    def createColorIcon(self, color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)

    def createStatusBar(self):
        self.sbar = self.statusBar()
        
        self.lbl_mode = QLabel('Mode: not set')
        self.sbar.addPermanentWidget(self.lbl_mode)

        self.lbl_selection = QLabel('Sel: none')
        self.sbar.addPermanentWidget(self.lbl_selection)

    def updateStatusBar(self):
        self.lbl_mode.setText('Mode: ' + self.scene.getMode())
        #! This section is not working!!!
        if len(self.scene.selectedItems()) == 0:
            self.lbl_selection.setText('Sel: none')
        elif len(self.scene.selectedItems()) == 1:
            self.lbl_selection.setText('Sel: ' + self.scene.selectedItems()[0].get_ITGType_as_str())
        elif len(self.scene.selectedItems()) > 1:
            self.lbl_selection.setText('Sel: <multiple>')
Esempio n. 38
0
class AudioVideoTab(QWidget):
    def __init__(self, parent):
        super(AudioVideoTab, self).__init__(parent)
        self.parent = parent
        self.name = 'AudioVideo'

        self.defaultStr = self.tr('Default')
        self.DisableStream = self.tr('Disable')

        self.formats = config.video_formats
        frequency_values = [self.defaultStr] + config.video_frequency_values
        bitrate_values = [self.defaultStr] + config.video_bitrate_values

        rotation_options = [
                self.tr('None'),
                '90 ' + self.tr('clockwise'),
                '90 ' + self.tr('clockwise') + ' + ' + self.tr('vertical flip'),
                '90 ' + self.tr('counter clockwise'),
                '90 ' + self.tr('counter clockwise') +
                ' + ' + self.tr('vertical flip'),
                '180',
                self.tr('horizontal flip'),
                self.tr('vertical flip')
                ]

        digits_validator = QRegExpValidator(QRegExp(r'[1-9]\d*'), self)
        digits_validator_wzero = QRegExpValidator(QRegExp(r'\d*'), self)
        digits_validator_minus = QRegExpValidator(QRegExp(r'(-1|[1-9]\d*)'), self)
        time_validator = QRegExpValidator(
                QRegExp(r'\d{1,2}:\d{1,2}:\d{1,2}\.\d+'), self)

        converttoQL = QLabel(self.tr('Convert to:'))
        self.extQCB = QComboBox()
        self.extQCB.setMinimumWidth(100)
        vidcodecQL = QLabel('Video codec:')
        self.vidcodecQCB = QComboBox()
        self.vidcodecQCB.setMinimumWidth(110)
        audcodecQL = QLabel('Audio codec:')
        self.audcodecQCB = QComboBox()
        self.audcodecQCB.setMinimumWidth(110)

        hlayout1 = utils.add_to_layout(
                'h', converttoQL, self.extQCB, QSpacerItem(180, 20),
                vidcodecQL, self.vidcodecQCB, audcodecQL, self.audcodecQCB)

        commandQL = QLabel(self.tr('Command:'))
        self.commandQLE = QLineEdit()
        self.presetQPB = QPushButton(self.tr('Preset'))
        self.defaultQPB = QPushButton(self.defaultStr)
        hlayout2 = utils.add_to_layout(
                'h', commandQL, self.commandQLE, self.presetQPB,
                self.defaultQPB)

        sizeQL = QLabel(self.tr('Video Size:'))
        aspectQL = QLabel(self.tr('Aspect:'))
        frameQL = QLabel(self.tr('Frame Rate (fps):'))
        bitrateQL = QLabel(self.tr('Video Bitrate (kbps):'))

        self.widthQLE = utils.create_LineEdit(
                (70, 16777215), digits_validator_minus, 4)
        self.heightQLE = utils.create_LineEdit(
                (70, 16777215), digits_validator_minus, 4)
        label = QLabel('<html><p align="center">x</p></html>')
        layout1 = utils.add_to_layout('h', self.widthQLE, label,self.heightQLE)
        self.aspect1QLE = utils.create_LineEdit(
                (50, 16777215), digits_validator, 2)
        self.aspect2QLE = utils.create_LineEdit(
                (50, 16777215), digits_validator, 2)
        label = QLabel('<html><p align="center">:</p></html>')
        layout2 = utils.add_to_layout(
                'h', self.aspect1QLE, label, self.aspect2QLE)
        self.frameQLE = utils.create_LineEdit(
                (120, 16777215), digits_validator, 4)
        self.bitrateQLE = utils.create_LineEdit(
                (130, 16777215), digits_validator, 6)

        labels = [sizeQL, aspectQL, frameQL, bitrateQL]
        widgets = [layout1, layout2, self.frameQLE, self.bitrateQLE]

        self.preserveaspectQChB = QCheckBox(self.tr("Preserve aspect ratio"))
        self.preservesizeQChB = QCheckBox(self.tr("Preserve video size"))

        preserve_layout = utils.add_to_layout(
                'v', self.preserveaspectQChB, self.preservesizeQChB)

        videosettings_layout = QHBoxLayout()
        for a, b in zip(labels, widgets):
            a.setText('<html><p align="center">{0}</p></html>'.format(a.text()))
            layout = utils.add_to_layout('v', a, b)
            videosettings_layout.addLayout(layout)
            if a == aspectQL:
                # add vidaspectCB in layout after aspectQL
                videosettings_layout.addLayout(preserve_layout)

        freqQL = QLabel(self.tr('Frequency (Hz):'))
        chanQL = QLabel(self.tr('Audio Channels:'))
        bitrateQL = QLabel(self.tr('Audio Bitrate (kbps):'))
        threadsQL = QLabel(self.tr('Threads:'))

        self.freqQCB = QComboBox()
        self.freqQCB.addItems(frequency_values)
        self.chan1QRB = QRadioButton('1')
        self.chan1QRB.setMaximumSize(QSize(51, 16777215))
        self.chan2QRB = QRadioButton('2')
        self.chan2QRB.setMaximumSize(QSize(51, 16777215))
        self.group = QButtonGroup()
        self.group.addButton(self.chan1QRB)
        self.group.addButton(self.chan2QRB)
        spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum)
        spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum)
        chanlayout = utils.add_to_layout(
                'h', spcr1, self.chan1QRB, self.chan2QRB, spcr2)
        self.audbitrateQCB = QComboBox()
        self.audbitrateQCB.addItems(bitrate_values)
        self.threadsQLE = utils.create_LineEdit(
                (50, 16777215), digits_validator_wzero, 1)

        labels = [freqQL, bitrateQL, chanQL, threadsQL]
        widgets = [self.freqQCB, self.audbitrateQCB, chanlayout,self.threadsQLE]

        audiosettings_layout = QHBoxLayout()
        for a, b in zip(labels, widgets):
            a.setText('<html><p align="center">{0}</p></html>'.format(a.text()))
            layout = utils.add_to_layout('v', a, b)
            audiosettings_layout.addLayout(layout)

        time_format = " (hh:mm:ss):"
        beginQL = QLabel(self.tr("Split file. Begin time") + time_format)
        self.beginQLE = utils.create_LineEdit(None, time_validator, None)
        durationQL = QLabel(self.tr("Duration") + time_format)
        self.durationQLE = utils.create_LineEdit(None, time_validator, None)

        hlayout4 = utils.add_to_layout(
                'h',  beginQL, self.beginQLE, durationQL, self.durationQLE)

        embedQL = QLabel(self.tr("Embed subtitle:"))
        self.embedQLE = QLineEdit()
        self.embedQTB = QToolButton()
        self.embedQTB.setText("...")

        rotateQL = QLabel(self.tr("Rotate:"))
        self.rotateQCB = QComboBox()
        self.rotateQCB.addItems(rotation_options)

        hlayout5 = utils.add_to_layout(
                'h', rotateQL, self.rotateQCB, embedQL, self.embedQLE,
                self.embedQTB)

        hidden_layout = utils.add_to_layout(
                'v', videosettings_layout, audiosettings_layout,
                hlayout4, hlayout5)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.moreQPB = QPushButton(QApplication.translate('Tab', 'More'))
        self.moreQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.moreQPB.setCheckable(True)
        hlayout3 = utils.add_to_layout('h', line, self.moreQPB)

        self.frame = QFrame()
        self.frame.setLayout(hidden_layout)
        self.frame.hide()

        final_layout = utils.add_to_layout(
                'v', hlayout1, hlayout2, hlayout3, self.frame)
        self.setLayout(final_layout)

        self.presetQPB.clicked.connect(self.choose_preset)
        self.defaultQPB.clicked.connect(self.set_default_command)
        self.embedQTB.clicked.connect(self.open_subtitle_file)
        self.moreQPB.toggled.connect(self.frame.setVisible)
        self.moreQPB.toggled.connect(
                lambda: QTimer.singleShot(100, self.resize_parent))
        self.widthQLE.textChanged.connect(self.command_update_size)
        self.heightQLE.textChanged.connect(self.command_update_size)
        self.aspect1QLE.textChanged.connect(self.command_update_aspect)
        self.aspect2QLE.textChanged.connect(self.command_update_aspect)
        self.frameQLE.textChanged.connect(self.command_update_frames)
        self.bitrateQLE.textChanged.connect(self.command_update_vidbitrate)
        self.threadsQLE.textChanged.connect(self.command_update_threads)
        self.beginQLE.textChanged.connect(self.command_update_begin_time)
        self.durationQLE.textChanged.connect(self.command_update_duration)
        self.embedQLE.textChanged.connect(self.command_update_subtitles)
        self.vidcodecQCB.currentIndexChanged.connect(self.command_update_vcodec)
        self.audcodecQCB.currentIndexChanged.connect(self.command_update_acodec)
        self.freqQCB.currentIndexChanged.connect(self.command_update_frequency)
        self.rotateQCB.currentIndexChanged.connect(self.command_update_rotation)
        self.audbitrateQCB.currentIndexChanged.connect(
                self.command_update_audbitrate)
        self.chan1QRB.clicked.connect(
                lambda: self.command_update_channels('1'))
        self.chan2QRB.clicked.connect(
                lambda: self.command_update_channels('2'))
        self.preserveaspectQChB.toggled.connect(
                self.command_update_preserve_aspect)
        self.preservesizeQChB.toggled.connect(
                self.command_update_preserve_size)

    def resize_parent(self):
        """Give MainWindow its default size."""
        self.parent.setMinimumSize(self.parent.sizeHint())
        self.parent.resize(self.parent.sizeHint())

    def clear(self):
        """Clear all values of graphical widgets."""
        lines = [
                self.commandQLE, self.widthQLE, self.heightQLE,
                self.aspect1QLE, self.aspect2QLE, self.frameQLE,
                self.bitrateQLE, self.threadsQLE, self.beginQLE,
                self.embedQLE, self.durationQLE
                ]
        for i in lines:
            i.clear()

        self.vidcodecQCB.setCurrentIndex(0)
        self.audcodecQCB.setCurrentIndex(0)
        self.freqQCB.setCurrentIndex(0)
        self.audbitrateQCB.setCurrentIndex(0)
        self.rotateQCB.setCurrentIndex(0)
        self.preserveaspectQChB.setChecked(False)
        self.preservesizeQChB.setChecked(False)
        self.group.setExclusive(False)
        self.chan1QRB.setChecked(False)
        self.chan2QRB.setChecked(False)
        self.group.setExclusive(True)
        # setExclusive(False) in order to be able to uncheck checkboxes and
        # then setExclusive(True) so only one radio button can be set

    def fill_video_comboboxes(self, vcodecs, acodecs, extraformats):
        self.vidcodecQCB.currentIndexChanged.disconnect()
        self.audcodecQCB.currentIndexChanged.disconnect()

        self.vidcodecQCB.clear()
        self.audcodecQCB.clear()
        self.extQCB.clear()
        self.vidcodecQCB.addItems([self.defaultStr, self.DisableStream] + vcodecs)
        self.audcodecQCB.addItems([self.defaultStr, self.DisableStream] + acodecs)
        self.extQCB.addItems(sorted(self.formats + extraformats))

        self.vidcodecQCB.currentIndexChanged.connect(self.command_update_vcodec)
        self.audcodecQCB.currentIndexChanged.connect(self.command_update_acodec)

    def ok_to_continue(self):
        """
        Check if everything is ok with audiovideotab to continue conversion.
        Returns boolean.
        """
        if not self.parent.ffmpeg_path:
            QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr(
                'Error!'), self.tr('FFmpeg is not installed!'))
            return False
        return True

    def open_subtitle_file(self):
        fname = QFileDialog.getOpenFileName(
                self, 'FF Multi Converter - ' + self.tr('Choose File'),
                config.home, 'Subtitles (*.srt *.sub *.ssa *.ass)'
                )[0]
        if fname:
            self.embedQLE.setText(fname)

    def set_default_command(self):
        """Set the default value to self.commandQLE."""
        self.clear()
        self.commandQLE.setText(self.parent.default_command)

    def choose_preset(self):
        """
        Open the presets dialog and update self.commandQLE,
        and self.extQCB and with the appropriate values.
        """
        dialog = presets_dlgs.ShowPresets(choose=True)
        if dialog.exec_() and dialog.the_command is not None:
            self.clear()
            self.commandQLE.setText(dialog.the_command)
            self.commandQLE.home(False)
            find = self.extQCB.findText(dialog.the_extension)
            if find >= 0:
                self.extQCB.setCurrentIndex(find)

    def command_update_size(self):
        command = self.commandQLE.text()
        text1 = self.widthQLE.text()
        text2 = self.heightQLE.text()

        if not (text1 == '-1' or text2 == '-1'):
            self.preserveaspectQChB.setChecked(False)

        if (text1 or text2) and not (text1 and text2) or (text1 == '-' or
                text2 == '-'):
            return

        regex = r'(\s+|^)-s(:v){0,1}\s+\d+x\d+(\s+|$)'
        if re.search(regex, command):
            command = re.sub(regex, '', command)

        regex = r'(,*\s*){0,1}(scale=-?\d+:-?\d+)(\s*,*\s*){0,1}'
        _filter = "scale={0}:{1}".format(text1, text2) if text1 and text2 else ''

        self.commandQLE.setText(utils.update_cmdline_text(
                command, _filter, regex, bool(text1 and text2), 0, 2))

    def command_update_preserve_size(self):
        checked = self.preservesizeQChB.isChecked()

        self.widthQLE.setEnabled(not checked)
        self.heightQLE.setEnabled(not checked)

        if checked:
            self.widthQLE.clear()
            self.heightQLE.clear()
            # command_update_size() is triggered here

        command = self.commandQLE.text()
        regex = r'(\s+|^)-s\s+\d+x\d+(\s+|$)'
        command = re.sub(' +', ' ', re.sub(regex, ' ', command)).strip()
        self.commandQLE.setText(command)

    def command_update_aspect(self):
        command = self.commandQLE.text()
        text1 = self.aspect1QLE.text()
        text2 = self.aspect2QLE.text()

        if (text1 or text2) and not (text1 and text2):
            return

        regex = r'(\s+|^)-aspect\s+\d+:\d+(\s+|$)'
        s = ' -aspect {0}:{1} '.format(text1, text2) if text1 and text2 else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_preserve_aspect(self):
        command = self.commandQLE.text()
        checked = self.preserveaspectQChB.isChecked()

        self.aspect1QLE.setEnabled(not checked)
        self.aspect2QLE.setEnabled(not checked)

        if checked:
            self.aspect1QLE.clear()
            self.aspect2QLE.clear()
            # self.command_update_aspect() is triggered here

            regex = r'(,*\s*){0,1}(scale=(-?\d+):(-?\d+))(\s*,*\s*){0,1}'
            search = re.search(regex, command)
            if search:
                width = search.groups()[2]
                height = search.groups()[3]
                if not (width == '-1' or height == '-1'):
                    s = "scale=-1:{0}".format(height)
                    command = re.sub(regex, r'\1{0}\5'.format(s), command)
                    self.widthQLE.setText('-1')
                    self.heightQLE.setText(height)

        regex = r'(\s+|^)-aspect\s+\d+:\d+(\s+|$)'
        command = re.sub(' +', ' ', re.sub(regex, ' ', command)).strip()
        self.commandQLE.setText(command)

    def command_update_frames(self):
        command = self.commandQLE.text()
        text = self.frameQLE.text()

        regex = r'(\s+|^)-r\s+\d+(\s+|$)'
        s = ' -r {0} '.format(text) if text else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_vidbitrate(self):
        command = self.commandQLE.text()
        text = self.bitrateQLE.text()

        regex = r'(\s+|^)-b(:v){0,1}\s+\d+[kKmM](\s+|$)'
        s = ' -b:v {0}k '.format(text) if text else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub('-sameq', '', command)
        command = re.sub(' +', ' ', command).strip()

        self.commandQLE.setText(command)

    def command_update_frequency(self):
        command = self.commandQLE.text()
        text = self.freqQCB.currentText()

        regex = r'(\s+|^)-ar\s+\d+(\s+|$)'
        s = ' -ar {0} '.format(text) if self.freqQCB.currentIndex() != 0 else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_audbitrate(self):
        command = self.commandQLE.text()
        text = self.audbitrateQCB.currentText()

        regex = r'(\s+|^)-(ab|b:a)\s+\d+[kKmM](\s+|$)'
        if self.audbitrateQCB.currentIndex() != 0:
            s = ' -b:a {0}k '.format(text)
        else:
            s = ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_channels(self, channel):
        command = self.commandQLE.text()

        regex = r'(\s+|^)-ac\s+\d+(\s+|$)'
        s = ' -ac {0} '.format(channel)

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_threads(self):
        command = self.commandQLE.text()
        text = self.threadsQLE.text()

        regex = r'(\s+|^)-threads\s+\d+(\s+|$)'
        s = ' -threads {0} '.format(text) if text else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_begin_time(self):
        command = self.commandQLE.text()
        text = self.beginQLE.text()

        regex = r'(\s+|^)-ss\s+\S+(\s+|$)'
        s = ' -ss {0} '.format(text) if text else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_duration(self):
        command = self.commandQLE.text()
        text = self.durationQLE.text()

        regex = r'(\s+|^)-t\s+\S+(\s+|$)'
        s = ' -t {0} '.format(text) if text else ' '

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_vcodec(self):
        command = self.commandQLE.text()
        text = self.vidcodecQCB.currentText()

        regex = r'(\s+|^)-(vcodec|c:v)\s+\S+(\s+|$)'
        regex_vn = r'(\s+|^)-vn(\s+|$)'
        if self.vidcodecQCB.currentIndex() == 1:
            s = ' -vn '.format(text)
        elif self.vidcodecQCB.currentIndex() == 0:
            s = ' '
        else:
            s = ' -vcodec {0} '.format(text)

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        elif re.search(regex_vn, command):
            command = re.sub(regex_vn, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_acodec(self):
        command = self.commandQLE.text()
        text = self.audcodecQCB.currentText()

        regex = r'(\s+|^)-(acodec|c:a)\s+\S+(\s+|$)'
        regex_an = r'(\s+|^)-an(\s+|$)'
        if self.audcodecQCB.currentIndex() == 1:
            s = ' -an '.format(text)
        elif self.audcodecQCB.currentIndex() == 0:
            s = ' '
        else:
            s = ' -acodec {0} '.format(text)

        if re.search(regex, command):
            command = re.sub(regex, s, command)
        elif re.search(regex_an, command):
            command = re.sub(regex_an, s, command)
        else:
            command += s

        command = re.sub(' +', ' ', command).strip()
        self.commandQLE.setText(command)

    def command_update_subtitles(self):
        command = self.commandQLE.text()
        regex = r'(,*\s*){0,1}(subtitles=\'.*\')(\s*,*\s*){0,1}'

        text = self.embedQLE.text()
        _filter = "subtitles='{0}'".format(text) if text else ''

        self.commandQLE.setText(utils.update_cmdline_text(
                command, _filter, regex, bool(text), 0, 2))

    def command_update_rotation(self):
        command = self.commandQLE.text()
        regex = r'(,*\s*){0,1}(transpose=\d(,\s*transpose=\d)*|vflip|hflip)(\s*,*\s*){0,1}'

        rotate = self.rotateQCB.currentIndex()
        if rotate == 0:   # none
            _filter = ''
        elif rotate == 1: # 90 clockwise
            _filter = 'transpose=1'
        elif rotate == 2: # 90 clockwise + vertical flip
            _filter = 'transpose=3'
        elif rotate == 3: # 90 counter clockwise
            _filter = 'transpose=2'
        elif rotate == 4: # 90 counter clockwise + vertical flip
            _filter = 'transpose=0'
        elif rotate == 5: # 180
            _filter = 'transpose=2,transpose=2'
        elif rotate == 6: # horizontal flip
            _filter = 'hflip'
        elif rotate == 7: # vertical flip
            _filter = 'vflip'

        self.commandQLE.setText(utils.update_cmdline_text(
                command, _filter, regex, bool(rotate != 0), 0, 3))
class PlotWidget(QtWidgets.QWidget, plot_widget_class):
    """Wrapper widget for PyQtGraph adding some extra buttons"""

    def __init__(self, parent=None, fps=100, title="", *args):
        super(PlotWidget, self).__init__(*args)
        self.setupUi(self)

        # Limit the plot update to 10Hz
        self._ts = time()
        self._delay = 0.1

        # Check if we could import PyQtGraph, if not then stop here
        if not _pyqtgraph_found:
            self.can_enable = False
            return
        else:
            self.can_enable = True

        self._items = {}
        self._last_item = 0

        self.setSizePolicy(QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding))

        self.setMinimumSize(self.minimumSizeHint())
        self.parent = parent

        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        self._plot_widget = pg.PlotWidget()
        self._plot_widget.hideButtons()
        self._plot_widget.setLabel('bottom', "Time", "ms")
        self._plot_widget.addLegend()
        self._plot_widget.getViewBox().disableAutoRange(ViewBox.XAxis)
        self._plot_widget.getViewBox().sigRangeChangedManually.connect(
            self._manual_range_change)
        self._plot_widget.getViewBox().setMouseEnabled(x=False, y=True)
        self._plot_widget.getViewBox().setMouseMode(ViewBox.PanMode)

        self.plotLayout.addWidget(self._plot_widget)

        # self.saveToFile.clicked.connect(self.saveToFileSignal)
        self._x_min = 0
        self._x_max = 500
        self._enable_auto_y.setChecked(True)
        self._enable_samples_x.setChecked(True)
        self._last_ts = None
        self._dtime = None

        self._x_range = (
            float(self._range_x_min.text()), float(self._range_x_max.text()))
        self._nbr_samples = int(self._nbr_of_samples_x.text())

        self._nbr_of_samples_x.valueChanged.connect(self._nbr_samples_changed)
        self._range_y_min.valueChanged.connect(self._y_range_changed)
        self._range_y_max.valueChanged.connect(self._y_range_changed)

        self._y_btn_group = QButtonGroup()
        self._y_btn_group.addButton(self._enable_auto_y)
        self._y_btn_group.addButton(self._enable_range_y)
        self._y_btn_group.setExclusive(True)
        self._y_btn_group.buttonClicked.connect(self._y_mode_change)

        self._x_btn_group = QButtonGroup()
        self._x_btn_group.addButton(self._enable_range_x)
        self._x_btn_group.addButton(self._enable_samples_x)
        self._x_btn_group.addButton(self._enable_seconds_x)
        self._x_btn_group.addButton(self._enable_manual_x)
        self._x_btn_group.setExclusive(True)
        self._x_btn_group.buttonClicked.connect(self._x_mode_change)

        self._draw_graph = True
        self._auto_redraw.stateChanged.connect(self._auto_redraw_change)

    def _auto_redraw_change(self, state):
        """Callback from the auto redraw checkbox"""
        if state == 0:
            self._draw_graph = False
        else:
            self._draw_graph = True

    def _x_mode_change(self, box):
        """Callback when user changes the X-axis mode"""
        if box == self._enable_range_x:
            logger.info("Enable range x")
            self._x_range = (
                float(self._range_x_min.text()),
                float(self._range_x_max.text()))
        else:
            self._range_x_min.setEnabled(False)
            self._range_x_max.setEnabled(False)

    def _y_mode_change(self, box):
        """Callback when user changes the Y-axis mode"""
        if box == self._enable_range_y:
            self._range_y_min.setEnabled(True)
            self._range_y_max.setEnabled(True)
            y_range = (
                float(self._range_y_min.value()),
                float(self._range_y_max.value()))
            self._plot_widget.getViewBox().setRange(yRange=y_range)
        else:
            self._range_y_min.setEnabled(False)
            self._range_y_max.setEnabled(False)

        if box == self._enable_auto_y:
            self._plot_widget.getViewBox().enableAutoRange(ViewBox.YAxis)

    def _manual_range_change(self, obj):
        """
        Callback from pyqtplot when users changes the range of the plot using
        the mouse
        """
        [[x_min, x_max],
         [y_min, y_max]] = self._plot_widget.getViewBox().viewRange()
        self._range_y_min.setValue(y_min)
        self._range_y_max.setValue(y_max)
        self._range_y_min.setEnabled(True)
        self._range_y_max.setEnabled(True)
        self._enable_range_y.setChecked(True)

    def _y_range_changed(self, val):
        """Callback when user changes Y range manually"""
        _y_range = (
            float(self._range_y_min.value()),
            float(self._range_y_max.value()))
        self._plot_widget.getViewBox().setRange(yRange=_y_range, padding=0)

    def _nbr_samples_changed(self, val):
        """Callback when user changes the number of samples to be shown"""
        self._nbr_samples = val

    def set_title(self, title):
        """
        Set the title of the plot.

        title - the new title
        """
        self._plot_widget.setTitle(title)

    def add_curve(self, title, pen='r'):
        """
        Add a new curve to the plot.

        title - the name of the data
        pen - color of curve (using r for red and so on..)
        """
        self._items[title] = PlotItemWrapper(
            self._plot_widget.plot(name=title, pen=pen))

    def add_data(self, data, ts):
        """
        Add new data to the plot.

        data - dictionary sent from logging layer containing variable/value
               pairs
        ts - timestamp of the data in ms
        """
        if not self._last_ts:
            self._last_ts = ts
        elif not self._last_ts:
            self._dtime = ts - self._last_ts
            self._last_ts = ts

        x_min_limit = 0
        x_max_limit = 0
        # We are adding new datasets, calculate what we should show.
        if self._enable_samples_x.isChecked():
            x_min_limit = max(0, self._last_item - self._nbr_samples)
            x_max_limit = max(self._last_item, self._nbr_samples)

        for name in self._items:
            self._items[name].add_point(data[name], ts)
            if self._draw_graph and time() > self._ts + self._delay:
                [self._x_min, self._x_max] = self._items[name].show_data(
                    x_min_limit, x_max_limit)
        if time() > self._ts + self._delay:
            self._ts = time()
        if (self._enable_samples_x.isChecked() and self._dtime and
                self._last_item < self._nbr_samples):
            self._x_max = self._x_min + self._nbr_samples * self._dtime

        self._last_item = self._last_item + 1
        self._plot_widget.getViewBox().setRange(
            xRange=(self._x_min, self._x_max))

    def removeAllDatasets(self):
        """Reset the plot by removing all the datasets"""
        for item in self._items:
            self._plot_widget.removeItem(self._items[item])

        self._clear_legend()

        self._items = {}
        self._last_item = 0
        self._last_ts = None
        self._dtime = None
        self._plot_widget.clear()

    def _clear_legend(self):
        legend = self._plot_widget.plotItem.legend

        while legend.layout.count() > 0:
            item = legend.items[0]
            name = item[1].text
            legend.removeItem(name)
Esempio n. 40
0
class DataCheck(Content):

    def __init__(self, parent=None, button_func=None, params=None):
        super().__init__(parent, 'Data check', params)

        self.button_func = button_func

        path = os.path.abspath(os.path.dirname(__file__)) + '/static/'

        # nr = min(5, data.shape[0])
        nr = len(self.params.data5)

        if params.lang == 'jp':
            text = ('データの読み込み結果(先頭{n}行)を以下に示します.\n'
                    'データを正しく読み込めていることを確認してください.'.format(n=nr))
            self.set_paragraph(
                'データ読み込み結果の確認', text=text)
        else:
            text = ('First {n} rows of your data are shown below.\n'
                    'Confirm that the data was read correctly.'.format(n=nr))
            self.set_paragraph(
                'Check data', text=text)

        table = NonScrollTable(self.inner)

        table.setRowCount(nr)
        table.setColumnCount(len(self.params.columns))
        table.setHorizontalHeaderLabels(self.params.columns)

        for r in range(nr):
            for c in range(len(self.params.columns)):
                item = QTableWidgetItem(str(self.params.data5.iat[r, c]))
                item.setFlags(Qt.ItemIsEnabled)
                table.setItem(r, c, item)

        table.setNonScroll()

        self.vbox.addWidget(table)

        # Text for type checking and objective variable setting
        path1 = path + 'categorical'
        text = self.get_text(path1)
        if self.params.lang == 'en':
            self.set_paragraph(
                'Check type of variables and set objective variable',
                text=text)
        else:
            self.set_paragraph('変数タイプの確認と目的変数の設定', text=text)

        # htable = QTableWidget(self.inner)
        htable = NonScrollTable(self.inner)

        htable.setRowCount(len(self.params.columns))
        htable.setColumnCount(4)
        htable.setHorizontalHeaderLabels(
            ['columns', 'categorical', 'numerical', 'target'])

        self.lst_cat = []
        self.lst_num = []
        self.lst_obj = []
        self.obj_group = QButtonGroup(self.inner)
        for c in range(len(self.params.columns)):
            # col 1
            item = QTableWidgetItem(self.params.columns[c])
            item.setFlags(Qt.ItemIsEnabled)
            htable.setItem(c, 0, item)

            group = QButtonGroup(self.inner)

            # col 2
            htable.setCellWidget(
                c, 1,
                self.__make_cell(c, 'cat', self.params.col_types[c],
                                 self.params.col_types_def[c]))
            group.addButton(self.lst_cat[-1])

            # col 3
            htable.setCellWidget(
                c, 2,
                self.__make_cell(c, 'num', self.params.col_types[c],
                                 self.params.col_types_def[c]))
            group.addButton(self.lst_num[-1])

            # col 4
            htable.setCellWidget(
                c, 3,
                self.__make_cell(c, 'obj', self.params.col_types[c],
                                 self.params.col_types_def[c]))
            self.obj_group.addButton(self.lst_obj[-1])
            self.obj_group.setId(self.lst_obj[-1], c)

        htable.setNonScroll()

        self.vbox.addWidget(htable)

        if self.params.lang == 'jp':
            self.txt_cnf = ('<font color="red">目的変数を1つ選択し,'
                    'targetの列にチェックをいれてください。')
            if self.params.task.lower() == 'classification':
                self.txt_cnf += '<br>目的変数はカテゴリ変数である必要があります。</font>'
            else:
                self.txt_cnf += '<br>目的変数は量的変数である必要があります。</font>'
        else:
            self.txt_cnf = ('<font color="red">Select one variable as target variable,'
                            'then set the column of "target" of the variable checked.')
            if self.params.task.lower() == 'classification':
                self.txt_cnf += '<br>Target variable must be a categorical variable.</font>'
            else:
                self.txt_cnf += '<br>Target variable must be a numerical variable.</font>'
        self.lbl_cnf = QLabel(self.txt_cnf, self.inner)

        self.vbox.addWidget(self.lbl_cnf)

        self.vbox.addStretch(1)

        self.btn = QPushButton('Next', self.inner)
        self.btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
        if self.params.lang == 'en':
            self.btn.clicked.connect(lambda: self.button_func('Overfitting'))
        else:
            self.btn.clicked.connect(lambda: self.button_func('過学習'))
        if self.obj_group.checkedButton() is None:
            self.btn.setEnabled(False)
        else:
            self.btn.setEnabled(True)

        self.vbox.addWidget(self.btn)

    def __make_cell(self, c, name, col_type, col_type_def):
        cell = QWidget(self.inner)
        rbtn = QRadioButton('', cell)
        rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c)))
        hbl = QHBoxLayout(cell)
        hbl.addWidget(rbtn)
        hbl.setContentsMargins(0, 0, 0, 0)
        hbl.setAlignment(Qt.AlignCenter)
        cell.setLayout(hbl)
        if name == 'cat':
            if col_type == 'object':
                rbtn.setChecked(True)
            self.lst_cat.append(rbtn)
        elif name == 'num':
            if col_type != 'object':
                rbtn.setChecked(True)
            if col_type_def == 'object':
                rbtn.setEnabled(False)
            self.lst_num.append(rbtn)
        elif name == 'obj':
            if col_type == 'object' and self.params.task == 'Regression':
                rbtn.setEnabled(False)
            elif col_type != 'object' and self.params.task == 'Classification':
                rbtn.setEnabled(False)
            if self.params.columns[c] == self.params.objective:
                rbtn.setChecked(True)
            self.lst_obj.append(rbtn)

        return cell

    def rbtn_clicked(self, text):
        name, idx = text.split('_')
        idx = int(idx)
        if len(self.lst_obj) <= idx:
            return

        if self.lst_num[idx].isChecked():
            if self.params.task == 'Classification':
                self.obj_group.setExclusive(False)
                self.lst_obj[idx].setChecked(False)
                self.obj_group.setExclusive(True)
                self.lst_obj[idx].setEnabled(False)
            elif self.params.task == 'Regression':
                self.lst_obj[idx].setEnabled(True)

            self.params.col_types[idx] = self.params.col_types_def[idx]
        elif self.lst_cat[idx].isChecked():
            if self.params.task == 'Classification':
                self.lst_obj[idx].setEnabled(True)
            elif self.params.task == 'Regression':
                self.obj_group.setExclusive(False)
                self.lst_obj[idx].setChecked(False)
                self.obj_group.setExclusive(True)
                self.lst_obj[idx].setEnabled(False)

            self.params.col_types[idx] = 'object'

        if self.obj_group.checkedButton() is None:
            self.params.objective = None
            self.lbl_cnf.setText(self.txt_cnf)
            self.btn.setEnabled(False)
        else:
            self.params.objective =\
                self.params.columns[self.obj_group.checkedId()]
            self.lbl_cnf.setText('<br>')
            self.btn.setEnabled(True)

        self.params.col_types_changed = True
Esempio n. 41
0
class Palette(QWidget):
    """
    This class implements the Graphol palette.
    """
    Padding = 6
    Spacing = 4

    def __init__(self, *args):
        """
        Initialize the Palette.
        """
        super().__init__(*args)
        self.buttonById = {}
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonClicked = self.buttonGroup.buttonClicked
        self.mainLayout = QGridLayout(self)
        self.mainLayout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        self.mainLayout.setContentsMargins(0, Palette.Padding, 0, Palette.Padding)
        self.mainLayout.setSpacing(Palette.Spacing)
        self.add(ConceptNode, 0, 0)
        self.add(RoleNode, 0, 1)
        self.add(ValueDomainNode, 0, 2)
        self.add(IndividualNode, 1, 0)
        self.add(ValueRestrictionNode, 1, 1)
        self.add(AttributeNode, 1, 2)
        self.add(DomainRestrictionNode, 2, 0)
        self.add(RangeRestrictionNode, 2, 1)
        self.add(IntersectionNode, 2, 2)
        self.add(RoleChainNode, 3, 0)
        self.add(DatatypeRestrictionNode, 3, 1)
        self.add(RoleInverseNode, 3, 2)
        self.add(ComplementNode, 4, 0)
        self.add(EnumerationNode, 4, 1)
        self.add(UnionNode, 4, 2)
        self.add(DisjointUnionNode, 5, 0)
        self.add(PropertyAssertionNode, 5, 1)
        self.add(InclusionEdge, 5, 2)
        self.add(InputEdge, 6, 0)
        self.add(InstanceOfEdge, 6, 1)
        self.setContentsMargins(0, 0, 0, 0)
        self.setFixedSize(216, 394)

    ####################################################################################################################
    #                                                                                                                  #
    #   DRAWING                                                                                                        #
    #                                                                                                                  #
    ####################################################################################################################

    def paintEvent(self, paintEvent):
        """
        This is needed for the widget to pick the stylesheet.
        :type paintEvent: QPaintEvent
        """
        option = QStyleOption()
        option.initFrom(self)
        painter = QPainter(self)
        style = self.style()
        style.drawPrimitive(QStyle.PE_Widget, option, painter, self)

    ####################################################################################################################
    #                                                                                                                  #
    #   INTERFACE                                                                                                      #
    #                                                                                                                  #
    ####################################################################################################################

    def add(self, item, row, column):
        """
        Add a button to the palette.
        :type item: class
        :type row: int
        :type column: int
        """
        button = PaletteButton(item)
        self.buttonById[item.item] = button
        self.buttonGroup.addButton(button, item.item)
        self.mainLayout.addWidget(button, row, column)

    def button(self, button_id):
        """
        Returns the button matching the given id.
        :type button_id: Item
        :rtype: PaletteButton
        """
        return self.buttonById[button_id]

    def clear(self, *args):
        """
        Clear the palette selection.
        :type args: Item
        """
        for button in self.buttonById.values():
            if button not in args:
                button.setChecked(False)