コード例 #1
0
ファイル: kws_kaldi_gui.py プロジェクト: dzhelonkin/vcp
    def initUI(self):
        self.statusBar().showMessage('ready')
        self.filename = QLabel(self)
        self.filename.setText('filename')
        self.filename.move(20, 20)

        self.filename_edit = QLineEdit(self)
        self.filename_edit.move(80, 20)

        self.keywords = QLabel(self)
        self.keywords.setText('keyword')
        self.keywords.move(20, 60)

        self.keywords_edit = QLineEdit(self)
        self.keywords_edit.move(80, 60)

        self.button = QPushButton('search', self)
        self.button.move(20, 100)
        self.button.clicked.connect(self.search_keywords)

        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setMaximumSize(300, 200)
        self.setMinimumSize(300, 200)
        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('kws kaldi')

        self.error_message = QLabel(self)
        self.result = QLabel(self)
コード例 #2
0
ファイル: part7.py プロジェクト: death-finger/Scripts
class FindDialog(QDialog):
    def __init__(self, parent=None):
        super(FindDialog, self).__init__(parent)

        findLabel = QLabel("Enter the name of a contact:")
        self.lineEdit = QLineEdit()

        self.findButton = QPushButton("&Find")
        self.findText = ''

        layout = QHBoxLayout()
        layout.addWidget(findLabel)
        layout.addWidget(self.lineEdit)
        layout.addWidget(self.findButton)

        self.setLayout(layout)
        self.setWindowTitle("Find a Contact")

        self.findButton.clicked.connect(self.findClicked)
        self.findButton.clicked.connect(self.accept)

    def findClicked(self):
        text = self.lineEdit.text()

        if not text:
            QMessageBox.information(self, "Empty Field",
                    "Please enter a name.")
            return

        self.findText = text
        self.lineEdit.clear()
        self.hide()

    def getFindText(self):
        return self.findText
コード例 #3
0
ファイル: styles.py プロジェクト: death-finger/Scripts
    def createBottomRightGroupBox(self):
        self.bottomRightGroupBox = QGroupBox("Group 3")
        self.bottomRightGroupBox.setCheckable(True)
        self.bottomRightGroupBox.setChecked(True)

        lineEdit = QLineEdit('s3cRe7')
        lineEdit.setEchoMode(QLineEdit.Password)

        spinBox = QSpinBox(self.bottomRightGroupBox)
        spinBox.setValue(50)

        dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox)
        dateTimeEdit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox)
        slider.setValue(40)

        scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox)
        scrollBar.setValue(60)

        dial = QDial(self.bottomRightGroupBox)
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout()
        layout.addWidget(lineEdit, 0, 0, 1, 2)
        layout.addWidget(spinBox, 1, 0, 1, 2)
        layout.addWidget(dateTimeEdit, 2, 0, 1, 2)
        layout.addWidget(slider, 3, 0)
        layout.addWidget(scrollBar, 4, 0)
        layout.addWidget(dial, 3, 1, 2, 1)
        layout.setRowStretch(5, 1)
        self.bottomRightGroupBox.setLayout(layout)
コード例 #4
0
ファイル: qtui.py プロジェクト: nim65s/scripts
    def __init__(self, vcards, keys, parent):
        self.vcards, self.keys = vcards, keys
        super().__init__(parent)

        done = QPushButton("Done", self)
        done.clicked.connect(self.merge_done)

        self.edits = {}
        layout = QGridLayout()
        layout.addWidget(done, 0, 1)
        i = 1
        for key in self.keys:
            if key not in ['REV', 'UID', 'VERSION', 'PRODID']:

                items = set()
                for v in self.vcards.values():
                    if key in v.dict and v.dict[key]:
                        for item in v.dict[key]:
                            items.add(item)
                if items:
                    edit = QLineEdit(self)
                    edit.setText('|'.join(items))
                    layout.addWidget(QLabel(key), i, 0)
                    layout.addWidget(edit, i, 1)
                    self.edits[key] = edit
                    i += 1

        self.setLayout(layout)
コード例 #5
0
ファイル: gui.py プロジェクト: jamesabel/latus
 def add_line(self, label, value, row_number, layout):
     layout.addWidget(QLabel(label), row_number, 0)
     log_dir_widget = QLineEdit(value)
     log_dir_widget.setReadOnly(True)
     width = QFontMetrics(QFont()).width(value) * 1.05
     log_dir_widget.setMinimumWidth(width)
     layout.addWidget(log_dir_widget, row_number+1, 0)
コード例 #6
0
ファイル: maximum_flow_window.py プロジェクト: mintoo/NetDim
    def __init__(self, controller):
        super().__init__()
        self.controller = controller
        self.setWindowTitle('Maximum flow algorithms')
        
        algorithm = QLabel('Algorithm')        
        self.mf_list = QComboBox()
        self.mf_list.addItems(self.algorithms)

        source = QLabel('Source')
        self.source_edit = QLineEdit()
        
        destination = QLabel('Destination')
        self.destination_edit = QLineEdit()
                
        # confirmation button
        button_compute = QPushButton()
        button_compute.setText('Compute')
        button_compute.clicked.connect(self.compute_flow)
        
        # position in the grid
        layout = QGridLayout()
        layout.addWidget(algorithm, 0, 0, 1, 1)
        layout.addWidget(self.mf_list, 0, 1, 1, 1)
        layout.addWidget(source, 1, 0, 1, 1)
        layout.addWidget(self.source_edit, 1, 1, 1, 1)
        layout.addWidget(destination, 2, 0, 1, 1)
        layout.addWidget(self.destination_edit, 2, 1, 1, 1)
        layout.addWidget(button_compute, 3, 0, 1, 2)
        self.setLayout(layout)
コード例 #7
0
class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):      

        self.btn = QPushButton('Dialog', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showDialog)
        
        self.le = QLineEdit(self)
        self.le.move(130, 22)
        
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Input dialog')
        self.show()
        
        
    def showDialog(self):
        """ ボタンが押されるとダイアログを出す """

        # input dialogを出す
        text, ok = QInputDialog.getText(self, 'Input Dialog', 
            'Enter your name:')
        
        if ok:
            # QLineEditのオブジェクトにテキストをセット
            self.le.setText(str(text))
コード例 #8
0
class InputDialog(QDialog):
    def __init__(self,parent=None):
        super(InputDialog,self).__init__(parent)
        self.setWindowTitle("输入服务器地址和用户名")
        self.resize(300,150)
        self.setWindowIcon(QIcon('images/icon.jpg'))
        self.createGrid()

    def createGrid(self):
        names = ('呆尐兔兔','康师傅','哇哈哈','矿泉水','农夫山泉','蛤蛤','操作系统','计算机','网络','数据通信')
        nick_name = names[int(time.time() * 1000) % 10]
        layout = QGridLayout(self)
        self.setLayout(layout)
        #添加三个输入框
        self.ipEdit = QLineEdit('127.0.0.1')
        self.portEdit = QLineEdit('9999')
        self.nicknameEdit = QLineEdit(nick_name)
        layout.addWidget(QLabel("IP地址"),0,0,1,2)
        layout.addWidget(self.ipEdit,0,2,1,10)
        layout.addWidget(QLabel("端口号"),1,0,1,2)
        layout.addWidget(self.portEdit,1,2,1,10)
        layout.addWidget(QLabel("昵称"),2,0,1,2)
        layout.addWidget(self.nicknameEdit,2,2,1,10)
        #添加提交按钮
        submit_btn = QPushButton('确认',self)
        submit_btn.clicked.connect(self.submit)
        layout.addWidget(submit_btn,3,7,1,5)

    def submit(self):
        ip,port,nickname = self.ipEdit.text(),self.portEdit.text(),self.nicknameEdit.text()
        def is_valid_ip(ip_address):
            if ip_address == "localhost":
                return True
            if not ip:
                return False
            ip_address = str(ip_address).split('.')
            if len(ip_address) != 4:
                return False
            for each in ip_address :
                if not each.isdigit():
                    return False
                if int(each) > 255 or int(each) < 0:
                    return False
            return True

        def is_valid_port(port):
            return port and str(port).isdigit() and ( 0 < int(port) < 65536)

        def is_valid_nickname(nickname):
            return nickname and ( 0 < len(nickname) < 21)

        if not is_valid_ip(ip):
            QMessageBox.information(self,"警告","请输入正确的IP地址")
        elif not is_valid_port(port):
            QMessageBox.information(self,"警告","请输入正确的端口号")
        elif not is_valid_nickname(nickname):
            QMessageBox.information(self,"警告","请输入正确的昵称,1-20字符")
        else:
            self.hide()
            startGame(ip,port,nickname)
コード例 #9
0
    def init(self):

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        text = QLineEdit('0.')
        text.setReadOnly(True)
        vbox.addWidget(text)

        grid = QGridLayout()
        vbox.addLayout(grid)

        names = ['Exit', 'AC', 'DEL', '+/-',
                 '7', '8', '9', '/',
                 '4', '5', '6', '*',
                 '1', '2', '3', '-',
                 '0', '.', '=', '+']

        positions = [(i, j) for i in range(5) for j in range(4)]

        for position, name in zip(positions, names):
            btn = QPushButton(name)
            grid.addWidget(btn, *position)

        self.move(300, 200)
        self.setWindowTitle('Calculator')
        self.show()
コード例 #10
0
ファイル: hello_pyqt.py プロジェクト: jerryhan88/py_source
class Example(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.initUI()

    def initUI(self):

        self.btn = QPushButton("Dialog", self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showDialog)

        self.le = QLineEdit(self)
        self.le.move(130, 22)

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle("Input dialog")
        self.show()

    def showDialog(self):

        text, ok = QInputDialog.getText(self, "Input Dialog", "Enter your name:")

        if ok:
            self.le.setText(str(text))
コード例 #11
0
ファイル: area_operations.py プロジェクト: mintoo/NetDim
 def __init__(self, asm):
     super().__init__()
     self.setWindowTitle('Create area')
     
     area_name = QLabel('Area name')
     area_id = QLabel('Area id')
             
     self.name_edit = QLineEdit()
     self.name_edit.setMaximumWidth(120)
     
     self.id_edit = QLineEdit()
     self.id_edit.setMaximumWidth(120)
     
     # confirmation button
     button_create_area = QPushButton()
     button_create_area.setText('OK')
     button_create_area.clicked.connect(lambda: self.create_area(asm))
     
     # cancel button
     cancel_button = QPushButton()
     cancel_button.setText('Cancel')
     
     # position in the grid
     layout = QGridLayout()
     layout.addWidget(area_name, 0, 0, 1, 1)
     layout.addWidget(self.name_edit, 0, 1, 1, 1)
     layout.addWidget(area_id, 1, 0, 1, 1)
     layout.addWidget(self.id_edit, 1, 1, 1, 1)
     layout.addWidget(button_create_area, 2, 0, 1, 1)
     layout.addWidget(cancel_button, 2, 1, 1, 1)
     self.setLayout(layout)
コード例 #12
0
    def _initUi(self):
        self.setWindowTitle('杰卡德指数')
 
        # 控件
        label = QLabel('参数(格式: 周期1,涨幅1(%);周期2,涨幅2(%);..., 比如10,10;20,20;...)')
        self._lineEdit = QLineEdit('10,10;20,20;30,30;40,40;50,50;60,60')

        startDateLable = QLabel('开始日期')
        self._startDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

        endDateLable = QLabel('结束日期')
        self._endDateLineEdit = QLineEdit(datetime.now().strftime("%Y-%m-%d"))

        cancelPushButton = QPushButton('Cancel')
        okPushButton = QPushButton('OK')
        cancelPushButton.clicked.connect(self._cancel)
        okPushButton.clicked.connect(self._ok)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
 
        grid.addWidget(startDateLable, 0, 0)
        grid.addWidget(self._startDateLineEdit, 1, 0)

        grid.addWidget(endDateLable, 0, 1)
        grid.addWidget(self._endDateLineEdit, 1, 1)
 
        grid.addWidget(label, 2, 0, 1, 2)
        grid.addWidget(self._lineEdit, 3, 0, 1, 2)

        grid.addWidget(okPushButton, 4, 1)
        grid.addWidget(cancelPushButton, 4, 0)
 
        self.setLayout(grid)
コード例 #13
0
    def setupUi(self, Furniture_Form):
        layout = QGridLayout(self)
        self.furnitures = []

        if get_all_rooms_number() != []:
            min_room_number = min(get_all_rooms_number())
            max_room_number = max(get_all_rooms_number())
            room_number_label = "Enter room number({0}-{1}):".format(
                                str(min_room_number), str(max_room_number))
        else:
            room_number_label = ''
        self.room_number_label = QLabel(room_number_label)
        self.room_number_line_edit = QLineEdit()
        self.furniture_name_label = QLabel("Name:")
        self.furniture_name_line_edit = QLineEdit()
        self.quality_label = QLabel("Quality")
        self.quality_combo_box = QComboBox()
        self.quality_combo_box.addItem("Excellent")
        self.quality_combo_box.addItem("Good")
        self.quality_combo_box.addItem("Bad")

        layout.addWidget(self.room_number_label, 0, 0)
        layout.addWidget(self.room_number_line_edit, 0, 1)
        layout.addWidget(self.furniture_name_label, 1, 0)
        layout.addWidget(self.furniture_name_line_edit, 1, 1)
        layout.addWidget(self.quality_label, 2, 0)
        layout.addWidget(self.quality_combo_box, 2, 1)

        self.setLayout(layout)
        self.layout().setSizeConstraint(QLayout.SetFixedSize)
コード例 #14
0
ファイル: patches.py プロジェクト: DKMS-LSL/typeloader
 def init_UI(self):
     self.log.info("Requesting user input for necessary patches...")
     layout = QFormLayout()
     self.setLayout(layout)
     
     intro_lbl = QLabel("The new version of TypeLoader needs the following additional settings:")
     intro_lbl.setStyleSheet(general.label_style_2nd)
     layout.addRow(intro_lbl)
     
     intro_lbl2 = QLabel("(1) A short identifier for your company towards IPD. (IPD submission files will start with this.)\nAn acronym etc. is ideal:")
     intro_lbl2.setStyleSheet(general.label_style_italic)
     layout.addRow(intro_lbl2)
     self.ipd_short_fld = QLineEdit(self)
     layout.addRow(QLabel("IPD Shortname:"), self.ipd_short_fld)
     
     intro_lbl3 = QLabel("(2) The number of IPD submission files your company has already created with previous TypeLoader versions:")
     intro_lbl3.setStyleSheet(general.label_style_italic)
     layout.addRow(intro_lbl3)
     self.ipd_nr_fld = QLineEdit(self)
     self.ipd_nr_fld.setText("0")
     layout.addRow(QLabel("IPD Submission Nr:"), self.ipd_nr_fld)
     
     intro_lbl3 = QLabel("(3) A short identifier for your company to use for cell line naming. An acronym etc. is ideal:")
     intro_lbl3.setStyleSheet(general.label_style_italic)
     layout.addRow(intro_lbl3)
     self.token_fld = QLineEdit(self)
     self.token_fld.setPlaceholderText("Can be identical to IPD shortname; max. 10 characters, only alphanumeric or '-'.")
     layout.addRow(QLabel("Cell line identifier:"), self.token_fld)
     
     self.ok_btn = ProceedButton("Done", [self.ipd_short_fld, self.ipd_nr_fld, self.token_fld], self.log)
     layout.addRow(self.ok_btn)
     self.ipd_short_fld.textChanged.connect(self.ok_btn.check_ready)
     self.ipd_nr_fld.textChanged.connect(self.ok_btn.check_ready)
     self.token_fld.textChanged.connect(self.ok_btn.check_ready)
     self.ok_btn.clicked.connect(self.on_clicked)
コード例 #15
0
ファイル: config.py プロジェクト: frmwrk123/oeprint
class ConfigDialog(QDialog):
    """Dialog class for configuration dialog"""
    def __init__(self, parent=None):
        """Initializes the dialog"""
        super(ConfigDialog, self).__init__(parent)
        self.__config = Config()

        # create form elements
        self.submitButton = QPushButton('&Save')
        ssh_host_label = QLabel('SSH-Host')
        self.sshHostLine = QLineEdit()
        self.sshHostLine.setText(self.__config.get('SSH', 'host'))

        # create form layout
        form_layout = QGridLayout()
        form_layout.addWidget(ssh_host_label, 0, 0)
        form_layout.addWidget(self.sshHostLine, 0, 1)

        # create main layout
        main_layout = QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addWidget(self.submitButton)
        # connect submit button with submit action
        self.submitButton.clicked.connect(self.__save)
        self.setLayout(main_layout)
        self.setWindowTitle('Preferences')

    def __save(self):
        """Saves the preferences"""
        ssh_host = self.sshHostLine.text()
        self.__config.set('SSH', 'host', ssh_host)
        self.__config.write()
        self.hide()
コード例 #16
0
ファイル: glyphDialogs.py プロジェクト: anthrotype/trufont
class AddLayerDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Add layer…"))

        layout = QGridLayout(self)

        layerNameLabel = QLabel(self.tr("Layer name:"), self)
        self.layerNameEdit = QLineEdit(self)
        self.layerNameEdit.setFocus(True)
        self.layerColorVignette = ColorVignette(self)
        self.layerColorVignette.setColor(LayerColorGenerator.getQColor())

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        l = 0
        layout.addWidget(layerNameLabel, l, 0)
        layout.addWidget(self.layerNameEdit, l, 1)
        layout.addWidget(self.layerColorVignette, l, 2)
        l += 1
        layout.addWidget(buttonBox, l, 0, 1, 3)
        self.setLayout(layout)

    @classmethod
    def getNewLayerNameAndColor(cls, parent):
        dialog = cls(parent)
        result = dialog.exec_()
        name = dialog.layerNameEdit.text()
        color = dialog.layerColorVignette.color()
        if not result:
            LayerColorGenerator.revert()
        return (name, color.getRgbF(), result)
コード例 #17
0
ファイル: glyphDialogs.py プロジェクト: anthrotype/trufont
class RenameDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle(self.tr("Rename…"))

        nameLabel = QLabel(self.tr("Name:"), self)
        self.nameEdit = QLineEdit(self)
        self.nameEdit.setFocus(True)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        layout = QGridLayout(self)
        l = 0
        layout.addWidget(nameLabel, l, 0)
        layout.addWidget(self.nameEdit, l, 1, 1, 3)
        l += 1
        layout.addWidget(buttonBox, l, 3)
        self.setLayout(layout)

    @classmethod
    def getNewName(cls, parent, name=None):
        dialog = cls(parent)
        dialog.nameEdit.setText(name)
        dialog.nameEdit.selectAll()
        result = dialog.exec_()
        name = dialog.nameEdit.text()
        return (name, result)
コード例 #18
0
ファイル: GUI.py プロジェクト: L3nn0x/tags
    def initUI(self):
        self.setGeometry(200,200,500,200)
        self.setWindowTitle('Tag Indexer: Add an entry')
        
        lblURL = QLabel('URL:', self)

        lblTags = QLabel('Tags:', self)
        lblTags.setToolTip('À séparer par des virgules')

        self.champURL = QLineEdit(self)
        self.champURL.returnPressed.connect(self.save)


        self.champTags = QLineEdit(self)
        self.champTags.returnPressed.connect(self.save)

        btnEnr = QPushButton('Enregistrer',self)
        btnEnr.clicked.connect(self.save)

        btnAnnul = QPushButton('Annuler',self)
        btnAnnul.clicked.connect(self.hide)

        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(lblURL, 0,0)
        grid.addWidget(self.champURL, 0, 3, 1, 6)
        grid.addWidget(lblTags, 4, 0)
        grid.addWidget(self.champTags, 4, 3, 1, 6)
        grid.addWidget(btnAnnul, 9, 7)
        grid.addWidget(btnEnr, 9, 8)
        self.setLayout(grid)
コード例 #19
0
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.number = Number.Number(1)
        numberFromLabel = QLabel("Number:")
        self.numberFromLine = QLineEdit()
        baseFromLabel = QLabel("From Base:")
        self.baseFromLine = QLineEdit()
        baseToLabel = QLabel("To Base:")
        self.baseToLine = QLineEdit()
        self.submitButton = QPushButton("Convert!")
        self.resultLabel = QLabel("")

        vLayout1 = QVBoxLayout()
        vLayout1.addWidget(numberFromLabel)
        vLayout1.addWidget(self.numberFromLine)
        vLayout1.addWidget(baseFromLabel)
        vLayout1.addWidget(self.baseFromLine)
        vLayout1.addWidget(baseToLabel)
        vLayout1.addWidget(self.baseToLine)
        vLayout1.addWidget(self.submitButton)
        vLayout1.addWidget(self.resultLabel)

        self.submitButton.clicked.connect(self.submitNumbers)

        mainLayout = QGridLayout()
        mainLayout.addLayout(vLayout1, 0, 1)

        self.setLayout(mainLayout)
        self.setWindowTitle("Base converter")
コード例 #20
0
ファイル: lineedit.py プロジェクト: gpa14/enki
    def paintEvent(self, event):
        """QLineEdit.paintEvent implementation.
        Draws prompt
        """
        QLineEdit.paintEvent(self, event)

        if self._promptText and not self.text() and self.isEnabled():
            option = QStyleOptionFrameV3()
            self.initStyleOption(option)

            left, top, right, bottom = self.getTextMargins()

            va = self.style().visualAlignment(self.layoutDirection(), self.alignment())
            rect = (
                self.style()
                .subElementRect(QStyle.SE_LineEditContents, option, self)
                .adjusted(2, 0, 0, 0)
                .adjusted(left, top, -right, -bottom)
            )
            fm = QFontMetrics(self.font())
            text = fm.elidedText(self._promptText, Qt.ElideRight, rect.width())
            painter = QPainter(self)

            painter.setPen(self.palette().color(QPalette.Disabled, QPalette.Text))
            painter.drawText(rect, va, text)
コード例 #21
0
ファイル: GUI.py プロジェクト: L3nn0x/tags
class WinNewEntry(QWidget):
    def __init__(self, controller):
        super().__init__()
        self.initUI()
        self.controller = controller

    def initUI(self):
        self.setGeometry(200,200,500,200)
        self.setWindowTitle('Tag Indexer: Add an entry')
        
        lblURL = QLabel('URL:', self)

        lblTags = QLabel('Tags:', self)
        lblTags.setToolTip('À séparer par des virgules')

        self.champURL = QLineEdit(self)
        self.champURL.returnPressed.connect(self.save)


        self.champTags = QLineEdit(self)
        self.champTags.returnPressed.connect(self.save)

        btnEnr = QPushButton('Enregistrer',self)
        btnEnr.clicked.connect(self.save)

        btnAnnul = QPushButton('Annuler',self)
        btnAnnul.clicked.connect(self.hide)

        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(lblURL, 0,0)
        grid.addWidget(self.champURL, 0, 3, 1, 6)
        grid.addWidget(lblTags, 4, 0)
        grid.addWidget(self.champTags, 4, 3, 1, 6)
        grid.addWidget(btnAnnul, 9, 7)
        grid.addWidget(btnEnr, 9, 8)
        self.setLayout(grid)


    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.hide()

    def closeEvent(self, e):
        self.hide()
        e.ignore()

    def save(self):
        tags = self.champTags.text().split(",")
        tags = [i for i in map(lambda s: s.rstrip(" \t").lstrip(" \t"), tags)]
        e = NewDataEvent(self.champURL.text(), tags)
        self.champURL.setText('')
        self.champTags.setText('')
        self.hide()
        self.controller.notify(e)

    def cancel(self):
        self.champURL.setText('')
        self.champTags.setText('')
        self.hide()
コード例 #22
0
ファイル: widgets.py プロジェクト: gridsync/gridsync
class FolderSelector(QWidget):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.folder = None

        self.line_edit = QLineEdit()

        self.button = QPushButton()
        self.button.setText("Browse...")
        self.button.clicked.connect(self.on_clicked)

        gbox = QGroupBox(self)
        gbox.setTitle("Select a folder to sync:")
        gbox_layout = QHBoxLayout(gbox)
        gbox_layout.addItem(QSpacerItem(100, 0, QSizePolicy.Preferred, 0))
        gbox_layout.addWidget(self.line_edit)
        gbox_layout.addWidget(self.button)
        gbox_layout.addItem(QSpacerItem(100, 0, QSizePolicy.Preferred, 0))

        hbox = QHBoxLayout(self)
        hbox.addWidget(gbox)
        #hbox.addItem(QSpacerItem(100, 0, QSizePolicy.Preferred, 0))
        #hbox.addWidget(self.line_edit)
        #hbox.addWidget(self.button)
        #hbox.addItem(QSpacerItem(100, 0, QSizePolicy.Preferred, 0))

    def on_clicked(self):
        selected_folder = QFileDialog.getExistingDirectory(
            self, "Select a folder to sync")
        if selected_folder:
            self.line_edit.setText(selected_folder)
            self.folder = selected_folder
コード例 #23
0
ファイル: gui_hotp.py プロジェクト: lesbeben/m1ssi2013
    def set_view(self):
        self.setWindowTitle("QOtpToken")

        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Secret: "))
        self.secret = QLineEdit()
        hbox.addWidget(self.secret)
        vbox.addLayout(hbox)

        hbox = QHBoxLayout()
        self.counter = QSpinBox()
        self.counter.setMinimum(0)
        self.length = QSpinBox()
        self.length.setValue(6)
        self.length.setMinimum(6)
        self.length.setMaximum(8)
        self.generate = QPushButton("Générer")
        hbox.addWidget(QLabel("Compteur: "))
        hbox.addWidget(self.counter)
        hbox.addWidget(QLabel("Taille: "))
        hbox.addWidget(self.length)
        hbox.addWidget(self.generate)
        vbox.addLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Mot de passe jetable: "))
        self.display = QLineEdit("")
        self.display.setReadOnly(True)
        hbox.addWidget(self.display)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        pass
コード例 #24
0
 def createEditor(self, parent, option, index):
     """ Return a QLineEdit for arbitrary representation of a date value in any format.
     """
     editor = QLineEdit(parent)
     date = index.model().data(index, Qt.DisplayRole)
     editor.setText(date.strftime(self.format))
     return editor
コード例 #25
0
ファイル: editor.py プロジェクト: stweil/frescobaldi
    def __init__(self, page):
        super(TypographicalQuotes, self).__init__(page)

        layout = QGridLayout(spacing=1)
        self.setLayout(layout)
        l = self.languageLabel = QLabel()
        c = self.languageCombo = QComboBox(currentIndexChanged=self.languageChanged)
        l.setBuddy(c)

        self.primaryLabel = QLabel()
        self.secondaryLabel = QLabel()
        self.primaryLeft = QLineEdit(textEdited=self.changed)
        self.primaryRight = QLineEdit(textEdited=self.changed)
        self.secondaryLeft = QLineEdit(textEdited=self.changed)
        self.secondaryRight = QLineEdit(textEdited=self.changed)

        self._langs = ["current", "custom"]
        self._langs.extend(lang for lang in lasptyqu.available() if lang != "C")
        c.addItems(['' for i in self._langs])

        layout.addWidget(self.languageLabel, 0, 0)
        layout.addWidget(self.primaryLabel, 1, 0)
        layout.addWidget(self.secondaryLabel, 2, 0)
        layout.addWidget(self.languageCombo, 0, 1, 1, 2)
        layout.addWidget(self.primaryLeft, 1, 1)
        layout.addWidget(self.primaryRight, 1, 2)
        layout.addWidget(self.secondaryLeft, 2, 1)
        layout.addWidget(self.secondaryRight, 2, 2)

        app.translateUI(self)
コード例 #26
0
ファイル: proprietes_objets.py プロジェクト: wxgeo/geophar
 def __init__(self, parent, attribut, editable=False):
     QLineEdit.__init__(self, parent)
     self.setMinimumWidth(300)
     self.parent = parent
     self.attribut = attribut
     self.setReadOnly(not editable)
     self.actualiser()
コード例 #27
0
ファイル: myWidgets.py プロジェクト: MazeFX/pat
    def __init__(self, *args):
        super(MyCurrencyBox, self).__init__(*args)
        Lumberjack.info('spawning a << MyCurrencyBox >>')
        self.currencyBoxlayout = QHBoxLayout(self)
        self.currencyBoxlayout.setObjectName("currencyBoxlayout")
        self.currencyLabel = QLabel('€')
        self.euroLineEdit = QLineEdit()
        self.euroLineEdit.setText('0')
        self.euroLineEdit.setAlignment(Qt.AlignRight)
        self.euroLineEdit.setObjectName("euroLineEdit")
        euroValidator = QIntValidator()
        self.euroLineEdit.setValidator(euroValidator)
        self.euroLineEdit.setMaxLength(6)
        self.commaLabel = QLabel(',')
        self.centsLineEdit = QLineEdit()
        self.centsLineEdit.setText('00')
        self.euroLineEdit.setAlignment(Qt.AlignRight)
        self.centsLineEdit.setObjectName("centsLineEdit")
        centsValidator = QIntValidator(0, 99)
        self.centsLineEdit.setValidator(centsValidator)
        self.centsLineEdit.setMaxLength(2)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.currencyBoxlayout.addItem(spacerItem1)
        self.currencyBoxlayout.addWidget(self.currencyLabel)
        self.currencyBoxlayout.addWidget(self.euroLineEdit)
        self.currencyBoxlayout.addWidget(self.commaLabel)
        self.currencyBoxlayout.addWidget(self.centsLineEdit)
        self.currencyBoxlayout.addItem(spacerItem2)

        self.centsLineEdit.textChanged.connect(self.on_text_input)
        self.euroLineEdit.textChanged.connect(self.on_text_input)
コード例 #28
0
ファイル: gui_z3.py プロジェクト: EdwardBetts/python101
    def __init__(self, parent=None):
        super(LoginDialog, self).__init__(parent)

        # etykiety, pola edycyjne i przyciski ###
        loginLbl = QLabel('Login')
        hasloLbl = QLabel('Hasło')
        self.login = QLineEdit()
        self.haslo = QLineEdit()
        self.przyciski = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
            Qt.Horizontal, self)

        # układ główny ###
        uklad = QGridLayout(self)
        uklad.addWidget(loginLbl, 0, 0)
        uklad.addWidget(self.login, 0, 1)
        uklad.addWidget(hasloLbl, 1, 0)
        uklad.addWidget(self.haslo, 1, 1)
        uklad.addWidget(self.przyciski, 2, 0, 2, 0)

        # sygnały i sloty ###
        self.przyciski.accepted.connect(self.accept)
        self.przyciski.rejected.connect(self.reject)

        # właściwości widżetu ###
        self.setModal(True)
        self.setWindowTitle('Logowanie')
コード例 #29
0
ファイル: graph_dimension.py プロジェクト: mintoo/NetDim
 def __init__(self, graph_type, controller):
     super().__init__()
     self.controller = controller
     self.graph_type = graph_type
     self.setWindowTitle('Graph generation')
     
     layout = QGridLayout()
     self.node_subtype_list = QObjectComboBox()
     self.node_subtype_list.addItems(node_name_to_obj)
     
     number_of_nodes = QLabel('Nodes')
     self.nodes_edit = QLineEdit()
     self.nodes_edit.setMaximumWidth(120)
     
     if graph_type in ('kneser', 'petersen'):
         number_of_subset = QLabel('Subsets')
         self.subset_edit = QLineEdit()
         self.subset_edit.setMaximumWidth(120)
     
     # confirmation button
     confirmation_button = QPushButton(self)
     confirmation_button.setText('OK')
     confirmation_button.clicked.connect(self.confirm)
     
     layout.addWidget(self.node_subtype_list, 0, 0, 1, 2)
     layout.addWidget(number_of_nodes, 1, 0, 1, 1)
     layout.addWidget(self.nodes_edit, 1, 1, 1, 1)
     if graph_type in ('kneser', 'petersen'):
         layout.addWidget(number_of_subset, 2, 0, 1, 1)
         layout.addWidget(self.subset_edit, 2, 1, 1, 1)
     layout.addWidget(confirmation_button, 3, 0, 1, 2)
     self.setLayout(layout)
コード例 #30
0
	def initUI(self):

		# self.setStyleSheet( "background-color : grey")
		researchLabel = QLabel('Player Name')
		researchLabel.setFont( QFont("Fira Mono Bold", 11))
		researchLabel.adjustSize()
		resultsLabel = QLabel('Search results')
		resultsLabel.setFont( QFont("Fira Mono Bold", 11))
		resultsLabel.adjustSize()

		researchEdit = QLineEdit()
		researchEdit.setStyleSheet( "border : 2px solid #75FF6961; border-radius : 5px; background-color : #cbcbcb")
		researchEdit.setFont( QFont("Fira Mono Bold",12))
		researchEdit.returnPressed.connect(self.newResearch)

		grid = QGridLayout()
		grid.setSpacing(4)
		grid.addWidget(researchLabel, 1, 0)
		grid.addWidget(researchEdit, 1, 1)
		grid.addWidget(resultsLabel, 2, 0)
		self.setLayout(grid)
		# self.setGeometry(100, 100, 1000, 400)
		self.setWindowTitle('Player Searcher')
		self.show()

		self.researchEdit = researchEdit
		self.grid = grid
コード例 #31
0
    def interface(self):

        # Window background color
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        # Label name
        label1 = QLabel("Obraz:", self)
        label2 = QLabel("Wynik:", self)
        self.label = QLabel()

        positionLabels = QGridLayout()
        positionLabels.addWidget(label1, 1, 0)
        positionLabels.addWidget(label2, 1, 1)

        positionLabels.addWidget(self.label, 0, 0, 1, 3)
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)

        pixmap = QPixmap()
        self.label.setPixmap(pixmap)

        # Edit field
        self.fileEdt = QLineEdit()
        self.recognizeEdt = QLineEdit()

        self.recognizeEdt.readonly = True
        self.fileEdt.readonly = True

        positionLabels.addWidget(self.fileEdt, 2, 0)
        positionLabels.addWidget(self.recognizeEdt, 2, 1)

        # Buttons
        loadFileBtn = QPushButton("&Wczytaj obraz", self)
        recognizeBtn = QPushButton("&Rozpoznaj", self)
        endBtn = QPushButton("&Wyjdź", self)
        endBtn.resize(endBtn.sizeHint())

        loadFileBtn.setStyleSheet(
            "color: white; background-color: black; font-size: 16px; padding: 5px;"
        )
        recognizeBtn.setStyleSheet(
            "color: white; background-color: black; font-size: 16px; padding: 5px;"
        )
        endBtn.setStyleSheet(
            "color: white; background-color: red; font-size: 16px; font-weight: bold;"
        )

        positionBtns = QHBoxLayout()
        positionBtns.addWidget(loadFileBtn)
        positionBtns.addWidget(recognizeBtn)

        positionLabels.addLayout(positionBtns, 3, 0, 1, 3)
        positionLabels.addWidget(endBtn, 4, 0, 1, 3)

        self.setLayout(positionLabels)

        endBtn.clicked.connect(self.end)
        loadFileBtn.clicked.connect(self.getfiles)
        recognizeBtn.clicked.connect(self.prediction)

        self.setGeometry(300, 300, 700, 400)
        self.setWindowIcon(QIcon('./icon/icon.png'))
        self.setWindowTitle("Rozpoznawanie owoców")
        self.show()
コード例 #32
0
    def initUI(self):

        self.setGeometry(200, 200, 500, 200)
        self.setWindowTitle('DUT Info')
        self.setWindowIcon(QIcon('xbox_icon.ico'))

        self.okButton = QPushButton('Ok', self)
        self.okButton.setGeometry(210, 160, 80, 30)
        self.okButton.clicked[bool].connect(self.returnInfo)

        configId = QLabel(self)
        configId.setGeometry(10, 10, 80, 20)
        configId.setText("Config ID")

        self.configIdLineEdit = QLineEdit(self)
        self.configIdLineEdit.setGeometry(10, 30, 80, 20)
        self.configIdLineEdit.setText("Blank Config")

        pcbaSN = QLabel(self)
        pcbaSN.setGeometry(100, 10, 140, 20)
        pcbaSN.setText("PCBA Serial #")

        self.pcbaSNLineEdit = QLineEdit(self)
        self.pcbaSNLineEdit.setGeometry(100, 30, 140, 20)
        self.pcbaSNLineEdit.setText("0085602J1000863044")

        productSN = QLabel(self)
        productSN.setGeometry(250, 10, 120, 20)
        productSN.setText("Product Serial #")

        self.productSNLineEdit = QLineEdit(self)
        self.productSNLineEdit.setGeometry(250, 30, 120, 20)
        self.productSNLineEdit.setText("n/a")

        scopeType = QLabel(self)
        scopeType.setGeometry(10, 55, 80, 20)
        scopeType.setText("Scope Type")

        self.scopeTypeLineEdit = QLineEdit(self)
        self.scopeTypeLineEdit.setGeometry(10, 75, 80, 20)
        self.scopeTypeLineEdit.setText("Tek MSO4104B")

        probeType = QLabel(self)
        probeType.setGeometry(100, 55, 100, 20)
        probeType.setText("Scope Probe Type")

        self.probeTypeLineEdit = QLineEdit(self)
        self.probeTypeLineEdit.setGeometry(100, 75, 80, 20)
        self.probeTypeLineEdit.setText("Tek TDP1500")

        runNotes = QLabel(self)
        runNotes.setGeometry(200, 55, 150, 20)
        runNotes.setText("Run Notes")

        self.runNotesLineEdit = QLineEdit(self)
        self.runNotesLineEdit.setGeometry(200, 75, 150, 20)
        self.runNotesLineEdit.setText("Blank Note")

        senseRes = QLabel(self)
        senseRes.setGeometry(10, 100, 80, 20)
        senseRes.setText("Sense Resistor")

        self.senseResLineEdit = QLineEdit(self)
        self.senseResLineEdit.setGeometry(10, 120, 50, 20)
        self.senseResLineEdit.setText("0.001")
コード例 #33
0
    def __init__(self, parent=None):
        super().__init__(parent)

        # Display Window
        self.display = QLineEdit()
        self.display.setReadOnly(True)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setMaxLength(15)

        # Button Creation and Placement
        numLayout = QGridLayout()
        opLayout = QGridLayout()
        constLayout = QGridLayout()
        funcLayout = QGridLayout()

        buttonGroups = {
            'num': {
                'buttons': numPadList,
                'layout': numLayout,
                'columns': 3
            },
            'op': {
                'buttons': operatorList,
                'layout': opLayout,
                'columns': 2
            },
            'constants': {
                'buttons': constantList,
                'layout': constLayout,
                'columns': 1
            },
            'functions': {
                'buttons': functionList,
                'layout': funcLayout,
                'columns': 1
            },
        }

        for label in buttonGroups.keys():
            r = 0
            c = 0
            buttonPad = buttonGroups[label]
            for btnText in buttonPad['buttons']:
                button = Button(btnText, self.buttonClicked)
                buttonPad['layout'].addWidget(button, r, c)
                c += 1
                if c >= buttonPad['columns']:
                    c = 0
                    r += 1

        # Layout
        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)

        mainLayout.addWidget(self.display, 0, 0, 1, 2)
        mainLayout.addLayout(numLayout, 1, 0)
        mainLayout.addLayout(opLayout, 1, 1)
        mainLayout.addLayout(constLayout, 2, 0)
        mainLayout.addLayout(funcLayout, 2, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle("20181710 황예은")
コード例 #34
0
class Calculator(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # Display Window
        self.display = QLineEdit()
        self.display.setReadOnly(True)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setMaxLength(15)

        # Button Creation and Placement
        numLayout = QGridLayout()
        opLayout = QGridLayout()
        constLayout = QGridLayout()
        funcLayout = QGridLayout()

        buttonGroups = {
            'num': {
                'buttons': numPadList,
                'layout': numLayout,
                'columns': 3
            },
            'op': {
                'buttons': operatorList,
                'layout': opLayout,
                'columns': 2
            },
            'constants': {
                'buttons': constantList,
                'layout': constLayout,
                'columns': 1
            },
            'functions': {
                'buttons': functionList,
                'layout': funcLayout,
                'columns': 1
            },
        }

        for label in buttonGroups.keys():
            r = 0
            c = 0
            buttonPad = buttonGroups[label]
            for btnText in buttonPad['buttons']:
                button = Button(btnText, self.buttonClicked)
                buttonPad['layout'].addWidget(button, r, c)
                c += 1
                if c >= buttonPad['columns']:
                    c = 0
                    r += 1

        # Layout
        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)

        mainLayout.addWidget(self.display, 0, 0, 1, 2)
        mainLayout.addLayout(numLayout, 1, 0)
        mainLayout.addLayout(opLayout, 1, 1)
        mainLayout.addLayout(constLayout, 2, 0)
        mainLayout.addLayout(funcLayout, 2, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle("20181710 황예은")

    def buttonClicked(self):

        if self.display.text() == 'Error!':
            self.display.setText('')

        button = self.sender()
        key = button.text()

        if key == '=':
            try:
                result = str(eval(self.display.text()))
            except:
                result = 'Error!'
            self.display.setText(result)
        elif key == 'C':
            self.display.clear()
        elif key in constantList:
            self.display.setText(self.display.text() + constantDic[key])

        elif key in functionList:
            i = functionList.index(key)
            n = self.display.text()
            value = calcFunctions.calc(i, n)
            self.display.setText(str(value))

        else:
            self.display.setText(self.display.text() + key)
コード例 #35
0
    def initUi(self):

        self.setWindowTitle(self.Title)
        self.setStyleSheet(font_size_window)

        self.main_widget = QWidget(self)

        self.layout = QGridLayout(self.main_widget)

        self.groupBox1 = QGroupBox('ML Random Forest Features')
        self.groupBox1Layout = QGridLayout()
        self.groupBox1.setLayout(self.groupBox1Layout)

        self.feature0 = QCheckBox(features_list[0], self)
        self.feature1 = QCheckBox(features_list[1], self)
        self.feature2 = QCheckBox(features_list[2], self)
        self.feature3 = QCheckBox(features_list[3], self)
        self.feature4 = QCheckBox(features_list[4], self)
        self.feature5 = QCheckBox(features_list[5], self)
        self.feature6 = QCheckBox(features_list[6], self)
        self.feature7 = QCheckBox(features_list[7], self)
        self.feature0.setChecked(True)
        self.feature1.setChecked(True)
        self.feature2.setChecked(True)
        self.feature3.setChecked(True)
        self.feature4.setChecked(True)
        self.feature5.setChecked(True)
        self.feature6.setChecked(True)
        self.feature7.setChecked(True)

        self.lblPercentTest = QLabel('Percentage for Test :')
        self.lblPercentTest.adjustSize()

        self.txtPercentTest = QLineEdit(self)
        self.txtPercentTest.setText("30")

        self.btnExecute = QPushButton("Execute RF")
        self.btnExecute.clicked.connect(self.update)

        self.groupBox1Layout.addWidget(self.feature0, 0, 0)
        self.groupBox1Layout.addWidget(self.feature1, 0, 1)
        self.groupBox1Layout.addWidget(self.feature2, 1, 0)
        self.groupBox1Layout.addWidget(self.feature3, 1, 1)
        self.groupBox1Layout.addWidget(self.feature4, 2, 0)
        self.groupBox1Layout.addWidget(self.feature5, 2, 1)
        self.groupBox1Layout.addWidget(self.feature6, 3, 0)
        self.groupBox1Layout.addWidget(self.feature7, 3, 1)
        self.groupBox1Layout.addWidget(self.lblPercentTest, 4, 0)
        self.groupBox1Layout.addWidget(self.txtPercentTest, 4, 1)
        self.groupBox1Layout.addWidget(self.btnExecute, 5, 0)

        self.groupBox2 = QGroupBox('Results from the model')
        self.groupBox2Layout = QVBoxLayout()
        self.groupBox2.setLayout(self.groupBox2Layout)

        self.lblResults = QLabel('Results:')
        self.lblResults.adjustSize()
        self.txtResults = QPlainTextEdit()
        self.lblAccuracy = QLabel('Accuracy:')
        self.txtAccuracy = QLineEdit()

        self.groupBox2Layout.addWidget(self.lblResults)
        self.groupBox2Layout.addWidget(self.txtResults)
        self.groupBox2Layout.addWidget(self.lblAccuracy)
        self.groupBox2Layout.addWidget(self.txtAccuracy)

        #
        # Graphic 1 : Confusion Matrix
        #

        self.fig = Figure()
        self.ax1 = self.fig.add_subplot(111)
        self.axes = [self.ax1]
        self.canvas = FigureCanvas(self.fig)

        self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.canvas.updateGeometry()

        self.groupBoxG1 = QGroupBox('Confusion Matrix')
        self.groupBoxG1Layout = QVBoxLayout()
        self.groupBoxG1.setLayout(self.groupBoxG1Layout)

        self.groupBoxG1Layout.addWidget(self.canvas)

        #
        # Graphic 2 : ROC Curve
        #

        self.fig2 = Figure()
        self.ax2 = self.fig2.add_subplot(111)
        self.axes2 = [self.ax2]
        self.canvas2 = FigureCanvas(self.fig2)

        self.canvas2.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas2.updateGeometry()

        self.groupBoxG2 = QGroupBox('ROC Curve')
        self.groupBoxG2Layout = QVBoxLayout()
        self.groupBoxG2.setLayout(self.groupBoxG2Layout)

        self.groupBoxG2Layout.addWidget(self.canvas2)

        #
        # Graphic 3 : Importance of Features
        #

        self.fig3 = Figure()
        self.ax3 = self.fig3.add_subplot(111)
        self.axes3 = [self.ax3]
        self.canvas3 = FigureCanvas(self.fig3)

        self.canvas3.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas3.updateGeometry()

        self.groupBoxG3 = QGroupBox('Importance of Features')
        self.groupBoxG3Layout = QVBoxLayout()
        self.groupBoxG3.setLayout(self.groupBoxG3Layout)
        self.groupBoxG3Layout.addWidget(self.canvas3)

        #
        # Graphic 4 : ROC Curve by class
        #

        self.fig4 = Figure()
        self.ax4 = self.fig4.add_subplot(111)
        self.axes4 = [self.ax4]
        self.canvas4 = FigureCanvas(self.fig4)

        self.canvas4.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas4.updateGeometry()

        self.groupBoxG4 = QGroupBox('ROC Curve by Class')
        self.groupBoxG4Layout = QVBoxLayout()
        self.groupBoxG4.setLayout(self.groupBoxG4Layout)
        self.groupBoxG4Layout.addWidget(self.canvas4)

        # End of graphs

        self.layout.addWidget(self.groupBox1, 0, 0)
        self.layout.addWidget(self.groupBoxG1, 0, 1)
        self.layout.addWidget(self.groupBox2, 1, 0)
        self.layout.addWidget(self.groupBoxG2, 1, 1)
        self.layout.addWidget(self.groupBoxG3, 0, 2)
        self.layout.addWidget(self.groupBoxG4, 1, 2)

        self.setCentralWidget(self.main_widget)
        self.resize(1100, 700)
        self.show()
コード例 #36
0
class RandomForest(QMainWindow):
    send_fig = pyqtSignal(str)

    def __init__(self):
        super(RandomForest, self).__init__()
        self.Title = "Radom Forest Classifier"
        self.initUi()

    def initUi(self):

        self.setWindowTitle(self.Title)
        self.setStyleSheet(font_size_window)

        self.main_widget = QWidget(self)

        self.layout = QGridLayout(self.main_widget)

        self.groupBox1 = QGroupBox('ML Random Forest Features')
        self.groupBox1Layout = QGridLayout()
        self.groupBox1.setLayout(self.groupBox1Layout)

        self.feature0 = QCheckBox(features_list[0], self)
        self.feature1 = QCheckBox(features_list[1], self)
        self.feature2 = QCheckBox(features_list[2], self)
        self.feature3 = QCheckBox(features_list[3], self)
        self.feature4 = QCheckBox(features_list[4], self)
        self.feature5 = QCheckBox(features_list[5], self)
        self.feature6 = QCheckBox(features_list[6], self)
        self.feature7 = QCheckBox(features_list[7], self)
        self.feature0.setChecked(True)
        self.feature1.setChecked(True)
        self.feature2.setChecked(True)
        self.feature3.setChecked(True)
        self.feature4.setChecked(True)
        self.feature5.setChecked(True)
        self.feature6.setChecked(True)
        self.feature7.setChecked(True)

        self.lblPercentTest = QLabel('Percentage for Test :')
        self.lblPercentTest.adjustSize()

        self.txtPercentTest = QLineEdit(self)
        self.txtPercentTest.setText("30")

        self.btnExecute = QPushButton("Execute RF")
        self.btnExecute.clicked.connect(self.update)

        self.groupBox1Layout.addWidget(self.feature0, 0, 0)
        self.groupBox1Layout.addWidget(self.feature1, 0, 1)
        self.groupBox1Layout.addWidget(self.feature2, 1, 0)
        self.groupBox1Layout.addWidget(self.feature3, 1, 1)
        self.groupBox1Layout.addWidget(self.feature4, 2, 0)
        self.groupBox1Layout.addWidget(self.feature5, 2, 1)
        self.groupBox1Layout.addWidget(self.feature6, 3, 0)
        self.groupBox1Layout.addWidget(self.feature7, 3, 1)
        self.groupBox1Layout.addWidget(self.lblPercentTest, 4, 0)
        self.groupBox1Layout.addWidget(self.txtPercentTest, 4, 1)
        self.groupBox1Layout.addWidget(self.btnExecute, 5, 0)

        self.groupBox2 = QGroupBox('Results from the model')
        self.groupBox2Layout = QVBoxLayout()
        self.groupBox2.setLayout(self.groupBox2Layout)

        self.lblResults = QLabel('Results:')
        self.lblResults.adjustSize()
        self.txtResults = QPlainTextEdit()
        self.lblAccuracy = QLabel('Accuracy:')
        self.txtAccuracy = QLineEdit()

        self.groupBox2Layout.addWidget(self.lblResults)
        self.groupBox2Layout.addWidget(self.txtResults)
        self.groupBox2Layout.addWidget(self.lblAccuracy)
        self.groupBox2Layout.addWidget(self.txtAccuracy)

        #
        # Graphic 1 : Confusion Matrix
        #

        self.fig = Figure()
        self.ax1 = self.fig.add_subplot(111)
        self.axes = [self.ax1]
        self.canvas = FigureCanvas(self.fig)

        self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.canvas.updateGeometry()

        self.groupBoxG1 = QGroupBox('Confusion Matrix')
        self.groupBoxG1Layout = QVBoxLayout()
        self.groupBoxG1.setLayout(self.groupBoxG1Layout)

        self.groupBoxG1Layout.addWidget(self.canvas)

        #
        # Graphic 2 : ROC Curve
        #

        self.fig2 = Figure()
        self.ax2 = self.fig2.add_subplot(111)
        self.axes2 = [self.ax2]
        self.canvas2 = FigureCanvas(self.fig2)

        self.canvas2.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas2.updateGeometry()

        self.groupBoxG2 = QGroupBox('ROC Curve')
        self.groupBoxG2Layout = QVBoxLayout()
        self.groupBoxG2.setLayout(self.groupBoxG2Layout)

        self.groupBoxG2Layout.addWidget(self.canvas2)

        #
        # Graphic 3 : Importance of Features
        #

        self.fig3 = Figure()
        self.ax3 = self.fig3.add_subplot(111)
        self.axes3 = [self.ax3]
        self.canvas3 = FigureCanvas(self.fig3)

        self.canvas3.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas3.updateGeometry()

        self.groupBoxG3 = QGroupBox('Importance of Features')
        self.groupBoxG3Layout = QVBoxLayout()
        self.groupBoxG3.setLayout(self.groupBoxG3Layout)
        self.groupBoxG3Layout.addWidget(self.canvas3)

        #
        # Graphic 4 : ROC Curve by class
        #

        self.fig4 = Figure()
        self.ax4 = self.fig4.add_subplot(111)
        self.axes4 = [self.ax4]
        self.canvas4 = FigureCanvas(self.fig4)

        self.canvas4.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas4.updateGeometry()

        self.groupBoxG4 = QGroupBox('ROC Curve by Class')
        self.groupBoxG4Layout = QVBoxLayout()
        self.groupBoxG4.setLayout(self.groupBoxG4Layout)
        self.groupBoxG4Layout.addWidget(self.canvas4)

        # End of graphs

        self.layout.addWidget(self.groupBox1, 0, 0)
        self.layout.addWidget(self.groupBoxG1, 0, 1)
        self.layout.addWidget(self.groupBox2, 1, 0)
        self.layout.addWidget(self.groupBoxG2, 1, 1)
        self.layout.addWidget(self.groupBoxG3, 0, 2)
        self.layout.addWidget(self.groupBoxG4, 1, 2)

        self.setCentralWidget(self.main_widget)
        self.resize(1100, 700)
        self.show()

    def update(self):
        '''
        Decision Tree ML
        :return:
        '''

        #        ff_happiness["Happiness.Score"]
        self.list_corr_features = pd.DataFrame([])
        if self.feature0.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[0]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[0]]],
                    axis=1)

        if self.feature1.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[1]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[1]]],
                    axis=1)

        if self.feature2.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[2]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[2]]],
                    axis=1)

        if self.feature3.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[3]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[3]]],
                    axis=1)

        if self.feature4.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[4]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[4]]],
                    axis=1)

        if self.feature5.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[5]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[5]]],
                    axis=1)

        if self.feature6.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[6]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[6]]],
                    axis=1)

        if self.feature7.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[7]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[7]]],
                    axis=1)

        vtest_per = float(self.txtPercentTest.text())

        self.ax1.clear()
        self.ax2.clear()
        self.ax3.clear()
        self.ax4.clear()
        self.txtResults.clear()
        self.txtResults.setUndoRedoEnabled(False)

        vtest_per = vtest_per / 100

        X_dt = self.list_corr_features
        y_dt = ff_happiness["Happiness.Scale"]

        class_le = LabelEncoder()

        # fit and transform the class

        y_dt = class_le.fit_transform(y_dt)

        # split the dataset into train and test

        X_train, X_test, y_train, y_test = train_test_split(
            X_dt, y_dt, test_size=vtest_per, random_state=100)

        # perform training with entropy.
        # Decision tree with entropy

        #specify random forest classifier
        self.clf_rf = RandomForestClassifier(n_estimators=100,
                                             random_state=100)

        # perform training
        self.clf_rf.fit(X_train, y_train)

        #-----------------------------------------------------------------------

        # predicton on test using all features
        y_pred = self.clf_rf.predict(X_test)
        y_pred_score = self.clf_rf.predict_proba(X_test)

        # confusion matrix for RandomForest
        conf_matrix = confusion_matrix(y_test, y_pred)

        # clasification report

        self.ff_class_rep = classification_report(y_test, y_pred)
        self.txtResults.appendPlainText(self.ff_class_rep)

        # accuracy score

        self.ff_accuracy_score = accuracy_score(y_test, y_pred) * 100
        self.txtAccuracy.setText(str(self.ff_accuracy_score))

        ##  Ghaph1
        class_names1 = ['', 'Happy', 'Med.Happy', 'Low.Happy', 'Not.Happy']

        self.ax1.matshow(conf_matrix, cmap=plt.cm.get_cmap('Blues', 14))
        self.ax1.set_yticklabels(class_names1)
        self.ax1.set_xticklabels(class_names1, rotation=90)
        self.ax1.set_xlabel('Predicted label')
        self.ax1.set_ylabel('True label')

        for i in range(len(class_names)):
            for j in range(len(class_names)):
                y_pred_score = self.clf_rf.predict_proba(X_test)
                self.ax1.text(j, i, str(conf_matrix[i][j]))

        self.fig.tight_layout()
        self.fig.canvas.draw_idle()

        ## End Graph1

        ## Graph 2 - ROC Curve

        y_test_bin = label_binarize(y_test, classes=[0, 1, 2, 3])
        n_classes = y_test_bin.shape[1]

        #From the sckict learn site
        #https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html
        fpr = dict()
        tpr = dict()
        roc_auc = dict()
        for i in range(n_classes):
            fpr[i], tpr[i], _ = roc_curve(y_test_bin[:, i], y_pred_score[:, i])
            roc_auc[i] = auc(fpr[i], tpr[i])

        # Compute micro-average ROC curve and ROC area
        fpr["micro"], tpr["micro"], _ = roc_curve(y_test_bin.ravel(),
                                                  y_pred_score.ravel())

        roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

        lw = 2
        self.ax2.plot(fpr[2],
                      tpr[2],
                      color='darkorange',
                      lw=lw,
                      label='ROC curve (area = %0.2f)' % roc_auc[2])
        self.ax2.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
        self.ax2.set_xlim([0.0, 1.0])
        self.ax2.set_ylim([0.0, 1.05])
        self.ax2.set_xlabel('False Positive Rate')
        self.ax2.set_ylabel('True Positive Rate')
        self.ax2.set_title('ROC Curve Random Forest')
        self.ax2.legend(loc="lower right")

        self.fig2.tight_layout()
        self.fig2.canvas.draw_idle()
        ######################################
        # Graph - 3 Feature Importances
        #####################################
        # get feature importances
        importances = self.clf_rf.feature_importances_

        # convert the importances into one-dimensional 1darray with corresponding df column names as axis labels
        f_importances = pd.Series(importances, self.list_corr_features.columns)

        # sort the array in descending order of the importances
        f_importances.sort_values(ascending=False, inplace=True)

        # make the bar Plot from f_importances
        #        f_importances.plot(x='Features', y='Importance', kind='bar', figsize=(16, 9), rot=90, fontsize=15)

        X_Features = f_importances.index
        y_Importance = list(f_importances)

        self.ax3.barh(X_Features, y_Importance)
        self.ax3.set_aspect('auto')

        # show the plot
        self.fig3.tight_layout()
        self.fig3.canvas.draw_idle()

        #
        # Graph 4 - ROC Curve by Class
        #
        str_classes = ['HP', 'MEH', 'LOH', 'NH']
        colors = cycle(['magenta', 'darkorange', 'green', 'blue'])
        for i, color in zip(range(n_classes), colors):
            self.ax4.plot(fpr[i],
                          tpr[i],
                          color=color,
                          lw=lw,
                          label='{0} (area = {1:0.2f})'
                          ''.format(str_classes[i], roc_auc[i]))

        self.ax4.plot([0, 1], [0, 1], 'k--', lw=lw)
        self.ax4.set_xlim([0.0, 1.0])
        self.ax4.set_ylim([0.0, 1.05])
        self.ax4.set_xlabel('False Positive Rate')
        self.ax4.set_ylabel('True Positive Rate')
        self.ax4.set_title('ROC Curve by Class')
        self.ax4.legend(loc="lower right")

        # show the plot
        self.fig4.tight_layout()
        self.fig4.canvas.draw_idle()
コード例 #37
0
class DecisionTree(QMainWindow):
    send_fig = pyqtSignal(str)

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

        self.Title = "Decision Tree Classifier"
        self.initUi()

    def initUi(self):

        self.setWindowTitle(self.Title)
        self.setStyleSheet(font_size_window)

        self.main_widget = QWidget(self)

        self.layout = QGridLayout(self.main_widget)

        self.groupBox1 = QGroupBox('ML Decision Tree Features')
        self.groupBox1Layout = QGridLayout()
        self.groupBox1.setLayout(self.groupBox1Layout)

        self.feature0 = QCheckBox(features_list[0], self)
        self.feature1 = QCheckBox(features_list[1], self)
        self.feature2 = QCheckBox(features_list[2], self)
        self.feature3 = QCheckBox(features_list[3], self)
        self.feature4 = QCheckBox(features_list[4], self)
        self.feature5 = QCheckBox(features_list[5], self)
        self.feature6 = QCheckBox(features_list[6], self)
        self.feature7 = QCheckBox(features_list[7], self)
        self.feature0.setChecked(True)
        self.feature1.setChecked(True)
        self.feature2.setChecked(True)
        self.feature3.setChecked(True)
        self.feature4.setChecked(True)
        self.feature5.setChecked(True)
        self.feature6.setChecked(True)
        self.feature7.setChecked(True)

        self.lblPercentTest = QLabel('Percentage for Test :')
        self.lblPercentTest.adjustSize()

        self.txtPercentTest = QLineEdit(self)
        self.txtPercentTest.setText("30")

        self.lblMaxDepth = QLabel('Maximun Depth :')
        self.txtMaxDepth = QLineEdit(self)
        self.txtMaxDepth.setText("3")

        self.btnExecute = QPushButton("Execute DT")
        self.btnExecute.clicked.connect(self.update)

        self.btnDTFigure = QPushButton("View Tree")
        self.btnDTFigure.clicked.connect(self.view_tree)

        self.groupBox1Layout.addWidget(self.feature0, 0, 0)
        self.groupBox1Layout.addWidget(self.feature1, 0, 1)
        self.groupBox1Layout.addWidget(self.feature2, 1, 0)
        self.groupBox1Layout.addWidget(self.feature3, 1, 1)
        self.groupBox1Layout.addWidget(self.feature4, 2, 0)
        self.groupBox1Layout.addWidget(self.feature5, 2, 1)
        self.groupBox1Layout.addWidget(self.feature6, 3, 0)
        self.groupBox1Layout.addWidget(self.feature7, 3, 1)
        self.groupBox1Layout.addWidget(self.lblPercentTest, 4, 0)
        self.groupBox1Layout.addWidget(self.txtPercentTest, 4, 1)
        self.groupBox1Layout.addWidget(self.lblMaxDepth, 5, 0)
        self.groupBox1Layout.addWidget(self.txtMaxDepth, 5, 1)
        self.groupBox1Layout.addWidget(self.btnExecute, 6, 0)
        self.groupBox1Layout.addWidget(self.btnDTFigure, 6, 1)

        self.groupBox2 = QGroupBox('Results from the model')
        self.groupBox2Layout = QVBoxLayout()
        self.groupBox2.setLayout(self.groupBox2Layout)

        self.lblResults = QLabel('Results:')
        self.lblResults.adjustSize()
        self.txtResults = QPlainTextEdit()
        self.lblAccuracy = QLabel('Accuracy:')
        self.txtAccuracy = QLineEdit()

        self.groupBox2Layout.addWidget(self.lblResults)
        self.groupBox2Layout.addWidget(self.txtResults)
        self.groupBox2Layout.addWidget(self.lblAccuracy)
        self.groupBox2Layout.addWidget(self.txtAccuracy)

        #
        # Graphic 1 : Confusion Matrix
        #

        self.fig = Figure()
        self.ax1 = self.fig.add_subplot(111)
        self.axes = [self.ax1]
        self.canvas = FigureCanvas(self.fig)

        self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.canvas.updateGeometry()

        self.groupBoxG1 = QGroupBox('Confusion Matrix')
        self.groupBoxG1Layout = QVBoxLayout()
        self.groupBoxG1.setLayout(self.groupBoxG1Layout)

        self.groupBoxG1Layout.addWidget(self.canvas)

        #########
        ## End Graph1
        #########
        #
        # Graphic 2 : ROC Curve
        #

        self.fig2 = Figure()
        self.ax2 = self.fig2.add_subplot(111)
        self.axes2 = [self.ax2]
        self.canvas2 = FigureCanvas(self.fig2)

        self.canvas2.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas2.updateGeometry()

        self.groupBoxG2 = QGroupBox('ROC Curve')
        self.groupBoxG2Layout = QVBoxLayout()
        self.groupBoxG2.setLayout(self.groupBoxG2Layout)

        self.groupBoxG2Layout.addWidget(self.canvas2)

        #
        # Graphic 3 : ROC Curve by Class
        #

        self.fig3 = Figure()
        self.ax3 = self.fig3.add_subplot(111)
        self.axes3 = [self.ax3]
        self.canvas3 = FigureCanvas(self.fig3)

        self.canvas3.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)

        self.canvas3.updateGeometry()

        self.groupBoxG3 = QGroupBox('ROC Curve by Class')
        self.groupBoxG3Layout = QVBoxLayout()
        self.groupBoxG3.setLayout(self.groupBoxG3Layout)

        self.groupBoxG3Layout.addWidget(self.canvas3)

        ## End of elements o the dashboard

        self.layout.addWidget(self.groupBox1, 0, 0)
        self.layout.addWidget(self.groupBoxG1, 0, 1)
        self.layout.addWidget(self.groupBox2, 0, 2)
        self.layout.addWidget(self.groupBoxG2, 1, 1)
        self.layout.addWidget(self.groupBoxG3, 1, 2)

        self.setCentralWidget(self.main_widget)
        self.resize(1100, 700)
        self.show()

    def update(self):
        '''
        Decision Tree ML
        :return:
        '''

        #        ff_happiness["Happiness.Score"]
        self.list_corr_features = pd.DataFrame([])
        if self.feature0.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[0]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[0]]],
                    axis=1)

        if self.feature1.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[1]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[1]]],
                    axis=1)

        if self.feature2.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[2]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[2]]],
                    axis=1)

        if self.feature3.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[3]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[3]]],
                    axis=1)

        if self.feature4.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[4]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[4]]],
                    axis=1)

        if self.feature5.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[5]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[5]]],
                    axis=1)

        if self.feature6.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[6]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[6]]],
                    axis=1)

        if self.feature7.isChecked():
            if len(self.list_corr_features) == 0:
                self.list_corr_features = ff_happiness[features_list[7]]
            else:
                self.list_corr_features = pd.concat(
                    [self.list_corr_features, ff_happiness[features_list[7]]],
                    axis=1)

        vtest_per = float(self.txtPercentTest.text())
        vmax_depth = float(self.txtMaxDepth.text())

        self.ax1.clear()
        self.ax2.clear()
        self.ax3.clear()
        self.txtResults.clear()
        self.txtResults.setUndoRedoEnabled(False)

        vtest_per = vtest_per / 100

        X_dt = self.list_corr_features
        y_dt = ff_happiness["Happiness.Scale"]

        class_le = LabelEncoder()

        # fit and transform the class

        y_dt = class_le.fit_transform(y_dt)

        # split the dataset into train and test
        X_train, X_test, y_train, y_test = train_test_split(
            X_dt, y_dt, test_size=vtest_per, random_state=100)
        # perform training with entropy.
        # Decision tree with entropy
        self.clf_entropy = DecisionTreeClassifier(criterion="entropy",
                                                  random_state=100,
                                                  max_depth=vmax_depth,
                                                  min_samples_leaf=5)

        # Performing training
        self.clf_entropy.fit(X_train, y_train)

        # predicton on test using entropy
        y_pred_entropy = self.clf_entropy.predict(X_test)

        # confusion matrix for entropy model

        conf_matrix = confusion_matrix(y_test, y_pred_entropy)

        # clasification report

        self.ff_class_rep = classification_report(y_test, y_pred_entropy)
        self.txtResults.appendPlainText(self.ff_class_rep)

        # accuracy score

        self.ff_accuracy_score = accuracy_score(y_test, y_pred_entropy) * 100
        self.txtAccuracy.setText(str(self.ff_accuracy_score))

        self.ax1.set_xlabel('Predicted label')
        self.ax1.set_ylabel('True label')

        class_names1 = ['', 'Happy', 'Med.Happy', 'Low.Happy', 'Not.Happy']

        self.ax1.matshow(conf_matrix, cmap=plt.cm.get_cmap('Blues', 14))
        self.ax1.set_yticklabels(class_names1)
        self.ax1.set_xticklabels(class_names1, rotation=90)

        for i in range(len(class_names)):
            for j in range(len(class_names)):
                y_pred_score = self.clf_entropy.predict_proba(X_test)
                self.ax1.text(j, i, str(conf_matrix[i][j]))

        self.fig.tight_layout()
        self.fig.canvas.draw_idle()

        #####################
        # End Graph 1
        #####################

        ##########################
        # Graph 1 -- ROC
        ##########################

        y_test_bin = label_binarize(y_test, classes=[0, 1, 2, 3])
        n_classes = y_test_bin.shape[1]

        fpr = dict()
        tpr = dict()
        roc_auc = dict()
        for i in range(n_classes):
            fpr[i], tpr[i], _ = roc_curve(y_test_bin[:, i], y_pred_score[:, i])
            roc_auc[i] = auc(fpr[i], tpr[i])

        # Compute micro-average ROC curve and ROC area
        fpr["micro"], tpr["micro"], _ = roc_curve(y_test_bin.ravel(),
                                                  y_pred_score.ravel())

        roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

        lw = 2
        self.ax2.plot(fpr[2],
                      tpr[2],
                      color='darkorange',
                      lw=lw,
                      label='ROC curve (area = %0.2f)' % roc_auc[2])
        self.ax2.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
        self.ax2.set_xlim([0.0, 1.0])
        self.ax2.set_ylim([0.0, 1.05])
        self.ax2.set_xlabel('False Positive Rate')
        self.ax2.set_ylabel('True Positive Rate')
        self.ax2.set_title('ROC Curve Decision Tree')
        self.ax2.legend(loc="lower right")

        self.fig2.tight_layout()
        self.fig2.canvas.draw_idle()
        #--------------------------------
        ### Graph 3 Roc Curve by class
        #---------------------------------
        str_classes = ['HP', 'MEH', 'LOH', 'NH']
        colors = cycle(['magenta', 'darkorange', 'green', 'blue'])
        for i, color in zip(range(n_classes), colors):
            self.ax3.plot(fpr[i],
                          tpr[i],
                          color=color,
                          lw=lw,
                          label='{0} (area = {1:0.2f})'
                          ''.format(str_classes[i], roc_auc[i]))

        self.ax3.plot([0, 1], [0, 1], 'k--', lw=lw)
        self.ax3.set_xlim([0.0, 1.0])
        self.ax3.set_ylim([0.0, 1.05])
        self.ax3.set_xlabel('False Positive Rate')
        self.ax3.set_ylabel('True Positive Rate')
        self.ax3.set_title('ROC Curve by Class')
        self.ax3.legend(loc="lower right")

        # show the plot
        self.fig3.tight_layout()
        self.fig3.canvas.draw_idle()

    def view_tree(self):
        #        dot_data = export_graphviz(self.clf_entropy, filled=True, rounded=True, class_names=class_names,
        #                                   feature_names=ff_happiness.iloc[:, 4:11].columns, out_file=None)
        dot_data = export_graphviz(
            self.clf_entropy,
            filled=True,
            rounded=True,
            class_names=class_names,
            feature_names=self.list_corr_features.columns,
            out_file=None)

        graph = graph_from_dot_data(dot_data)
        graph.write_pdf("decision_tree_entropy.pdf")
        webbrowser.open_new(r'decision_tree_entropy.pdf')
コード例 #38
0
    def __init__(self, schedule: Schedule, parent=None, data=None):
        super(Popup, self).__init__(parent)
        self.schedule = schedule
        self.data, self.class_name = data if data is not None else (None, None)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.setWindowTitle("Add New Scheduled Notes" if data is None else
                            "Edit {} Details".format(self.class_name))

        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.form_layout = QFormLayout()
        self.form_layout.setContentsMargins(0, 0, 0,
                                            self.form_layout.verticalSpacing())
        self.form_layout_widget = QWidget()
        self.form_layout_widget.setLayout(self.form_layout)

        #The amount of fields in the form that come before the block section (name, #blocks, start, end date, color)
        self.rows_before_blocks = 3

        self.event_type = QPushButton()
        event_type_menu = QMenu()
        event_type_menu.addAction("Class")
        event_type_menu.addSection("Event")
        event_type_menu.addAction("One Time Event")
        event_type_menu.addAction("Recurring Event")
        event_type_menu.addAction("One Time Class Event")
        for action in event_type_menu.actions():
            if not action.isSeparator():
                action.triggered.connect(
                    lambda state, x=action.text(): self.set_type(x))
        self.event_type.setMenu(event_type_menu)
        self.form_layout.addRow("Type:", self.event_type)

        #Class Title
        self.name_edit = QLineEdit()
        self.form_layout.addRow("Name:", self.name_edit)
        #Color
        self.color_picker = QColorDialog()
        self.color_button = QPushButton("Pick Color")
        self.color_button.clicked.connect(self.color_picker.open)
        self.color_picker.currentColorChanged.connect(self.update_color)
        self.form_layout.addRow("Color Code:", self.color_button)

        # Initialize widgets to be added later
        self.start_date_model = DateTimePickerSeriesModel(self)
        self.class_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")
        self.event_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")

        self.end_date_model = DateTimePickerSeriesModel(self)
        self.class_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")
        self.event_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")

        self.event_date_model = DateTimePickerSeriesModel(self)
        self.class_event_date = DateTimePickerSeries(self.event_date_model,
                                                     "MMM d yyyy hh:mm:AP")
        self.event_date = DateTimePickerSeries(self.event_date_model,
                                               "MMM d yyyy hh:mm:AP")

        # Blocks
        self.blocks = 1
        self.spin_box = QSpinBox()
        self.spin_box.setValue(1)
        self.spin_box.setMinimum(1)
        self.spin_box.setMaximum(7)
        self.spin_box.valueChanged.connect(self.update_blocks)

        self.class_picker = QPushButton()
        class_picker_menu = QMenu()
        for class_name in self.schedule.schedule.keys():
            class_action = QAction(class_name, parent=class_picker_menu)
            class_action.triggered.connect(lambda state, x=class_action.text():
                                           self.class_picker.setText(x))
            class_picker_menu.addAction(class_action)
        class_picker_menu.aboutToShow.connect(
            lambda: class_picker_menu.setMinimumWidth(self.class_picker.width(
            )))
        self.class_picker.setMenu(class_picker_menu)

        self.stack = QStackedWidget()
        self.stack.setContentsMargins(0, 0, 0, 0)

        class_layout = QFormLayout()
        class_layout.setContentsMargins(0, 0, 0,
                                        class_layout.verticalSpacing())
        class_layout.addRow("Start Date:", self.class_start_date)
        class_layout.addRow("End Date:", self.class_end_date)
        class_layout.addRow("Weekly Blocks:", self.spin_box)
        class_layout.addRow("Block Time:", ClassTimePicker())
        self.class_options = QWidget()
        self.class_options.setSizePolicy(QSizePolicy.Ignored,
                                         QSizePolicy.Ignored)
        self.class_options.setLayout(class_layout)

        recurring_event_layout = QFormLayout()
        recurring_event_layout.setContentsMargins(
            0, 0, 0, recurring_event_layout.verticalSpacing())
        recurring_event_layout.addRow("Start Date:", self.event_start_date)
        recurring_event_layout.addRow("End Date:", self.event_end_date)
        self.recurring_event_time_picker = ClassTimePicker()
        recurring_event_layout.addRow("Event Time:",
                                      self.recurring_event_time_picker)
        self.recurring_event_options = QWidget()
        self.recurring_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                   QSizePolicy.Ignored)
        self.recurring_event_options.setLayout(recurring_event_layout)

        one_time_event_layout = QFormLayout()
        one_time_event_layout.setContentsMargins(
            0, 0, 0, one_time_event_layout.verticalSpacing())
        one_time_event_layout.addRow("Event Date:", self.event_date)
        self.one_time_event_options = QWidget()
        self.one_time_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                  QSizePolicy.Ignored)
        self.one_time_event_options.setLayout(one_time_event_layout)

        class_event_layout = QFormLayout()
        class_event_layout.setContentsMargins(
            0, 0, 0, class_event_layout.verticalSpacing())
        class_event_layout.addRow("Class:", self.class_picker)
        class_event_layout.addRow("Event Date:", self.class_event_date)
        self.class_event_options = QWidget()
        self.class_event_options.setSizePolicy(QSizePolicy.Ignored,
                                               QSizePolicy.Ignored)
        self.class_event_options.setLayout(class_event_layout)

        self.stack.addWidget(self.class_event_options)
        self.stack.addWidget(self.one_time_event_options)
        self.stack.addWidget(self.recurring_event_options)
        self.stack.addWidget(self.class_options)

        self.set_type("Class")

        self.layout.addWidget(self.form_layout_widget)
        self.layout.addWidget(self.stack)
        self.setLayout(self.layout)
        self.show_buttons()

        #Update Values if self.data is defined
        if self.data is not None:
            self.name_edit.setText(self.data["name"])
            self.start_date.setDate(to_qdate(self.data["start"]))
            self.end_date.setDate(to_qdate(self.data["end"]))
            self.color_picker.setCurrentColor(to_qcolor(self.data["color"]))
            self.spin_box.setValue(len(self.data["blocks"]))
            for i in range(0, len(self.data["blocks"])):
                w: ClassTimePicker = self.layout.itemAt(
                    self.rows_before_blocks + i,
                    QFormLayout.FieldRole).widget()
                block = self.data["blocks"][i]
                w.set_day(block["day"])
                w.set_time(block["time"])
コード例 #39
0
class AIGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        #关于表格类的相关初始化代码
        #setSpacing 就是设置每个控件的外边框
        grid = QGridLayout()
        grid.setSpacing(10)

        #各个控件
        #1号控件
        explain = QLabel('请选择您要识别的图片')
        #2号 单号文本框
        self.imgUrl = QLineEdit()
        #3号,按钮
        self.select = QPushButton("选择图片")
        #为按钮添加一个事件处理函数
        self.select.clicked.connect(self.openfile)
        #4号,图片框
        self.imgLab = QLabel("图片")
        self.imgLab.setFrameShape(QFrame.Box)
        #imgLab.setFrameShadow(QFrame.Raised)
        self.imgLab.setLineWidth(1)

        #imgLab.setPixmap(QPixmap(""))
        #5号,多行
        self.info = QTextEdit()

        #将控件进行合理布局
        grid.addWidget(explain, 1, 0)
        grid.addWidget(self.imgUrl, 1, 1)
        grid.addWidget(self.select, 1, 2)
        grid.addWidget(self.imgLab, 2, 0, 5, 3)
        grid.addWidget(self.info, 1, 3, 6, 1)

        #窗口最后的设置
        self.setLayout(grid)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle("AIGUI")
        self.show()

    def openfile(self):
        #打开图片弹窗,选择图片
        self.select_path = QFileDialog.getOpenFileName(
            self, "选择要识别的图片", "/", "Imgae Files(*.jpg *.png)")
        #如果没选择图片,空过
        if not self.select_path[0].strip():
            pass
        else:
            #选择图片后执行下面的内容
            # 设置图片的路径
            self.imgUrl.setText(self.select_path[0])
            #在图片标签框中显示图片
            #1)根据路径pixmap解析图片
            pixmap = QPixmap(self.select_path[0])
            #2)缩放图片
            scalePixmap = pixmap.scaledToWidth(300)
            #scaledPixmap=pixmap.scaled(QSize(311,301))
            #3)显示
            self.imgLab.setPixmap(scalePixmap)
            result = self.identify()
            self.info.setText(result)

    #借助百度AI平台完成植物识别工作
    def identify(self):
        result = Request.BaiduAPI(self.select_path[0])
        return result
コード例 #40
0
class windowFruits(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.left = 10
        self.top = 10
        self.width = 500
        self.height = 500

        self.interface()

    def interface(self):

        # Window background color
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setPalette(p)

        # Label name
        label1 = QLabel("Obraz:", self)
        label2 = QLabel("Wynik:", self)
        self.label = QLabel()

        positionLabels = QGridLayout()
        positionLabels.addWidget(label1, 1, 0)
        positionLabels.addWidget(label2, 1, 1)

        positionLabels.addWidget(self.label, 0, 0, 1, 3)
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)

        pixmap = QPixmap()
        self.label.setPixmap(pixmap)

        # Edit field
        self.fileEdt = QLineEdit()
        self.recognizeEdt = QLineEdit()

        self.recognizeEdt.readonly = True
        self.fileEdt.readonly = True

        positionLabels.addWidget(self.fileEdt, 2, 0)
        positionLabels.addWidget(self.recognizeEdt, 2, 1)

        # Buttons
        loadFileBtn = QPushButton("&Wczytaj obraz", self)
        recognizeBtn = QPushButton("&Rozpoznaj", self)
        endBtn = QPushButton("&Wyjdź", self)
        endBtn.resize(endBtn.sizeHint())

        loadFileBtn.setStyleSheet(
            "color: white; background-color: black; font-size: 16px; padding: 5px;"
        )
        recognizeBtn.setStyleSheet(
            "color: white; background-color: black; font-size: 16px; padding: 5px;"
        )
        endBtn.setStyleSheet(
            "color: white; background-color: red; font-size: 16px; font-weight: bold;"
        )

        positionBtns = QHBoxLayout()
        positionBtns.addWidget(loadFileBtn)
        positionBtns.addWidget(recognizeBtn)

        positionLabels.addLayout(positionBtns, 3, 0, 1, 3)
        positionLabels.addWidget(endBtn, 4, 0, 1, 3)

        self.setLayout(positionLabels)

        endBtn.clicked.connect(self.end)
        loadFileBtn.clicked.connect(self.getfiles)
        recognizeBtn.clicked.connect(self.prediction)

        self.setGeometry(300, 300, 700, 400)
        self.setWindowIcon(QIcon('./icon/icon.png'))
        self.setWindowTitle("Rozpoznawanie owoców")
        self.show()

    def end(self):
        self.close()

    def closeEvent(self, event):

        answer = QMessageBox.question(self, 'Komunikat',
                                      "Czy na pewno koniec?",
                                      QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.No)

        if answer == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.close()

    def getfiles(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, 'Open File', '', 'Images (*.png *.jpeg *.jpg)')
        filePath = fileName
        self.file = filePath
        print(self.file)
        self.fileEdt.setText(fileName)
        image = QImage(fileName)
        self.label.setPixmap(QPixmap.fromImage(image))

    def prediction(self):
        img = load_img(self.file, target_size=(100, 100))
        x = img_to_array(img)
        array = x / 255
        x = np.expand_dims(x, axis=0)
        images = np.vstack([x])
        classes = model.predict_classes(images)
        pred = model.predict(images)
        if classes == 0:
            self.recognizeEdt.setText('Borówka')
        elif classes == 1:
            self.recognizeEdt.setText('Wiśnia')
        elif classes == 2:
            self.recognizeEdt.setText('Brzoskwinia')
        elif classes == 3:
            self.recognizeEdt.setText('Malina')
        else:
            self.recognizeEdt.setText('N/A')
コード例 #41
0
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowIcon(
            QIcon(
                "C:/Users/dava8001/AppData/Local/Programs/Python/Python36-32/test-scan1/barcode.png"
            ))
        self.setWindowTitle("Barcode Scanner")
        self.resize(500, 400)
        self.allFiles = 0

        self.InitWindow()

    def InitWindow(self):
        self.button = QPushButton("Choose Folder Path")
        self.button.clicked.connect(self.getFolder)
        self.lineEdit = QLineEdit("C:/")
        self.lineEdit.setReadOnly(True)

        self.btnScan = QPushButton("Scan")
        self.btnScan.clicked.connect(lambda folder=self.lineEdit.text(): self.
                                     scan(self.lineEdit.text()))
        self.btnScan.setEnabled(False)

        self.btnClose = QPushButton("Close")
        self.btnClose.clicked.connect(self.CloseApp)
        self.textEdit = QTextEdit(self)
        self.pbar = QProgressBar(self)

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        layoutH = QHBoxLayout()
        layoutH.addWidget(self.button)
        layoutH.addStretch(1)
        layoutH.addWidget(self.btnScan)

        layoutV = QVBoxLayout(centralWidget)
        layoutV.addLayout(layoutH)
        layoutV.addWidget(self.lineEdit)
        layoutV.addWidget(self.textEdit)
        layoutV.addWidget(self.pbar)
        layoutV.addWidget(self.btnClose)

    def scan(self, folder):

        self.btnScan.setEnabled(False)
        self.thread = AThread(folder, self.allFiles)
        self.thread.finished.connect(self.closeW)
        self.thread.start()
        self.thread.updateSignal.connect(self.update)

    def update(self, texts, val):
        text = "\n".join(texts)
        self.textEdit.append(text)
        self.pbar.setValue(val)

    def closeW(self):
        self.textEdit.append("--- Directory scan complete! ---")
        self.btnScan.setEnabled(True)

    def getFolder(self):
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        folder = QFileDialog.getExistingDirectory(self,
                                                  "Open Folder",
                                                  self.lineEdit.text(),
                                                  options=options)
        if folder:
            self.pbar.setValue(0)
            self.lineEdit.setText(folder)

            self.textEdit.append("\n{}:".format(folder))
            self.allFiles = 0
            for root, dirs, files in os.walk(folder):
                self.allFiles += len(files)
            self.textEdit.append("    total files: {}".format(self.allFiles))
            self.btnScan.setEnabled(True)
        else:
            self.textEdit.append("Sorry, choose a directory to scan!")
            self.btnScan.setEnabled(False)

    def CloseApp(self):
        reply = QMessageBox.question(self, "Close Message",
                                     "Are you sure you want to close?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.close()
コード例 #42
0
class Popup(QDialog):
    def __init__(self, schedule: Schedule, parent=None, data=None):
        super(Popup, self).__init__(parent)
        self.schedule = schedule
        self.data, self.class_name = data if data is not None else (None, None)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.setWindowTitle("Add New Scheduled Notes" if data is None else
                            "Edit {} Details".format(self.class_name))

        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.form_layout = QFormLayout()
        self.form_layout.setContentsMargins(0, 0, 0,
                                            self.form_layout.verticalSpacing())
        self.form_layout_widget = QWidget()
        self.form_layout_widget.setLayout(self.form_layout)

        #The amount of fields in the form that come before the block section (name, #blocks, start, end date, color)
        self.rows_before_blocks = 3

        self.event_type = QPushButton()
        event_type_menu = QMenu()
        event_type_menu.addAction("Class")
        event_type_menu.addSection("Event")
        event_type_menu.addAction("One Time Event")
        event_type_menu.addAction("Recurring Event")
        event_type_menu.addAction("One Time Class Event")
        for action in event_type_menu.actions():
            if not action.isSeparator():
                action.triggered.connect(
                    lambda state, x=action.text(): self.set_type(x))
        self.event_type.setMenu(event_type_menu)
        self.form_layout.addRow("Type:", self.event_type)

        #Class Title
        self.name_edit = QLineEdit()
        self.form_layout.addRow("Name:", self.name_edit)
        #Color
        self.color_picker = QColorDialog()
        self.color_button = QPushButton("Pick Color")
        self.color_button.clicked.connect(self.color_picker.open)
        self.color_picker.currentColorChanged.connect(self.update_color)
        self.form_layout.addRow("Color Code:", self.color_button)

        # Initialize widgets to be added later
        self.start_date_model = DateTimePickerSeriesModel(self)
        self.class_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")
        self.event_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")

        self.end_date_model = DateTimePickerSeriesModel(self)
        self.class_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")
        self.event_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")

        self.event_date_model = DateTimePickerSeriesModel(self)
        self.class_event_date = DateTimePickerSeries(self.event_date_model,
                                                     "MMM d yyyy hh:mm:AP")
        self.event_date = DateTimePickerSeries(self.event_date_model,
                                               "MMM d yyyy hh:mm:AP")

        # Blocks
        self.blocks = 1
        self.spin_box = QSpinBox()
        self.spin_box.setValue(1)
        self.spin_box.setMinimum(1)
        self.spin_box.setMaximum(7)
        self.spin_box.valueChanged.connect(self.update_blocks)

        self.class_picker = QPushButton()
        class_picker_menu = QMenu()
        for class_name in self.schedule.schedule.keys():
            class_action = QAction(class_name, parent=class_picker_menu)
            class_action.triggered.connect(lambda state, x=class_action.text():
                                           self.class_picker.setText(x))
            class_picker_menu.addAction(class_action)
        class_picker_menu.aboutToShow.connect(
            lambda: class_picker_menu.setMinimumWidth(self.class_picker.width(
            )))
        self.class_picker.setMenu(class_picker_menu)

        self.stack = QStackedWidget()
        self.stack.setContentsMargins(0, 0, 0, 0)

        class_layout = QFormLayout()
        class_layout.setContentsMargins(0, 0, 0,
                                        class_layout.verticalSpacing())
        class_layout.addRow("Start Date:", self.class_start_date)
        class_layout.addRow("End Date:", self.class_end_date)
        class_layout.addRow("Weekly Blocks:", self.spin_box)
        class_layout.addRow("Block Time:", ClassTimePicker())
        self.class_options = QWidget()
        self.class_options.setSizePolicy(QSizePolicy.Ignored,
                                         QSizePolicy.Ignored)
        self.class_options.setLayout(class_layout)

        recurring_event_layout = QFormLayout()
        recurring_event_layout.setContentsMargins(
            0, 0, 0, recurring_event_layout.verticalSpacing())
        recurring_event_layout.addRow("Start Date:", self.event_start_date)
        recurring_event_layout.addRow("End Date:", self.event_end_date)
        self.recurring_event_time_picker = ClassTimePicker()
        recurring_event_layout.addRow("Event Time:",
                                      self.recurring_event_time_picker)
        self.recurring_event_options = QWidget()
        self.recurring_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                   QSizePolicy.Ignored)
        self.recurring_event_options.setLayout(recurring_event_layout)

        one_time_event_layout = QFormLayout()
        one_time_event_layout.setContentsMargins(
            0, 0, 0, one_time_event_layout.verticalSpacing())
        one_time_event_layout.addRow("Event Date:", self.event_date)
        self.one_time_event_options = QWidget()
        self.one_time_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                  QSizePolicy.Ignored)
        self.one_time_event_options.setLayout(one_time_event_layout)

        class_event_layout = QFormLayout()
        class_event_layout.setContentsMargins(
            0, 0, 0, class_event_layout.verticalSpacing())
        class_event_layout.addRow("Class:", self.class_picker)
        class_event_layout.addRow("Event Date:", self.class_event_date)
        self.class_event_options = QWidget()
        self.class_event_options.setSizePolicy(QSizePolicy.Ignored,
                                               QSizePolicy.Ignored)
        self.class_event_options.setLayout(class_event_layout)

        self.stack.addWidget(self.class_event_options)
        self.stack.addWidget(self.one_time_event_options)
        self.stack.addWidget(self.recurring_event_options)
        self.stack.addWidget(self.class_options)

        self.set_type("Class")

        self.layout.addWidget(self.form_layout_widget)
        self.layout.addWidget(self.stack)
        self.setLayout(self.layout)
        self.show_buttons()

        #Update Values if self.data is defined
        if self.data is not None:
            self.name_edit.setText(self.data["name"])
            self.start_date.setDate(to_qdate(self.data["start"]))
            self.end_date.setDate(to_qdate(self.data["end"]))
            self.color_picker.setCurrentColor(to_qcolor(self.data["color"]))
            self.spin_box.setValue(len(self.data["blocks"]))
            for i in range(0, len(self.data["blocks"])):
                w: ClassTimePicker = self.layout.itemAt(
                    self.rows_before_blocks + i,
                    QFormLayout.FieldRole).widget()
                block = self.data["blocks"][i]
                w.set_day(block["day"])
                w.set_time(block["time"])

    def show_buttons(self):
        buttonBox = QDialogButtonBox(QDialogButtonBox.Save
                                     | QDialogButtonBox.Cancel,
                                     parent=self)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.setOrientation(Qt.Horizontal)
        self.layout.addWidget(buttonBox)

    def set_type(self, event_type: str):
        if self.event_type.text() == event_type:
            return
        self.event_type.setText(event_type)
        self.stack.currentWidget().setSizePolicy(QSizePolicy.Ignored,
                                                 QSizePolicy.Ignored)
        if event_type == "Class":
            self.class_options.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Expanding)
            self.class_options.adjustSize()
            self.stack.setCurrentWidget(self.class_options)
        elif event_type == "Recurring Event":
            self.recurring_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                       QSizePolicy.Expanding)
            self.recurring_event_options.adjustSize()
            self.stack.setCurrentWidget(self.recurring_event_options)
        elif event_type == "One Time Event":
            self.one_time_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                      QSizePolicy.Expanding)
            self.one_time_event_options.adjustSize()
            self.stack.setCurrentWidget(self.one_time_event_options)
        elif event_type == "One Time Class Event":
            self.class_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                   QSizePolicy.Expanding)
            self.class_event_options.adjustSize()
            self.stack.setCurrentWidget(self.class_event_options)
        self.stack.adjustSize()
        max_width = 0
        for i in range(self.form_layout.rowCount()):
            widget = self.form_layout.itemAt(i, QFormLayout.LabelRole).widget()
            widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            widget.adjustSize()
            max_width = max(widget.size().width(), max_width)
        # noinspection PyTypeChecker
        current_widget_layout: QFormLayout = self.stack.currentWidget().layout(
        )
        for i in range(current_widget_layout.rowCount()):
            widget = current_widget_layout.itemAt(
                i, QFormLayout.LabelRole).widget()
            widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            widget.adjustSize()
            max_width = max(widget.size().width(), max_width)
        for i in range(self.form_layout.rowCount()):
            self.form_layout.itemAt(
                i, QFormLayout.LabelRole).widget().setMinimumWidth(max_width)
        for i in range(current_widget_layout.rowCount()):
            current_widget_layout.itemAt(
                i, QFormLayout.LabelRole).widget().setMinimumWidth(max_width)
        self.adjustSize()

    def update_color(self):
        self.color_button.setStyleSheet(
            "background-color: rgb({},{},{})".format(
                self.color_picker.currentColor().red(),
                self.color_picker.currentColor().green(),
                self.color_picker.currentColor().blue()))

    def update_blocks(self, value):
        if self.blocks == value:
            return
        old_blocks = self.blocks
        self.blocks = value
        class_options_layout: QFormLayout = self.class_options.layout()
        if self.blocks > old_blocks:
            #Change label of block 1
            if old_blocks == 1:
                class_options_layout.itemAt(
                    self.rows_before_blocks,
                    QFormLayout.LabelRole).widget().setText("Block 1 Time:")
            for i in range(1, self.blocks - old_blocks + 1):
                offset = self.rows_before_blocks + old_blocks + i - 1
                widget = class_options_layout.itemAt(offset,
                                                     QFormLayout.FieldRole)
                label = class_options_layout.itemAt(offset,
                                                    QFormLayout.LabelRole)
                if widget is not None and label is not None:
                    widget = widget.widget()
                    label = label.widget()
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
                    label.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
                    widget.adjustSize()
                    label.adjustSize()
                    widget.show()
                    label.show()
                else:
                    picker = ClassTimePicker()
                    picker.sizePolicy().setRetainSizeWhenHidden(False)
                    class_options_layout.addRow(
                        "Block {} Time:".format(old_blocks + i), picker)
        elif self.blocks < old_blocks:
            if self.blocks == 1:
                class_options_layout.itemAt(
                    self.rows_before_blocks,
                    QFormLayout.LabelRole).widget().setText("Block Time:")
            for i in range(old_blocks - self.blocks):
                offset = self.rows_before_blocks + old_blocks + i - 1
                widget = class_options_layout.itemAt(
                    offset, QFormLayout.FieldRole).widget()
                label = class_options_layout.itemAt(
                    offset, QFormLayout.LabelRole).widget()
                print(widget.size())
                widget.hide()
                label.hide()
                widget.adjustSize()
                label.adjustSize()
                self.class_options.adjustSize()
                self.stack.adjustSize()
                self.adjustSize()

                print(widget.size())

        # self.class_options.adjustSize()
        # self.stack.adjustSize()
        # self.adjustSize()

    def get_name(self):
        return self.name_edit.text()

    def get_data(self):
        event_type = self.event_type.text()
        data = {
            "type": event_type.lower(),
            "name": self.get_name(),
            "color": {
                "r": self.color_picker.currentColor().red(),
                "g": self.color_picker.currentColor().green(),
                "b": self.color_picker.currentColor().blue(),
            }
        }
        if event_type == "Class":
            block_data = []
            # noinspection PyTypeChecker
            class_layout: QFormLayout = self.stack.currentWidget().layout()
            for row in range(self.rows_before_blocks, class_layout.rowCount()):
                # noinspection PyTypeChecker
                block_widget: ClassTimePicker = class_layout.itemAt(
                    row, QFormLayout.FieldRole).widget()
                if block_widget.isHidden():
                    continue
                time = block_widget.get_time()
                block_data.append({
                    "day": block_widget.day_picker.get_day(),
                    "time": {
                        "hour": time.hour(),
                        "minute": time.minute()
                    }
                })
            data["blocks"] = block_data
        if event_type in ["Class", "Recurring Event"]:
            start_date = self.start_date_model.content.date()
            data["start"] = {
                "day": start_date.day(),
                "month": start_date.month(),
                "year": start_date.year()
            }
            end_date = self.end_date_model.content.date()
            data["end"] = {
                "day": end_date.day(),
                "month": end_date.month(),
                "year": end_date.year()
            }
        if event_type == "Recurring Event":
            data["day"] = self.recurring_event_time_picker.day_picker.get_day()
            time = self.recurring_event_time_picker.get_time()
            data["time"] = {"hour": time.hour(), "minute": time.minute()}
        if event_type == "One Time Class Event":
            data["class_name"] = self.class_picker.text()
        if event_type in ["One Time Event", "One Time Class Event"]:
            date_time = self.event_date_model.content
            date = date_time.date()
            time = date_time.time()
            data["date"] = {
                "day": date.day(),
                "month": date.month(),
                "year": date.year(),
            }
            data["time"] = {"hour": time.hour(), "minute": time.minute()}
        return data

    def accept(self):
        event_type = self.event_type.text()
        if event_type == "":
            error = QMessageBox()
            error.setText("Please select a type for the event.")
            error.exec_()
            self.event_type.setFocus()
            return
        # Check Name
        if len(self.get_name()) == 0:
            error = QMessageBox()
            error.setText("Please enter a name for the event.")
            error.exec_()
            self.name_edit.setFocus()
            return
        if event_type in ["Class", "Recurring Event"]:
            # Check Start/End Date
            start_date = self.start_date_model.content.date()
            end_date = self.end_date_model.content.date()
            if start_date >= end_date:
                error = QMessageBox()
                error.setText("End date cannot {} start date.".format(
                    "be equal to" if start_date ==
                    end_date else "come before"))
                error.exec_()
                if event_type == "Class":
                    self.class_end_date.setFocus()
                else:
                    self.event_end_date.setFocus()
                return
            if event_type == "Class":
                # Check Blocks
                # noinspection PyTypeChecker
                class_layout: QFormLayout = self.stack.currentWidget().layout()
                print(class_layout)
                for row in range(self.rows_before_blocks,
                                 class_layout.rowCount()):
                    block_widget = class_layout.itemAt(
                        row, QFormLayout.FieldRole).widget()
                    if block_widget.isHidden():
                        continue
                    # Make sure a day is selected for each block
                    if not block_widget.is_valid():
                        block_name = "the class block" if self.blocks == 1 else str.lower(
                            class_layout.itemAt(row, QFormLayout.LabelRole).
                            widget().text()).replace(" time:", "")
                        error = QMessageBox()
                        error.setText(
                            "Please select a valid day for {}.".format(
                                block_name))
                        error.exec_()
                        return
                    # Check for duplicate blocks
                    for other in range(self.rows_before_blocks,
                                       class_layout.rowCount() - 1):
                        if row == other:
                            continue
                        other_block_widget = class_layout.itemAt(
                            other, QFormLayout.FieldRole).widget()
                        same_time = block_widget.get_time(
                        ) == other_block_widget.get_time()
                        same_day = block_widget.day_picker.get_day(
                        ) == other_block_widget.day_picker.get_day()
                        if same_time and same_day:
                            error = QMessageBox()
                            error.setText(
                                "Block {} and {} cannot have the same day and time."
                                .format(row - self.rows_before_blocks + 1,
                                        other - self.rows_before_blocks + 1))
                            error.exec_()
                            return
            if event_type == "Recurring Event":
                # Make sure a day is selected
                if not self.recurring_event_time_picker.is_valid():
                    error = QMessageBox()
                    error.setText("Please select a valid day for this event.")
                    error.exec_()
                    self.recurring_event_time_picker.setFocus()
                    return
        if event_type == "One Time Class Event":
            # Check Class
            if len(self.class_picker.text()) == 0:
                error = QMessageBox()
                error.setText("Please select a class for this event.")
                error.exec_()
                self.class_picker.setFocus()
                return
        if self.data is not None:
            error = QMessageBox()
            error.setText(
                "Changes will not be saved because this feature is incomplete."
            )
            error.exec_()
            super(Popup, self).reject()
        # Valid name
        elif self.get_name() in self.schedule.schedule.keys():
            error = QMessageBox()
            error.setText(
                "An event with this name already exists, would you like to overwrite it?"
            )
            error.setStandardButtons(error.Apply | error.Cancel)
            result = error.exec_()
            if result == error.Apply:
                self.schedule.edit_event(self.get_data())
                self.reject()
            elif result == error.Cancel:
                self.name_edit.setFocus()
        super(Popup, self).accept()

    def reject(self):
        super(Popup, self).reject()
コード例 #43
0
ファイル: clases.py プロジェクト: elramirezv123/CodeReader
class CheckItem(QGroupBox):
    def __init__(self, parent):
        super().__init__(parent)
        self.setGeometry(0,0, SCREEN_WIDTH, SCREEN_HEIGHT)

        self.label = QLabel('Escanée un producto',self)
        self.label.setGeometry(col3, row, col4, row)
        self.label.setFont(QFont("Times", 15))
        self.loaded = False
        self.index = -1

        self.codeInput = QLineEdit(self)
        self.codeInput.setGeometry(0, 0, 0, 0)
        self.codeInput.setFocus()
        self.codeInput.setFont(QFont("Times", 15))

        self.itemShower = QGroupBox(self)
        self.itemShower.setGeometry(col1, 150, col8, row17)

    def loadQty(self, value):
        self.codeInput.setFocus()
        if self.loaded:
            self.fields['Cantidad'].setText(self.parent().database[value]['Cantidad'])
            if self.fields['Cantidad'].text() == '0':
                self.plus_button.setEnabled(False)
            self.take_value.setText('0')
            self.less_button.setEnabled(False)

    def showItem(self):
        self.itemShower.hide()

        self.itemShower = QGroupBox(self)
        self.itemShower.setGeometry(col1, 150, col8, row17)
        self.index = -1
        for i in self.parent().database:
            self.index += 1
            if i['Codigo'] == self.codeInput.text():
                self.loaded = True
                self.takeButton = QPushButton('Retirar', self.itemShower)
                self.takeButton.setGeometry(col3, row15, col2, row)
                self.takeButton.setFont(QFont("Times", 15))
                self.takeButton.clicked.connect(self.takeItem)
                self.takeButton.show()
                self.imageshower = QLabel(self.itemShower)
                self.imageshower.setGeometry(col2,row11 ,col4,row3)
                self.imageshower.show()

                self.plus_button = QPushButton('+', self.itemShower)
                self.plus_button.setGeometry(col5, row9, col, row)
                self.plus_button.show()
                self.plus_button.clicked.connect(self.add)

                self.take_value = QLabel('0', self.itemShower)
                self.take_value.setGeometry(col4 + 30, row9, col / 2 ,row)
                self.take_value.show()
                self.take_value.setFont(QFont("Times", 15))

                self.less_button = QPushButton('-', self.itemShower)
                self.less_button.setGeometry(col3, row9, col, row)
                self.less_button.show()
                self.less_button.clicked.connect(self.less)
                self.less_button.setEnabled(False)



                self.fileName = ''

                self.fields = {
                'Codigo':QLabel(i['Codigo'], self.itemShower),
                'Nombre':QLabel(i['Nombre'], self.itemShower),
                'Marca':QLabel(i['Marca'], self.itemShower),
                'Precio':QLabel(i['Precio'], self.itemShower),
                'Cantidad':QLabel(i['Cantidad'], self.itemShower)
                }
                self.imageshower.setPixmap(QPixmap(i['Imagen']).scaled(col4, row3))
                contador = 0
                for i in self.fields:
                    label = QLabel(i + ': ', self.itemShower)
                    label.setGeometry(col, (row + 70) * contador , col + 40, row)
                    label.setFont(QFont("Times",15))
                    label.show()

                    edit = self.fields[i]
                    edit.setGeometry(col2 + 50, (row +70) * contador , col6, row)
                    edit.setFont(QFont("Times",15))
                    edit.show()

                    contador += 1
                self.itemShower.show()
                if self.fields['Cantidad'].text() == '0':
                    self.plus_button.setEnabled(False)
                break

        self.codeInput.setFocus()
        self.codeInput.setText('')


    def takeItem(self):
        if int(self.fields['Cantidad'].text()) >= int(self.take_value.text()):
            self.parent().database[self.index]['Cantidad'] = str(int(self.parent().database[self.index]['Cantidad']) - int(self.take_value.text()))
            self.loadQty(self.index)
            with open('db.json','w') as file:
                json.dump(self.parent().database, file)
        self.codeInput.setFocus()
        self.codeInput.setText('')

    def add(self):
        if int(self.take_value.text()) + 1 >= int(self.fields['Cantidad'].text()):
            self.plus_button.setEnabled(False)
        self.take_value.setText(str(int(self.take_value.text()) + 1))
        self.less_button.setEnabled(True)

    def less(self):
        self.take_value.setText(str(int(self.take_value.text()) - 1))
        self.plus_button.setEnabled(True)
        if self.take_value.text() == '0':
            self.less_button.setEnabled(False)

    def keyPressEvent(self, event):
        self.showItem()
        self.codeInput.setFocus()
コード例 #44
0
ファイル: monsterbuilder.py プロジェクト: treymerkley/yendor
    def tab(self):
        """sets up the actual tab layout"""
        # Initializing the complete layout
        self.layout = QVBoxLayout()

        name_line_edit_label = QLabel("Name:")
        self.name_line_edit = QLineEdit()

        # This sets up the level scaling for
        # the resulting character. The current
        # cap is at 30, but the algorithm should
        # continue to function to any level.
        level_combo_box_label = QLabel("Level:")
        self.level_combo_box = QComboBox()
        for i in range(1, 31):
            self.level_combo_box.addItem(str(i))
            i += 1

        # This sets up the elements box
        size_combo_box_label = QLabel("Size:")
        self.size_combo_box = QComboBox()
        list_of_sizes = ('Fine', 'Diminutive', 'Tiny', 'Small',
                         'Medium', 'Large', 'Huge', 'Gargantuan',
                         'Colossal')
        self.size_combo_box.addItems(list_of_sizes)

        # This sets up the elements box
        skills_combo_box_label = QLabel("Skills:")
        self.skills_combo_box = QComboBox()
        list_of_skills = ('Babble', 'Blindsense', 'Blindsight', 'Breath Weapon',
                          'Constrict', 'Create Spawn', 'Damage Reduction',
                          'Darkvision', 'Enslave', 'Etherealness',
                          'Fast Healing', 'Firey Aura', 'Flight',
                          'Improved Grab', 'Incorporeality', 'Invisibility',
                          'Leader', 'Low-Light Vision', 'Earth Mastery',
                          'Water Mastery', 'Fire Mastery', 'Air Mastery',
                          'Mindless', 'Natural Cunning', 'Pounce',
                          'Powerful Charge', 'Push', 'Rake', 'Regeneration',
                          'Scent', 'Snatch', 'Stonecunning', 'Swallow Whole',
                          'Torment', 'Trample', 'Tremorsense')
        self.skills_combo_box.addItems(list_of_skills)

        # This is a toggle modifier to increasethe strength
        # of the monster and the loot it's carrying. It's
        # entirely optional and can be removed, or the
        # strength of the modifier can be changed in the "math" folder.
        boss_check_box_label = QLabel("Boss:")
        self.boss_check_box = QCheckBox()

        # These are the buttons for saving and generating new NPCs.
        self.save_button = QPushButton("Save")
        bottom_buttons_layout = QHBoxLayout()
        bottom_buttons_layout.addStretch(1)
        bottom_buttons_layout.addWidget(self.save_button)

        # This builds the textbox that you see the resulting character in
        main_text_box = QTextEdit()
        text_box_layout = QHBoxLayout()
        text_box_label = QLabel("Description: ")
        text_box_layout.addWidget(text_box_label)
        text_box_layout.addWidget(main_text_box)

        # This creates the layout for the controls. Any new fields should
        # follow this same general convention.
        controls = QScrollArea()
        controls.setFixedHeight(100)
        controls.setWidgetResizable(False)
        controls_layout = QHBoxLayout(controls)

        controls.setWidget(controls_layout.widget())

        controls_layout.addWidget(level_combo_box_label)
        controls_layout.addWidget(self.level_combo_box)
        controls_layout.addWidget(name_line_edit_label)
        controls_layout.addWidget(self.name_line_edit)
        controls_layout.addWidget(skills_combo_box_label)
        controls_layout.addWidget(self.skills_combo_box)
        controls_layout.addWidget(size_combo_box_label)
        controls_layout.addWidget(self.size_combo_box)
        controls_layout.addWidget(boss_check_box_label)
        controls_layout.addWidget(self.boss_check_box)

        # Adds all of the disparate groups of controls to the total layout
        self.layout.addWidget(controls)
        self.layout.addLayout(text_box_layout)
        self.layout.addLayout(bottom_buttons_layout)
コード例 #45
0
class SpreadSheet(QMainWindow):

    dateFormats = ["dd/M/yyyy", "yyyy/M/dd", "dd.MM.yyyy"]

    currentDateFormat = dateFormats[0]

    def __init__(self, rows, cols, parent=None):
        super(SpreadSheet, self).__init__(parent)

        self.toolBar = QToolBar()
        self.addToolBar(self.toolBar)
        self.formulaInput = QLineEdit()
        self.cellLabel = QLabel(self.toolBar)
        self.cellLabel.setMinimumSize(80, 0)
        self.toolBar.addWidget(self.cellLabel)
        self.toolBar.addWidget(self.formulaInput)
        self.table = QTableWidget(rows, cols, self)
        for c in range(cols):
            character = chr(ord("A") + c)
            self.table.setHorizontalHeaderItem(c, QTableWidgetItem(character))

        self.table.setItemPrototype(self.table.item(rows - 1, cols - 1))
        self.table.setItemDelegate(SpreadSheetDelegate(self))
        self.createActions()
        self.updateColor(0)
        self.setupMenuBar()
        self.setupContents()
        self.setupContextMenu()
        self.setCentralWidget(self.table)
        self.statusBar()
        self.table.currentItemChanged.connect(self.updateStatus)
        self.table.currentItemChanged.connect(self.updateColor)
        self.table.currentItemChanged.connect(self.updateLineEdit)
        self.table.itemChanged.connect(self.updateStatus)
        self.formulaInput.returnPressed.connect(self.returnPressed)
        self.table.itemChanged.connect(self.updateLineEdit)
        self.setWindowTitle("Spreadsheet")

    def createActions(self):
        self.cell_sumAction = QAction("Sum", self)
        self.cell_sumAction.triggered.connect(self.actionSum)

        self.cell_addAction = QAction("&Add", self)
        self.cell_addAction.setShortcut(Qt.CTRL | Qt.Key_Plus)
        self.cell_addAction.triggered.connect(self.actionAdd)

        self.cell_subAction = QAction("&Subtract", self)
        self.cell_subAction.setShortcut(Qt.CTRL | Qt.Key_Minus)
        self.cell_subAction.triggered.connect(self.actionSubtract)

        self.cell_mulAction = QAction("&Multiply", self)
        self.cell_mulAction.setShortcut(Qt.CTRL | Qt.Key_multiply)
        self.cell_mulAction.triggered.connect(self.actionMultiply)

        self.cell_divAction = QAction("&Divide", self)
        self.cell_divAction.setShortcut(Qt.CTRL | Qt.Key_division)
        self.cell_divAction.triggered.connect(self.actionDivide)

        self.fontAction = QAction("Font...", self)
        self.fontAction.setShortcut(Qt.CTRL | Qt.Key_F)
        self.fontAction.triggered.connect(self.selectFont)

        self.colorAction = QAction(QIcon(QPixmap(16, 16)),
                                   "Background &Color...", self)
        self.colorAction.triggered.connect(self.selectColor)

        self.clearAction = QAction("Clear", self)
        self.clearAction.setShortcut(Qt.Key_Delete)
        self.clearAction.triggered.connect(self.clear)

        self.aboutSpreadSheet = QAction("About Spreadsheet", self)
        self.aboutSpreadSheet.triggered.connect(self.showAbout)

        self.exitAction = QAction("E&xit", self)
        self.exitAction.setShortcut(QKeySequence.Quit)
        self.exitAction.triggered.connect(QApplication.instance().quit)

        self.printAction = QAction("&Print", self)
        self.printAction.setShortcut(QKeySequence.Print)
        self.printAction.triggered.connect(self.print_)

        self.firstSeparator = QAction(self)
        self.firstSeparator.setSeparator(True)

        self.secondSeparator = QAction(self)
        self.secondSeparator.setSeparator(True)

    def setupMenuBar(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.dateFormatMenu = self.fileMenu.addMenu("&Date format")
        self.dateFormatGroup = QActionGroup(self)
        for f in self.dateFormats:
            action = QAction(f,
                             self,
                             checkable=True,
                             triggered=self.changeDateFormat)
            self.dateFormatGroup.addAction(action)
            self.dateFormatMenu.addAction(action)
            if f == self.currentDateFormat:
                action.setChecked(True)

        self.fileMenu.addAction(self.printAction)
        self.fileMenu.addAction(self.exitAction)
        self.cellMenu = self.menuBar().addMenu("&Cell")
        self.cellMenu.addAction(self.cell_addAction)
        self.cellMenu.addAction(self.cell_subAction)
        self.cellMenu.addAction(self.cell_mulAction)
        self.cellMenu.addAction(self.cell_divAction)
        self.cellMenu.addAction(self.cell_sumAction)
        self.cellMenu.addSeparator()
        self.cellMenu.addAction(self.colorAction)
        self.cellMenu.addAction(self.fontAction)
        self.menuBar().addSeparator()
        self.aboutMenu = self.menuBar().addMenu("&Help")
        self.aboutMenu.addAction(self.aboutSpreadSheet)

    def changeDateFormat(self):
        action = self.sender()
        oldFormat = self.currentDateFormat
        newFormat = self.currentDateFormat = action.text()
        for row in range(self.table.rowCount()):
            item = self.table.item(row, 1)
            date = QDate.fromString(item.text(), oldFormat)
            item.setText(date.toString(newFormat))

    def updateStatus(self, item):
        if item and item == self.table.currentItem():
            self.statusBar().showMessage(item.data(Qt.StatusTipRole), 1000)
            self.cellLabel.setText(
                "Cell: (%s)" %
                encode_pos(self.table.row(item), self.table.column(item)))

    def updateColor(self, item):
        pixmap = QPixmap(16, 16)
        color = QColor()
        if item:
            color = item.backgroundColor()
        if not color.isValid():
            color = self.palette().base().color()
        painter = QPainter(pixmap)
        painter.fillRect(0, 0, 16, 16, color)
        lighter = color.lighter()
        painter.setPen(lighter)
        # light frame
        painter.drawPolyline(QPoint(0, 15), QPoint(0, 0), QPoint(15, 0))
        painter.setPen(color.darker())
        # dark frame
        painter.drawPolyline(QPoint(1, 15), QPoint(15, 15), QPoint(15, 1))
        painter.end()
        self.colorAction.setIcon(QIcon(pixmap))

    def updateLineEdit(self, item):
        if item != self.table.currentItem():
            return
        if item:
            self.formulaInput.setText(item.data(Qt.EditRole))
        else:
            self.formulaInput.clear()

    def returnPressed(self):
        text = self.formulaInput.text()
        row = self.table.currentRow()
        col = self.table.currentColumn()
        item = self.table.item(row, col)
        if not item:
            self.table.setItem(row, col, SpreadSheetItem(text))
        else:
            item.setData(Qt.EditRole, text)
        self.table.viewport().update()

    def selectColor(self):
        item = self.table.currentItem()
        color = (item and QColor(item.background())
                 or self.table.palette().base().color())
        color = QColorDialog.getColor(color, self)
        if not color.isValid():
            return
        selected = self.table.selectedItems()
        if not selected:
            return
        for i in selected:
            i and i.setBackground(color)
        self.updateColor(self.table.currentItem())

    def selectFont(self):
        selected = self.table.selectedItems()
        if not selected:
            return
        font, ok = QFontDialog.getFont(self.font(), self)
        if not ok:
            return
        for i in selected:
            i and i.setFont(font)

    def runInputDialog(self, title, c1Text, c2Text, opText, outText, cell1,
                       cell2, outCell):
        rows = []
        cols = []
        for r in range(self.table.rowCount()):
            rows.append(str(r + 1))
        for c in range(self.table.columnCount()):
            cols.append(chr(ord("A") + c))
        addDialog = QDialog(self)
        addDialog.setWindowTitle(title)
        group = QGroupBox(title, addDialog)
        group.setMinimumSize(250, 100)
        cell1Label = QLabel(c1Text, group)
        cell1RowInput = QComboBox(group)
        c1Row, c1Col = decode_pos(cell1)
        cell1RowInput.addItems(rows)
        cell1RowInput.setCurrentIndex(c1Row)
        cell1ColInput = QComboBox(group)
        cell1ColInput.addItems(cols)
        cell1ColInput.setCurrentIndex(c1Col)
        operatorLabel = QLabel(opText, group)
        operatorLabel.setAlignment(Qt.AlignHCenter)
        cell2Label = QLabel(c2Text, group)
        cell2RowInput = QComboBox(group)
        c2Row, c2Col = decode_pos(cell2)
        cell2RowInput.addItems(rows)
        cell2RowInput.setCurrentIndex(c2Row)
        cell2ColInput = QComboBox(group)
        cell2ColInput.addItems(cols)
        cell2ColInput.setCurrentIndex(c2Col)
        equalsLabel = QLabel("=", group)
        equalsLabel.setAlignment(Qt.AlignHCenter)
        outLabel = QLabel(outText, group)
        outRowInput = QComboBox(group)
        outRow, outCol = decode_pos(outCell)
        outRowInput.addItems(rows)
        outRowInput.setCurrentIndex(outRow)
        outColInput = QComboBox(group)
        outColInput.addItems(cols)
        outColInput.setCurrentIndex(outCol)

        cancelButton = QPushButton("Cancel", addDialog)
        cancelButton.clicked.connect(addDialog.reject)
        okButton = QPushButton("OK", addDialog)
        okButton.setDefault(True)
        okButton.clicked.connect(addDialog.accept)
        buttonsLayout = QHBoxLayout()
        buttonsLayout.addStretch(1)
        buttonsLayout.addWidget(okButton)
        buttonsLayout.addSpacing(10)
        buttonsLayout.addWidget(cancelButton)

        dialogLayout = QVBoxLayout(addDialog)
        dialogLayout.addWidget(group)
        dialogLayout.addStretch(1)
        dialogLayout.addItem(buttonsLayout)

        cell1Layout = QHBoxLayout()
        cell1Layout.addWidget(cell1Label)
        cell1Layout.addSpacing(10)
        cell1Layout.addWidget(cell1ColInput)
        cell1Layout.addSpacing(10)
        cell1Layout.addWidget(cell1RowInput)

        cell2Layout = QHBoxLayout()
        cell2Layout.addWidget(cell2Label)
        cell2Layout.addSpacing(10)
        cell2Layout.addWidget(cell2ColInput)
        cell2Layout.addSpacing(10)
        cell2Layout.addWidget(cell2RowInput)
        outLayout = QHBoxLayout()
        outLayout.addWidget(outLabel)
        outLayout.addSpacing(10)
        outLayout.addWidget(outColInput)
        outLayout.addSpacing(10)
        outLayout.addWidget(outRowInput)
        vLayout = QVBoxLayout(group)
        vLayout.addItem(cell1Layout)
        vLayout.addWidget(operatorLabel)
        vLayout.addItem(cell2Layout)
        vLayout.addWidget(equalsLabel)
        vLayout.addStretch(1)
        vLayout.addItem(outLayout)
        if addDialog.exec_():
            cell1 = cell1ColInput.currentText() + cell1RowInput.currentText()
            cell2 = cell2ColInput.currentText() + cell2RowInput.currentText()
            outCell = outColInput.currentText() + outRowInput.currentText()
            return True, cell1, cell2, outCell

        return False, None, None, None

    def actionSum(self):
        row_first = 0
        row_last = 0
        row_cur = 0
        col_first = 0
        col_last = 0
        col_cur = 0
        selected = self.table.selectedItems()
        if selected:
            first = selected[0]
            last = selected[-1]
            row_first = self.table.row(first)
            row_last = self.table.row(last)
            col_first = self.table.column(first)
            col_last = self.table.column(last)

        current = self.table.currentItem()
        if current:
            row_cur = self.table.row(current)
            col_cur = self.table.column(current)

        cell1 = encode_pos(row_first, col_first)
        cell2 = encode_pos(row_last, col_last)
        out = encode_pos(row_cur, col_cur)
        ok, cell1, cell2, out = self.runInputDialog(
            "Sum cells",
            "First cell:",
            "Last cell:",
            u"\N{GREEK CAPITAL LETTER SIGMA}",
            "Output to:",
            cell1,
            cell2,
            out,
        )
        if ok:
            row, col = decode_pos(out)
            self.table.item(row, col).setText("sum %s %s" % (cell1, cell2))

    def actionMath_helper(self, title, op):
        cell1 = "C1"
        cell2 = "C2"
        out = "C3"
        current = self.table.currentItem()
        if current:
            out = encode_pos(self.table.currentRow(),
                             self.table.currentColumn())
        ok, cell1, cell2, out = self.runInputDialog(title, "Cell 1", "Cell 2",
                                                    op, "Output to:", cell1,
                                                    cell2, out)
        if ok:
            row, col = decode_pos(out)
            self.table.item(row, col).setText("%s %s %s" % (op, cell1, cell2))

    def actionAdd(self):
        self.actionMath_helper("Addition", "+")

    def actionSubtract(self):
        self.actionMath_helper("Subtraction", "-")

    def actionMultiply(self):
        self.actionMath_helper("Multiplication", "*")

    def actionDivide(self):
        self.actionMath_helper("Division", "/")

    def clear(self):
        for i in self.table.selectedItems():
            i.setText("")

    def setupContextMenu(self):
        self.addAction(self.cell_addAction)
        self.addAction(self.cell_subAction)
        self.addAction(self.cell_mulAction)
        self.addAction(self.cell_divAction)
        self.addAction(self.cell_sumAction)
        self.addAction(self.firstSeparator)
        self.addAction(self.colorAction)
        self.addAction(self.fontAction)
        self.addAction(self.secondSeparator)
        self.addAction(self.clearAction)
        self.setContextMenuPolicy(Qt.ActionsContextMenu)

    def setupContents(self):
        titleBackground = QColor(Qt.lightGray)
        titleFont = self.table.font()
        titleFont.setBold(True)
        # column 0
        self.table.setItem(0, 0, SpreadSheetItem("Item"))
        self.table.item(0, 0).setBackground(titleBackground)
        self.table.item(
            0, 0).setToolTip("This column shows the purchased item/service")
        self.table.item(0, 0).setFont(titleFont)
        self.table.setItem(1, 0, SpreadSheetItem("AirportBus"))
        self.table.setItem(2, 0, SpreadSheetItem("Flight (Munich)"))
        self.table.setItem(3, 0, SpreadSheetItem("Lunch"))
        self.table.setItem(4, 0, SpreadSheetItem("Flight (LA)"))
        self.table.setItem(5, 0, SpreadSheetItem("Taxi"))
        self.table.setItem(6, 0, SpreadSheetItem("Dinner"))
        self.table.setItem(7, 0, SpreadSheetItem("Hotel"))
        self.table.setItem(8, 0, SpreadSheetItem("Flight (Oslo)"))
        self.table.setItem(9, 0, SpreadSheetItem("Total:"))
        self.table.item(9, 0).setFont(titleFont)
        self.table.item(9, 0).setBackground(Qt.lightGray)
        # column 1
        self.table.setItem(0, 1, SpreadSheetItem("Date"))
        self.table.item(0, 1).setBackground(titleBackground)
        self.table.item(0, 1).setToolTip(
            "This column shows the purchase date, double click to change")
        self.table.item(0, 1).setFont(titleFont)
        self.table.setItem(1, 1, SpreadSheetItem("15/6/2006"))
        self.table.setItem(2, 1, SpreadSheetItem("15/6/2006"))
        self.table.setItem(3, 1, SpreadSheetItem("15/6/2006"))
        self.table.setItem(4, 1, SpreadSheetItem("21/5/2006"))
        self.table.setItem(5, 1, SpreadSheetItem("16/6/2006"))
        self.table.setItem(6, 1, SpreadSheetItem("16/6/2006"))
        self.table.setItem(7, 1, SpreadSheetItem("16/6/2006"))
        self.table.setItem(8, 1, SpreadSheetItem("18/6/2006"))
        self.table.setItem(9, 1, SpreadSheetItem())
        self.table.item(9, 1).setBackground(Qt.lightGray)
        # column 2
        self.table.setItem(0, 2, SpreadSheetItem("Price"))
        self.table.item(0, 2).setBackground(titleBackground)
        self.table.item(
            0, 2).setToolTip("This column shows the price of the purchase")
        self.table.item(0, 2).setFont(titleFont)
        self.table.setItem(1, 2, SpreadSheetItem("150"))
        self.table.setItem(2, 2, SpreadSheetItem("2350"))
        self.table.setItem(3, 2, SpreadSheetItem("-14"))
        self.table.setItem(4, 2, SpreadSheetItem("980"))
        self.table.setItem(5, 2, SpreadSheetItem("5"))
        self.table.setItem(6, 2, SpreadSheetItem("120"))
        self.table.setItem(7, 2, SpreadSheetItem("300"))
        self.table.setItem(8, 2, SpreadSheetItem("1240"))
        self.table.setItem(9, 2, SpreadSheetItem())
        self.table.item(9, 2).setBackground(Qt.lightGray)
        # column 3
        self.table.setItem(0, 3, SpreadSheetItem("Currency"))
        self.table.item(0, 3).setBackgroundColor(titleBackground)
        self.table.item(0, 3).setToolTip("This column shows the currency")
        self.table.item(0, 3).setFont(titleFont)
        self.table.setItem(1, 3, SpreadSheetItem("NOK"))
        self.table.setItem(2, 3, SpreadSheetItem("NOK"))
        self.table.setItem(3, 3, SpreadSheetItem("EUR"))
        self.table.setItem(4, 3, SpreadSheetItem("EUR"))
        self.table.setItem(5, 3, SpreadSheetItem("USD"))
        self.table.setItem(6, 3, SpreadSheetItem("USD"))
        self.table.setItem(7, 3, SpreadSheetItem("USD"))
        self.table.setItem(8, 3, SpreadSheetItem("USD"))
        self.table.setItem(9, 3, SpreadSheetItem())
        self.table.item(9, 3).setBackground(Qt.lightGray)
        # column 4
        self.table.setItem(0, 4, SpreadSheetItem("Ex. Rate"))
        self.table.item(0, 4).setBackground(titleBackground)
        self.table.item(
            0, 4).setToolTip("This column shows the exchange rate to NOK")
        self.table.item(0, 4).setFont(titleFont)
        self.table.setItem(1, 4, SpreadSheetItem("1"))
        self.table.setItem(2, 4, SpreadSheetItem("1"))
        self.table.setItem(3, 4, SpreadSheetItem("8"))
        self.table.setItem(4, 4, SpreadSheetItem("8"))
        self.table.setItem(5, 4, SpreadSheetItem("7"))
        self.table.setItem(6, 4, SpreadSheetItem("7"))
        self.table.setItem(7, 4, SpreadSheetItem("7"))
        self.table.setItem(8, 4, SpreadSheetItem("7"))
        self.table.setItem(9, 4, SpreadSheetItem())
        self.table.item(9, 4).setBackground(Qt.lightGray)
        # column 5
        self.table.setItem(0, 5, SpreadSheetItem("NOK"))
        self.table.item(0, 5).setBackground(titleBackground)
        self.table.item(0,
                        5).setToolTip("This column shows the expenses in NOK")
        self.table.item(0, 5).setFont(titleFont)
        self.table.setItem(1, 5, SpreadSheetItem("* C2 E2"))
        self.table.setItem(2, 5, SpreadSheetItem("* C3 E3"))
        self.table.setItem(3, 5, SpreadSheetItem("* C4 E4"))
        self.table.setItem(4, 5, SpreadSheetItem("* C5 E5"))
        self.table.setItem(5, 5, SpreadSheetItem("* C6 E6"))
        self.table.setItem(6, 5, SpreadSheetItem("* C7 E7"))
        self.table.setItem(7, 5, SpreadSheetItem("* C8 E8"))
        self.table.setItem(8, 5, SpreadSheetItem("* C9 E9"))
        self.table.setItem(9, 5, SpreadSheetItem("sum F2 F9"))
        self.table.item(9, 5).setBackground(Qt.lightGray)

    def showAbout(self):
        QMessageBox.about(
            self,
            "About Spreadsheet",
            """
            <HTML>
            <p><b>This demo shows use of <c>QTableWidget</c> with custom handling for
             individual cells.</b></p>
            <p>Using a customized table item we make it possible to have dynamic
             output in different cells. The content that is implemented for this
             particular demo is:
            <ul>
            <li>Adding two cells.</li>
            <li>Subtracting one cell from another.</li>
            <li>Multiplying two cells.</li>
            <li>Dividing one cell with another.</li>
            <li>Summing the contents of an arbitrary number of cells.</li>
            </HTML>
        """,
        )

    def print_(self):
        printer = QPrinter(QPrinter.ScreenResolution)
        dlg = QPrintPreviewDialog(printer)
        view = PrintView()
        view.setModel(self.table.model())
        dlg.paintRequested.connect(view.print_)
        dlg.exec_()
コード例 #46
0
ファイル: clases.py プロジェクト: elramirezv123/CodeReader
class Buylayout(QGroupBox):
    def __init__(self, parent):
        super().__init__(parent)
        self.setGeometry(0,0, SCREEN_WIDTH, SCREEN_HEIGHT)

        self.label = QLabel("Escanea tu Producto", self)
        self.label.setGeometry(270, 200, 300, 70)
        self.label.setFont(QFont("Times",18))

        self.cart_label = QLabel("Tu Carro", self)
        self.cart_label.setGeometry(20, 515, 150, 40)
        self.cart_label.setFont(QFont("Times", 15))

        self.cart_background = QGroupBox(self)
        self.cart_background.setGeometry(0, 500, 768, 866)
        self.cart_background.setStyleSheet('background-color: rgb(100,255,100)')
        self.cart_background.lower()

        self.cart_layout = QGroupBox(self)
        self.cart_layout.setGeometry(20, 560, 728, 786)
        self.cart_layout.setStyleSheet('background-color: white')


        self.layout = QGroupBox(self)
        self.layout.setGeometry(0,0, 768,500)
        self.layout.lower()

        self.code = QLineEdit(self)
        self.code.setGeometry(0,0,0,0)
        self.code.setFocus()

        self.cart = {}
        self.total = 0

        self.label_total = QLabel("   Total: $0", self)
        self.label_total.setGeometry(20, 1250, 328, 90)
        self.label_total.setFont(QFont("Times", 20))
        self.label_total.setStyleSheet('background-color: rgb(255, 255, 255)')

        self.boton_cancelar = QPushButton("Cancelar", self)
        self.boton_cancelar.setGeometry(300, 1250, 200, 90)
        self.boton_cancelar.setFont(QFont("Times", 18))
        self.boton_cancelar.clicked.connect(self.cancelar)

        self.boton_imprimir = QPushButton("Imprimir", self)
        self.boton_imprimir.setGeometry(500, 1250, 200, 90)
        self.boton_imprimir.setFont(QFont("Times", 18))

        self.icono = QLabel(self)
        self.icono.setPixmap(QPixmap('logo.svg').scaled(300, 100))
        self.icono.move(234, 50)

        self.imageShower = QLabel(self)
        self.imageShower.setGeometry(500, 250, 200, 200)

    def cancelar(self):
        self.label.show()
        self.layout.hide()
        self.cart = {}
        self.cart_layout.hide()
        self.total = 0

        self.cart_layout = QGroupBox(self)
        self.cart_layout.setGeometry(20, 560, 728, 786)
        self.cart_layout.lower()
        self.cart_background.lower()
        self.cart_layout.setStyleSheet('background-color: rgb(255, 255, 255)')
        self.cart_layout.show()

        self.label_total.setText("   Total: ${}".format(str(self.total)))
        self.code.setFocus()

        self.imageShower.show()

    def keyPressEvent(self, event):
        self.searchCode()

    def mousePressEvent(self, event):
        self.code.setFocus()

    def searchCode(self):
        self.label.hide()
        self.layout.hide()

        self.layout = QGroupBox(self)
        self.layout.setGeometry(0,0, 768, 500)
        self.layout.lower()
        contador = 0
        for i in self.parent().database:
            if i['Codigo'] == self.code.text():
                if int(i['Cantidad'] )> 0:
                    label = QLabel('Nombre: ' + i['Nombre'], self.layout)
                    label.setGeometry(20, 250, 450, 50)
                    label.setFont(QFont("Times", 16))
                    label = QLabel('Marca: ' + i['Marca'], self.layout)
                    label.setGeometry(20, 340, 450, 50)
                    label.setFont(QFont("Times", 16))
                    label = QLabel('Precio: $' + i['Precio'], self.layout)
                    label.setGeometry(20, 430, 450, 50)
                    label.setFont(QFont("Times", 16))

                    self.imageShower.setPixmap(QPixmap(i['Imagen']).scaled(200, 200))
                    self.imageShower.show()
                    self.layout.show()
                    self.total += int(i['Precio'])
                    self.label_total.setText("   Total: ${}".format(str(self.total)))

                    if i['Nombre'] in list(self.cart.keys()):
                        self.cart[i['Nombre']][0] += 1
                        self.cart[i['Nombre']][1].setText(str(self.cart[i['Nombre']][0]))
                    else:
                        label = QLabel(i['Nombre'], self.cart_layout)
                        label.setGeometry(30, len(self.cart) * 40, 250, 30)
                        label.show()
                        label.setFont(QFont("Times",13))

                        label = QLabel('1', self.cart_layout)
                        label.setGeometry(300, len(self.cart) * 40, 100, 30)
                        label.show()
                        label.setFont(QFont("Times",13))
                        self.cart[i['Nombre']] = [1, label]
                    self.parent().database[contador]['Cantidad'] = str(int(self.parent().database[contador]['Cantidad']) - 1)
                    with open('db.json','w') as file:
                        json.dump(self.parent().database, file)
                else:
                    self.label.setText('''Lo sentimos, ese
producto no está disponible''')
                    self.label.show()
                break

            contador += 1

        self.code.setText('')
コード例 #47
0
class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.initUI()
        self.setWindowTitle("Graphing Application")

    def initUI(self):
        centralwidget = QWidget()

        # create submenu option for later reference
        fileDiaglogue = QAction('&Open .mat file', self)

        # create instance of menu bar
        mainMenu = self.menuBar()
        # create menu option for opening file
        fileMenu = mainMenu.addMenu('&File')
        # add submenu option to tool bar
        fileMenu.addAction(fileDiaglogue)
        # connect openFile method to submenu selection
        fileDiaglogue.triggered.connect(self.openFile)

        # create dropdown menu gui
        self.dropLabel = QLabel('Channel Set', self)
        self.comboBox = QComboBox(self)
        self.comboBox.currentIndexChanged.connect(self.checkSet)
        self.comboBox.currentIndexChanged.connect(self.updateBtns)

        # create y-gap textbox
        self.yLabel = QLabel('Y Axis Gap', self)
        self.textbox = QLineEdit(self)

        # create graph all checkbox

        self.graphAll = QPushButton('Select All Channels', self)
        self.graphAll.clicked.connect(self.selectAll)

        # create update button
        update_btn = QPushButton('Update', self)
        update_btn.clicked.connect(self.update)

        # instantiate main plot canvas
        plot_canvas = FigureCanvas(Figure(figsize=(5, 5)))

        # add toolbar to layout
        self.addToolBar(QtCore.Qt.BottomToolBarArea,
                        NavigationToolbar(plot_canvas, self))

        self._static_ax = plot_canvas.figure.subplots()
        # label graph axes
        xtext = self._static_ax.set_xlabel(
            'my xdata')  # returns a Text instance
        ytext = self._static_ax.set_ylabel('my ydata')

        # create grid for button layout
        self.grid = QGridLayout()
        # ensures no stretching occurs when maximizing/minimizing windows
        # self.grid.setSpacing(1)

        # assign grid position to each widget
        self.grid.addWidget(update_btn, 4, 0, 1, 5)
        self.grid.addWidget(self.yLabel, 1, 1)
        self.grid.addWidget(self.textbox, 1, 2)
        self.grid.addWidget(self.comboBox, 2, 2)
        self.grid.addWidget(self.dropLabel, 2, 1)
        self.grid.addWidget(self.graphAll, 3, 0, 1, 5)
        # create grid for channel button layout
        self.gridButtons = QGridLayout()
        self.gridButtons.setAlignment(Qt.AlignTop)

        # create layout for the graph canvas
        canvasBox = QHBoxLayout()
        canvasBox.addWidget(plot_canvas)

        # create main layout
        mainBox = QVBoxLayout()
        mainBox.addLayout(self.grid, 25)
        mainBox.addLayout(self.gridButtons, 75)
        mainBox.setAlignment(Qt.AlignHCenter)

        # create top layout
        topBox = QHBoxLayout()
        topBox.addLayout(canvasBox, 75)
        topBox.addLayout(mainBox, 25)

        centralwidget.setLayout(topBox)

        self.setCentralWidget(centralwidget)

        self.selected_SET = 0

    # method creates an instance of the File object and fills the dropdown menu with associated channel sets
    def openFile(self):
        self.file1 = File()
        # clear any pre-existing channel sets
        self.comboBox.clear()
        # check that a file has been chosen by the user
        if self.file1.file_path != "":
            # iterate through all sets and fill the dropdown with the name of each channel set
            for s in range(3, len(self.file1.ecog_SETS)):
                self.comboBox.addItem(self.file1.ecog_SETS[s])

    # method checks what channel set is currently selected and gets its index

    def checkSet(self):
        # iterate through all channel sets until it matches the currently selected channel set
        for s in range(3, len(self.file1.ecog_SETS)):
            if self.comboBox.currentText() == self.file1.ecog_SETS[s]:
                self.selected_SET = s

    # method creates buttons based on the number channels in the selected set
    def updateBtns(self):
        # deletes any checkboxes from any previous set selection
        for i in reversed(range(self.gridButtons.count())):
            self.gridButtons.itemAt(i).widget().setParent(None)
        # determine the number of channels based on the number of y values in the selected set
        self.num_channels = len(
            self.file1.mat_contents.get(
                self.file1.ecog_SETS[self.selected_SET])[0, :])
        # create a array of checkboxes for later reference
        self.box_array = list()
        self.list_array = list()
        # determine the maximum number of rows based on the numbe
        # r of channels
        max_rows = np.ceil(self.num_channels / 10)
        numB = 0
        # for each row, determine if the row will be complete
        for i in range(1, max_rows.astype(int) + 1):
            if self.num_channels - i * 10 > 0:
                columns = 10
            else:
                columns = self.num_channels % 10

            # create a label for each row indicating the number of each button
            self.list_array.append(QLabel())
            self.list_array[i - 1].setText(
                str((i - 1) * 10) + '-' + str(((i - 1) * 10) + columns))
            self.gridButtons.addWidget(self.list_array[i - 1], i + 2, 1)

            for j in range(1, columns + 1):
                self.box_array.append(QCheckBox(self))
                self.gridButtons.addWidget(self.box_array[numB], i + 2, j + 1)
                numB += 1
        self.channels_array = list()
        for i in range(0, self.num_channels):
            self.channels_array.append(
                channel(i, self.selected_SET, self.file1))

    def selectAll(self):
        # if user checks the "graph all" checkbox, append all channels to be graphed
        for b in range(0, len(self.box_array)):
            self.box_array[b].setCheckState(Qt.Checked)

    def checkBtns(self):
        # reinstantiate selected channels
        self.channels_selected = []
        # check which buttons and selected and add the respective channel to an array
        for b in range(0, len(self.box_array)):
            if self.box_array[b].checkState() == Qt.Checked:
                self.channels_selected.append(b)

    def updatePlot(self):
        # clear the axes before graphing selected channels
        self._static_ax.clear()
        # intantiate y_gap value for later use using the current textbox value
        y_gap = self.textbox.text()

        # check that user has entered a y gap value
        if y_gap == "":
            QMessageBox.about(self, "Error", "Please enter a y-gap value.")
        else:

            for j in range(0, len(self.channels_selected)):
                self.channels_array[self.channels_selected[j]].gap(
                    float(y_gap) * j)
                self._static_ax.plot(
                    self.channels_array[self.channels_selected[j]].x,
                    self.channels_array[self.channels_selected[j]].y)

        self._static_ax.figure.canvas.draw()

    def update(self):
        # check if an instance of the File() object has been created
        try:
            self.test = self.file1
        # if no File() object exists instruct the user to select a file
        except:
            QMessageBox.about(self, "Error", "Please load a .mat file.")
        # call checkBtn() and updatePlot() method if file exists.
        else:
            self.checkBtns()
            self.updatePlot()
コード例 #48
0
        def __init__(self):
            super(Widget,self).__init__()
            
            self.setWindowTitle("Uren invoeren externe werken -lonen")
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))
            self.setWindowFlags(self.windowFlags()| Qt.WindowSystemMenuHint |
                                Qt.WindowMinMaxButtonsHint)
            
            #self.setStyleSheet("background-color: #D9E1DF")
            self.setFont(QFont('Arial', 10))
               
            self.zkaccEdit = QLineEdit(str(maccountnr))
            self.zkaccEdit.setFixedWidth(150)
            self.zkaccEdit.setFont(QFont("Arial",10))
            reg_ex = QRegExp("^[1]{1}[0-9]{8}$")
            input_validator = QRegExpValidator(reg_ex, self.zkaccEdit)
            self.zkaccEdit.setValidator(input_validator)
            
            self.zkwerknEdit = QLineEdit(str(mwerknr))
            self.zkwerknEdit.setFixedWidth(150)
            self.zkwerknEdit.setFont(QFont("Arial",10))
            reg_ex = QRegExp("^[8]{1}[0-9]{8}$")
            input_validator = QRegExpValidator(reg_ex, self.zkwerknEdit)
            self.zkwerknEdit.setValidator(input_validator)
     
            self.k0Edit = QComboBox()
            self.k0Edit.setFixedWidth(150)
            self.k0Edit.setFont(QFont("Arial",10))
            self.k0Edit.addItem('100%')
            self.k0Edit.addItem('125%')
            self.k0Edit.addItem('150%')
            self.k0Edit.addItem('200%')
            self.k0Edit.addItem('Reis')
            self.k0Edit.addItem('Verlof')
            self.k0Edit.addItem('Extra verlof')
            self.k0Edit.addItem('Ziekte')
            self.k0Edit.addItem('Feestdag')
            self.k0Edit.addItem('Dokter')
            self.k0Edit.addItem('Geoorl. verzuim')
            self.k0Edit.addItem('Ong. verzuim')
  
            self.cBox = QCheckBox('Meerwerk')
            self.cBox.setFont(QFont("Arial",10))
                                                                     
            self.urenEdit = QLineEdit('0')
            self.urenEdit.setFixedWidth(150)
            self.urenEdit.setFont(QFont("Arial",10))
            reg_ex = QRegExp("^[-+]?[0-9]*\.?[0-9]+$")
            input_validator = QRegExpValidator(reg_ex, self.urenEdit)
            self.urenEdit.setValidator(input_validator)
            
            self.urentotEdit = QLineEdit('0')
            self.urentotEdit.setFixedWidth(150)
            self.urentotEdit.setDisabled(True)
            self.urentotEdit.setFont(QFont("Arial",10))
            self.urentotEdit.setStyleSheet("color: black")
                                                          
            self.boekdatumEdit = QLineEdit(mboekd)
            self.boekdatumEdit.setFixedWidth(150)
            self.boekdatumEdit.setFont(QFont("Arial",10))
            reg_ex = QRegExp("^[2]{1}[0-1]{1}[0-9]{2}[-]{1}[0-1]{1}[0-9]{1}[-]{1}[0-3]{1}[0-9]{1}$")
            input_validator = QRegExpValidator(reg_ex, self.boekdatumEdit)
            self.boekdatumEdit.setValidator(input_validator)
                                            
            def accChanged():
                self.zkaccEdit.setText(self.zkaccEdit.text())
            self.zkaccEdit.textChanged.connect(accChanged)
             
            def werknChanged():
                self.zkwerknEdit.setText(self.zkwerknEdit.text())
            self.zkwerknEdit.textChanged.connect(werknChanged)
             
            '''
            def k0Changed():
                self.k0Edit.setCurrentText(self.k0Edit.currentText())
            self.k0Edit.currentTextChanged.connect(k0Changed)
            '''
            
            def k0Changed():
                self.k0Edit.setCurrentIndex(self.k0Edit.currentIndex())
            self.k0Edit.currentIndexChanged.connect(k0Changed)
                        
            def  cboxChanged():
                 self.cBox.setCheckState(self.cBox.checkState())
            self.cBox.stateChanged.connect(cboxChanged)
            
            def urenChanged():
                self.urenEdit.setText(self.urenEdit.text())
            self.urenEdit.textChanged.connect(urenChanged)
            
            def boekdatumChanged():
                self.boekdatumEdit.setText(self.boekdatumEdit.text())
            self.boekdatumEdit.textChanged.connect(boekdatumChanged)
            
            grid = QGridLayout()
            grid.setSpacing(10)
            
            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl ,0 , 1)
            
            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo , 0, 3, 1, 1, Qt.AlignRight)       

            self.lblt = QLabel('Muteren uren (werken - lonen) niet cumulatief')
            self.lblt.setFont(QFont("Arial", 10))
            grid.addWidget(self.lblt , 12, 1, 1, 4, Qt.AlignCenter)
            
            lbl1 = QLabel('Accountnummer')
            lbl1.setFont(QFont("Arial", 10))
            grid.addWidget(lbl1, 6, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(self.zkaccEdit , 6, 2, 1, 1, Qt.AlignRight)
            
            lbl2 = QLabel('Werknummer')
            lbl2.setFont(QFont("Arial", 10))
            grid.addWidget(lbl2, 7, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(self.zkwerknEdit, 7, 2, 1, 1, Qt.AlignRight)
                
            lbl3 = QLabel('Soort Uren')
            lbl3.setFont(QFont("Arial", 10))
            grid.addWidget(lbl3, 8, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(self.k0Edit, 8, 2, 1, 1, Qt.AlignRight)
                        
            grid.addWidget(self.cBox, 8, 3)
            
            self.lblprof = QLabel('Totaaluren\n')
            grid.addWidget(self.lblprof, 9, 1, 1, 1, Qt.AlignRight | Qt.AlignTop)
            grid.addWidget(self.urentotEdit, 9, 2, 1, 1, Qt.AlignRight)
            
            lbl4 = QLabel('Urenmutatie')
            lbl4.setFont(QFont("Arial", 10))
            grid.addWidget(lbl4, 10, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(self.urenEdit, 10, 2, 1, 1, Qt.AlignRight)
                                       
            lbl5 = QLabel('Boekdatum')
            lbl5.setFont(QFont("Arial", 10))
            grid.addWidget(lbl5, 11, 1, 1, 1, Qt.AlignRight)
            grid.addWidget(self.boekdatumEdit, 11, 2, 1, 1, Qt.AlignRight)
            
            self.applyBtn = QPushButton('Muteren')
            self.applyBtn.clicked.connect(lambda: urenBoeking(self, merror, m_email))
               
            self.applyBtn.setFont(QFont("Arial",10))
            self.applyBtn.setFixedWidth(100)
            self.applyBtn.setStyleSheet("color: black;  background-color: gainsboro") 
                
            grid.addWidget(self.applyBtn,13, 3 , 1 , 1, Qt.AlignRight)
                
            cancelBtn = QPushButton('Sluiten')
            cancelBtn.clicked.connect(lambda: windowSluit(self, m_email)) 
    
            grid.addWidget(cancelBtn, 13, 2, 1 , 1, Qt.AlignRight)
            cancelBtn.setFont(QFont("Arial",10))
            cancelBtn.setFixedWidth(100)
            cancelBtn.setStyleSheet("color: black; background-color: gainsboro") 
                   
            infoBtn = QPushButton('Informatie')
            infoBtn.clicked.connect(lambda: info()) 
    
            grid.addWidget(infoBtn, 13, 1, 1, 1, Qt.AlignRight)
            infoBtn.setFont(QFont("Arial",10))
            infoBtn.setFixedWidth(100)
            infoBtn.setStyleSheet("color: black; background-color: gainsboro") 
            
            grid.addWidget(QLabel('\u00A9 2017 all rights reserved - [email protected]'), 14, 1, 1, 4, Qt.AlignCenter)
            
            self.setLayout(grid)
            self.setGeometry(600, 200, 150, 100)
コード例 #49
0
ファイル: password_dialog.py プロジェクト: proteanx/DeLight
class PasswordLayout(object):

    titles = [_("Enter Password"), _("Change Password"), _("Enter Passphrase")]

    def __init__(self, wallet, msg, kind, OK_button):
        self.wallet = wallet

        self.pw = QLineEdit()
        self.pw.setEchoMode(2)
        self.new_pw = QLineEdit()
        self.new_pw.setEchoMode(2)
        self.conf_pw = QLineEdit()
        self.conf_pw.setEchoMode(2)
        self.kind = kind
        self.OK_button = OK_button

        vbox = QVBoxLayout()
        label = QLabel(msg + "\n")
        label.setWordWrap(True)

        grid = QGridLayout()
        grid.setSpacing(8)
        grid.setColumnMinimumWidth(0, 150)
        grid.setColumnMinimumWidth(1, 100)
        grid.setColumnStretch(1,1)

        if kind == PW_PASSPHRASE:
            vbox.addWidget(label)
            msgs = [_('Passphrase:'), _('Confirm Passphrase:')]
        else:
            logo_grid = QGridLayout()
            logo_grid.setSpacing(8)
            logo_grid.setColumnMinimumWidth(0, 70)
            logo_grid.setColumnStretch(1,1)

            logo = QLabel()
            logo.setAlignment(Qt.AlignCenter)

            logo_grid.addWidget(logo,  0, 0)
            logo_grid.addWidget(label, 0, 1, 1, 2)
            vbox.addLayout(logo_grid)

            m1 = _('New Password:'******'Password:'******'Confirm Password:'******'Current Password:'******'Encrypt wallet file'))
        self.encrypt_cb.setEnabled(False)
        grid.addWidget(self.encrypt_cb, 4, 0, 1, 2)
        self.encrypt_cb.setVisible(kind != PW_PASSPHRASE)

        def enable_OK():
            ok = self.new_pw.text() == self.conf_pw.text()
            OK_button.setEnabled(ok)
            self.encrypt_cb.setEnabled(ok and bool(self.new_pw.text()))
        self.new_pw.textChanged.connect(enable_OK)
        self.conf_pw.textChanged.connect(enable_OK)

        self.vbox = vbox

    def title(self):
        return self.titles[self.kind]

    def layout(self):
        return self.vbox

    def pw_changed(self):
        password = self.new_pw.text()
        if password:
            colors = {"Weak":"Red", "Medium":"Blue", "Strong":"Green",
                      "Very Strong":"Green"}
            strength = check_password_strength(password)
            label = (_("Password Strength") + ": " + "<font color="
                     + colors[strength] + ">" + strength + "</font>")
        else:
            label = ""
        self.pw_strength.setText(label)

    def old_password(self):
        if self.kind == PW_CHANGE:
            return self.pw.text() or None
        return None

    def new_password(self):
        pw = self.new_pw.text()
        # Empty passphrases are fine and returned empty.
        if pw == "" and self.kind != PW_PASSPHRASE:
            pw = None
        return pw
コード例 #50
0
    def initUI(self):
        centralwidget = QWidget()

        # create submenu option for later reference
        fileDiaglogue = QAction('&Open .mat file', self)

        # create instance of menu bar
        mainMenu = self.menuBar()
        # create menu option for opening file
        fileMenu = mainMenu.addMenu('&File')
        # add submenu option to tool bar
        fileMenu.addAction(fileDiaglogue)
        # connect openFile method to submenu selection
        fileDiaglogue.triggered.connect(self.openFile)

        # create dropdown menu gui
        self.dropLabel = QLabel('Channel Set', self)
        self.comboBox = QComboBox(self)
        self.comboBox.currentIndexChanged.connect(self.checkSet)
        self.comboBox.currentIndexChanged.connect(self.updateBtns)

        # create y-gap textbox
        self.yLabel = QLabel('Y Axis Gap', self)
        self.textbox = QLineEdit(self)

        # create graph all checkbox

        self.graphAll = QPushButton('Select All Channels', self)
        self.graphAll.clicked.connect(self.selectAll)

        # create update button
        update_btn = QPushButton('Update', self)
        update_btn.clicked.connect(self.update)

        # instantiate main plot canvas
        plot_canvas = FigureCanvas(Figure(figsize=(5, 5)))

        # add toolbar to layout
        self.addToolBar(QtCore.Qt.BottomToolBarArea,
                        NavigationToolbar(plot_canvas, self))

        self._static_ax = plot_canvas.figure.subplots()
        # label graph axes
        xtext = self._static_ax.set_xlabel(
            'my xdata')  # returns a Text instance
        ytext = self._static_ax.set_ylabel('my ydata')

        # create grid for button layout
        self.grid = QGridLayout()
        # ensures no stretching occurs when maximizing/minimizing windows
        # self.grid.setSpacing(1)

        # assign grid position to each widget
        self.grid.addWidget(update_btn, 4, 0, 1, 5)
        self.grid.addWidget(self.yLabel, 1, 1)
        self.grid.addWidget(self.textbox, 1, 2)
        self.grid.addWidget(self.comboBox, 2, 2)
        self.grid.addWidget(self.dropLabel, 2, 1)
        self.grid.addWidget(self.graphAll, 3, 0, 1, 5)
        # create grid for channel button layout
        self.gridButtons = QGridLayout()
        self.gridButtons.setAlignment(Qt.AlignTop)

        # create layout for the graph canvas
        canvasBox = QHBoxLayout()
        canvasBox.addWidget(plot_canvas)

        # create main layout
        mainBox = QVBoxLayout()
        mainBox.addLayout(self.grid, 25)
        mainBox.addLayout(self.gridButtons, 75)
        mainBox.setAlignment(Qt.AlignHCenter)

        # create top layout
        topBox = QHBoxLayout()
        topBox.addLayout(canvasBox, 75)
        topBox.addLayout(mainBox, 25)

        centralwidget.setLayout(topBox)

        self.setCentralWidget(centralwidget)

        self.selected_SET = 0
コード例 #51
0
    def setupUi(self):

        ipport = QLabel("TCP/IP port", self)
        self.ipportEdit = QLineEdit(self.guvip, self)

        tcpport = QLabel("TCP port", self)
        self.tcpportEdit = QLineEdit(self.guvport, self)

        guvtype_lbl = QLabel("GUV type", self)
        self.guvtype_cb = QComboBox(self)
        mylist = ["GUV-541", "GUV-2511", "GUV-3511"]
        self.guvtype_cb.addItems(mylist)
        self.guvtype_cb.setCurrentIndex(mylist.index(self.guvtype_str))

        ##############################################

        self.runstopButton = QPushButton("START", self)
        self.clearButton = QPushButton("Clear", self)

        ##############################################

        schroll_lbl = QLabel("Schroll elapsed time ", self)
        self.combo0 = QComboBox(self)
        mylist0 = ["100", "200", "400", "600", "800", "1000", "1500", "2000"]
        self.combo0.addItems(mylist0)
        self.combo0.setCurrentIndex(mylist0.index(str(self.schroll_pts)))

        ##############################################

        self.cb_logdata = QCheckBox('Log data to file', self)
        self.cb_logdata.toggle()
        self.cb_logdata.setChecked(self.log_guv_check)
        #self.cb_logdata.setLayoutDirection(Qt.RightToLeft)
        self.file_edit = QLineEdit(self.log_guv_str, self)
        self.file_edit.setStyleSheet("color: blue")
        if self.cb_logdata.isChecked():
            self.file_edit.setEnabled(True)
        else:
            self.file_edit.setEnabled(False)

        self.lcd = QLCDNumber(self)
        self.lcd.setStyleSheet("color: red")
        self.lcd.setFixedWidth(170)
        self.lcd.setFixedHeight(35)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.setNumDigits(11)
        self.time_str = time.strftime("%y%m%d-%H%M")
        self.lcd.display(self.time_str)

        ##############################################

        g0_1 = QGridLayout()
        g0_1.addWidget(ipport, 0, 0)
        g0_1.addWidget(self.ipportEdit, 0, 1)
        g0_1.addWidget(tcpport, 0, 2)
        g0_1.addWidget(self.tcpportEdit, 0, 3)
        g0_1.addWidget(guvtype_lbl, 0, 4)
        g0_1.addWidget(self.guvtype_cb, 0, 5)

        g0_2 = QGridLayout()
        g0_2.addWidget(schroll_lbl, 0, 0)
        g0_2.addWidget(self.combo0, 0, 1)
        g0_2.addWidget(self.runstopButton, 0, 2)
        g0_2.addWidget(self.clearButton, 0, 3)
        g0_2.addWidget(self.cb_logdata, 1, 0)
        g0_2.addWidget(self.lcd, 1, 1)

        g0_4 = QVBoxLayout()
        g0_4.addLayout(g0_1)
        g0_4.addLayout(g0_2)
        g0_4.addWidget(self.file_edit)

        ##############################################

        # set graph  and toolbar to a new vertical group vcan
        self.pw1 = pg.PlotWidget()
        self.pw1.setFixedWidth(600)

        ##############################################

        # create table
        self.tableWidget = self.createTable()

        ##############################################

        # SET ALL VERTICAL COLUMNS TOGETHER
        vbox = QVBoxLayout()
        vbox.addLayout(g0_4)
        vbox.addWidget(self.pw1)

        hbox = QVBoxLayout()
        hbox.addLayout(vbox)
        hbox.addWidget(self.tableWidget)

        self.threadpool = QThreadPool()
        print("Multithreading in the GUV dialog with maximum %d threads" %
              self.threadpool.maxThreadCount())
        self.isRunning = False

        self.setLayout(hbox)
        self.setWindowTitle("Test GUV")

        # PLOT 2 settings
        # create plot and add it to the figure canvas
        self.p1 = self.pw1.plotItem
        self.curves = []
        colors = itertools.cycle(["r", "b", "g", "y", "m", "c", "w"])
        for i in range(20):
            mycol = next(colors)
            self.curves.append(
                self.p1.plot(pen=pg.mkPen(color=mycol),
                             symbol='s',
                             symbolPen=mycol,
                             symbolBrush=mycol,
                             symbolSize=4))
        # create plot and add it to the figure
        self.p0_1 = pg.ViewBox()
        self.curve2 = pg.PlotCurveItem(pen='r')
        self.p0_1.addItem(self.curve2)
        # connect respective axes to the plot
        #self.p1.showAxis('left')
        self.p1.getAxis('left').setLabel("Power density",
                                         units="",
                                         color='yellow')
        self.p1.showAxis('right')
        self.p1.getAxis('right').setLabel("Arb unit", units="", color='red')
        self.p1.scene().addItem(self.p0_1)
        self.p1.getAxis('right').linkToView(self.p0_1)
        self.p0_1.setXLink(self.p1)

        self.p1.getAxis('bottom').setLabel("Time passed",
                                           units="s",
                                           color='yellow')
        # Use automatic downsampling and clipping to reduce the drawing load
        self.pw1.setDownsampling(mode='peak')
        self.pw1.setClipToView(True)

        # Initialize and set titles and axis names for both plots
        self.clear_vars_graphs()
        self.combo0.activated[str].connect(self.onActivated0)
        self.guvtype_cb.activated[str].connect(self.onActivated1)
        self.cb_logdata.toggled.connect(self.logdata)

        # run or cancel the main script
        self.runstopButton.clicked.connect(self.runstop)
        self.clearButton.clicked.connect(self.set_clear)
        self.clearButton.setEnabled(False)
コード例 #52
0
ファイル: password_dialog.py プロジェクト: proteanx/DeLight
    def __init__(self, wallet, msg, kind, OK_button):
        self.wallet = wallet

        self.pw = QLineEdit()
        self.pw.setEchoMode(2)
        self.new_pw = QLineEdit()
        self.new_pw.setEchoMode(2)
        self.conf_pw = QLineEdit()
        self.conf_pw.setEchoMode(2)
        self.kind = kind
        self.OK_button = OK_button

        vbox = QVBoxLayout()
        label = QLabel(msg + "\n")
        label.setWordWrap(True)

        grid = QGridLayout()
        grid.setSpacing(8)
        grid.setColumnMinimumWidth(0, 150)
        grid.setColumnMinimumWidth(1, 100)
        grid.setColumnStretch(1,1)

        if kind == PW_PASSPHRASE:
            vbox.addWidget(label)
            msgs = [_('Passphrase:'), _('Confirm Passphrase:')]
        else:
            logo_grid = QGridLayout()
            logo_grid.setSpacing(8)
            logo_grid.setColumnMinimumWidth(0, 70)
            logo_grid.setColumnStretch(1,1)

            logo = QLabel()
            logo.setAlignment(Qt.AlignCenter)

            logo_grid.addWidget(logo,  0, 0)
            logo_grid.addWidget(label, 0, 1, 1, 2)
            vbox.addLayout(logo_grid)

            m1 = _('New Password:'******'Password:'******'Confirm Password:'******'Current Password:'******'Encrypt wallet file'))
        self.encrypt_cb.setEnabled(False)
        grid.addWidget(self.encrypt_cb, 4, 0, 1, 2)
        self.encrypt_cb.setVisible(kind != PW_PASSPHRASE)

        def enable_OK():
            ok = self.new_pw.text() == self.conf_pw.text()
            OK_button.setEnabled(ok)
            self.encrypt_cb.setEnabled(ok and bool(self.new_pw.text()))
        self.new_pw.textChanged.connect(enable_OK)
        self.conf_pw.textChanged.connect(enable_OK)

        self.vbox = vbox
コード例 #53
0
ファイル: email_tab.py プロジェクト: JoeEmp/AirMemo
class Email_Tab_Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.set_data()
        self.setupUi()

    def set_data(self):
        self.user_info = mine['user_info']
        self._email_records = get_user_email_conf(
            self.user_info['username'])['records']

    def setupUi(self):
        self.gridLayoutWidget = QWidget(self)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 500, 350))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")

        self.tips_lab = QLabel(self.gridLayoutWidget)
        self.tips_lab.setMaximumSize(QtCore.QSize(130, 15))
        self.tips_lab.setText('暂不支持stmp')
        self.tips_lab.setObjectName("tips_lab")
        self.gridLayout.addWidget(self.tips_lab, 0, 0, 1, 1)

        self.email_list = QListWidget(self.gridLayoutWidget)
        for record in self._email_records:
            item = QListWidgetItem(record['addr'])
            if record['is_default'] == 1:
                brush = QtGui.QBrush(QtGui.QColor(1, 203, 31))
                brush.setStyle(QtCore.Qt.NoBrush)
                item.setForeground(brush)
            item.data = record
            self.email_list.addItem(item)
        self.email_list.itemClicked.connect(self.set_email_config_form)
        self.gridLayout.addWidget(self.email_list, 1, 0, 4, 4)

        self.default_email_btn = QPushButton(self.gridLayoutWidget)
        self.default_email_btn.setText('设置默认')
        self.default_email_btn.clicked.connect(self._selectDefualt)
        self.gridLayout.addWidget(self.default_email_btn, 5, 0, 1, 1)

        self.del_email_btn = QPushButton(self.gridLayoutWidget)
        self.del_email_btn.setText('删除')
        self.del_email_btn.clicked.connect(self.del_email_config)
        self.gridLayout.addWidget(self.del_email_btn, 5, 3, 1, 1)

        self.add_email_btn = QPushButton(self.gridLayoutWidget)
        self.add_email_btn.setText('添加邮箱')
        self.add_email_btn.clicked.connect(self.set_email_config_form)
        self.gridLayout.addWidget(self.add_email_btn, 5, 1, 1, 1)

        self.email_lab = QLabel(self.gridLayoutWidget)
        self.email_lab.setText('邮箱地址')
        self.gridLayout.addWidget(self.email_lab, 1, 4, 1, 1)

        self.email_le = QLineEdit(self.gridLayoutWidget)
        self.gridLayout.addWidget(self.email_le, 1, 5, 1, 2)

        self.password_lab = QLabel(self.gridLayoutWidget)
        self.password_lab.setText('密码')
        self.gridLayout.addWidget(self.password_lab, 2, 4, 1, 1)

        self.password_le = QLineEdit(self.gridLayoutWidget)
        self.gridLayout.addWidget(self.password_le, 2, 5, 1, 2)
        self.password_le.setEchoMode(QLineEdit.Password)

        self.ssl_lab = QLabel(self.gridLayoutWidget)
        self.ssl_lab.setText('ssl端口')
        self.gridLayout.addWidget(self.ssl_lab, 3, 4, 1, 1)

        self.ssl_rbtn = QRadioButton(self.gridLayoutWidget)
        self.ssl_rbtn.setText("")
        self.ssl_rbtn.setObjectName("ssl_rbtn")
        self.ssl_rbtn.clicked.connect(self.chcek_radio_slot)
        self.gridLayout.addWidget(self.ssl_rbtn, 3, 5, 1, 1)

        self.ssl_port_le = QLineEdit(self.gridLayoutWidget)
        self.ssl_port_le.setObjectName("ssl_le")
        self.gridLayout.addWidget(self.ssl_port_le, 3, 6, 1, 1)

        self.sender_le = QLineEdit(self.gridLayoutWidget)
        self.sender_le.setObjectName("sender_le")
        self.gridLayout.addWidget(self.sender_le, 4, 5, 1, 2)

        self.sender_lab = QLabel(self.gridLayoutWidget)
        self.sender_lab.setText('发信名称')
        self.gridLayout.addWidget(self.sender_lab, 4, 4, 1, 1)

        self.save_email_btn = QPushButton(self.gridLayoutWidget)
        self.save_email_btn.setText('保存')
        self.save_email_btn.clicked.connect(self.save_email_config)
        self.gridLayout.addWidget(self.save_email_btn, 5, 6, 1, 1)

    def save_email_config(self):
        if not self.email_le.text():
            return Toast(self).show_toast('请输入邮箱地址', height=0.15)
        if not self.password_le.text():
            return Toast(self).show_toast('请输入邮箱第三方设置密码',
                                          time=1500,
                                          height=0.15)
        else:
            ssl_port = self.ssl_port_le.text()
            if not ssl_port:
                ssl_port = None
                user_ssl = 0
            else:
                user_ssl = 1
            sender_name = self.email_le.text() or self.sender_le.text()
            args = [
                self.user_info['username'],
                self.email_le.text(),
                self.password_le.text(), sender_name, ssl_port, user_ssl
            ]
            if -1 != self.email_list.currentIndex:
                add_email_conf(*args)
                self.set_email_config_form()
                Toast(self).show_toast("添加成功", height=0.1)
            else:
                update_email_conf(*args)
            self.refresh_widget()

    def _selectDefualt(self):
        if self.email_list.currentRow() != -1:
            id = self.email_list.currentItem().data['id']
            set_is_default_email_conf(id, self.user_info['username'])
            self.refresh_email_tab()
        else:
            Toast(self).show_toast('请选择优先使用的邮箱', height=0.15)

    def refresh_widget(self):
        self.email_list.clear()
        self.set_email_config_form()
        for record in get_user_email_conf(self.user_info['username']).get(
                'records', []):
            item = QListWidgetItem(record['addr'])
            if record['is_default'] == 1:
                brush = QtGui.QBrush(QtGui.QColor(1, 203, 31))
                brush.setStyle(QtCore.Qt.NoBrush)
                item.setForeground(brush)
            item.data = record
            self.email_list.addItem(item)

    def set_email_config_form(self, item=None):
        if item:
            data = item.data
        else:
            data = {
                "addr": '',
                "password": "",
                "sender_name": "",
                "ssl_port": '',
                "user_ssl": 0
            }
        self.email_le.setText(data['addr'])
        self.password_le.setText(data['password'])
        self.sender_le.setText(data['sender_name'])
        if data['ssl_port']:
            self.ssl_port_le.setText(str(data['ssl_port']))
        if data['user_ssl'] == 1:
            self.ssl_port_le.setEnabled(True)
            self.ssl_rbtn.setChecked(True)
        else:
            self.ssl_port_le.setEnabled(False)
            self.ssl_rbtn.setChecked(False)

    def del_email_config(self):
        index = self.email_list.currentRow()
        item = self.email_list.currentItem()
        if item:
            ret = QMessageBox.question(self, ' ', '是否删除本条配置', QMessageBox.Yes,
                                       QMessageBox.Cancel)
            try:
                if ret == QMessageBox.Yes:
                    del_email_conf(item.data['id'])
                    self.email_list.takeItem(index)
                    self.clear_email_form()
            except Exception as e:
                logging.error(e)
        else:
            Toast(self).show_toast('没有选择删除项')

    def chcek_radio_slot(self):
        if self.ssl_rbtn.isChecked():
            self.ssl_port_le.setEnabled(True)
        else:
            self.ssl_port_le.setEnabled(False)
            self.ssl_port_le.clear()
コード例 #54
0
class GUV_TEST_dialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)

        # Initial read of the config file
        self.config = configparser.ConfigParser()

        try:
            self.config.read('config.ini')
            self.last_used_scan = self.config.get('LastScan', 'last_used_scan')

            #self.log_guv=self.bool_(self.config.get(self.last_used_scan,'log_guv'))
            self.schroll_pts = int(
                self.config.get(self.last_used_scan, 'schroll'))
            self.log_guv_str = self.config.get(self.last_used_scan,
                                               'log_guv').strip().split(',')[0]
            self.log_guv_check = self.bool_(
                self.config.get(self.last_used_scan,
                                'log_guv').strip().split(',')[1])

            self.guvip = self.config.get("Instruments",
                                         'guvport').strip().split(',')[0]
            self.guvport = self.config.get("Instruments",
                                           'guvport').strip().split(',')[1]
            self.guvtype_str = self.config.get("Instruments", 'guvtype')
        except configparser.NoOptionError as e:
            QMessageBox.critical(
                self, 'Message', ''.join(
                    ["Main FAULT while reading the config.ini file\n",
                     str(e)]))
            raise

        self.setupUi()

    def bool_(self, txt):

        if txt == "True":
            return True
        elif txt == "False":
            return False

    def setupUi(self):

        ipport = QLabel("TCP/IP port", self)
        self.ipportEdit = QLineEdit(self.guvip, self)

        tcpport = QLabel("TCP port", self)
        self.tcpportEdit = QLineEdit(self.guvport, self)

        guvtype_lbl = QLabel("GUV type", self)
        self.guvtype_cb = QComboBox(self)
        mylist = ["GUV-541", "GUV-2511", "GUV-3511"]
        self.guvtype_cb.addItems(mylist)
        self.guvtype_cb.setCurrentIndex(mylist.index(self.guvtype_str))

        ##############################################

        self.runstopButton = QPushButton("START", self)
        self.clearButton = QPushButton("Clear", self)

        ##############################################

        schroll_lbl = QLabel("Schroll elapsed time ", self)
        self.combo0 = QComboBox(self)
        mylist0 = ["100", "200", "400", "600", "800", "1000", "1500", "2000"]
        self.combo0.addItems(mylist0)
        self.combo0.setCurrentIndex(mylist0.index(str(self.schroll_pts)))

        ##############################################

        self.cb_logdata = QCheckBox('Log data to file', self)
        self.cb_logdata.toggle()
        self.cb_logdata.setChecked(self.log_guv_check)
        #self.cb_logdata.setLayoutDirection(Qt.RightToLeft)
        self.file_edit = QLineEdit(self.log_guv_str, self)
        self.file_edit.setStyleSheet("color: blue")
        if self.cb_logdata.isChecked():
            self.file_edit.setEnabled(True)
        else:
            self.file_edit.setEnabled(False)

        self.lcd = QLCDNumber(self)
        self.lcd.setStyleSheet("color: red")
        self.lcd.setFixedWidth(170)
        self.lcd.setFixedHeight(35)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.setNumDigits(11)
        self.time_str = time.strftime("%y%m%d-%H%M")
        self.lcd.display(self.time_str)

        ##############################################

        g0_1 = QGridLayout()
        g0_1.addWidget(ipport, 0, 0)
        g0_1.addWidget(self.ipportEdit, 0, 1)
        g0_1.addWidget(tcpport, 0, 2)
        g0_1.addWidget(self.tcpportEdit, 0, 3)
        g0_1.addWidget(guvtype_lbl, 0, 4)
        g0_1.addWidget(self.guvtype_cb, 0, 5)

        g0_2 = QGridLayout()
        g0_2.addWidget(schroll_lbl, 0, 0)
        g0_2.addWidget(self.combo0, 0, 1)
        g0_2.addWidget(self.runstopButton, 0, 2)
        g0_2.addWidget(self.clearButton, 0, 3)
        g0_2.addWidget(self.cb_logdata, 1, 0)
        g0_2.addWidget(self.lcd, 1, 1)

        g0_4 = QVBoxLayout()
        g0_4.addLayout(g0_1)
        g0_4.addLayout(g0_2)
        g0_4.addWidget(self.file_edit)

        ##############################################

        # set graph  and toolbar to a new vertical group vcan
        self.pw1 = pg.PlotWidget()
        self.pw1.setFixedWidth(600)

        ##############################################

        # create table
        self.tableWidget = self.createTable()

        ##############################################

        # SET ALL VERTICAL COLUMNS TOGETHER
        vbox = QVBoxLayout()
        vbox.addLayout(g0_4)
        vbox.addWidget(self.pw1)

        hbox = QVBoxLayout()
        hbox.addLayout(vbox)
        hbox.addWidget(self.tableWidget)

        self.threadpool = QThreadPool()
        print("Multithreading in the GUV dialog with maximum %d threads" %
              self.threadpool.maxThreadCount())
        self.isRunning = False

        self.setLayout(hbox)
        self.setWindowTitle("Test GUV")

        # PLOT 2 settings
        # create plot and add it to the figure canvas
        self.p1 = self.pw1.plotItem
        self.curves = []
        colors = itertools.cycle(["r", "b", "g", "y", "m", "c", "w"])
        for i in range(20):
            mycol = next(colors)
            self.curves.append(
                self.p1.plot(pen=pg.mkPen(color=mycol),
                             symbol='s',
                             symbolPen=mycol,
                             symbolBrush=mycol,
                             symbolSize=4))
        # create plot and add it to the figure
        self.p0_1 = pg.ViewBox()
        self.curve2 = pg.PlotCurveItem(pen='r')
        self.p0_1.addItem(self.curve2)
        # connect respective axes to the plot
        #self.p1.showAxis('left')
        self.p1.getAxis('left').setLabel("Power density",
                                         units="",
                                         color='yellow')
        self.p1.showAxis('right')
        self.p1.getAxis('right').setLabel("Arb unit", units="", color='red')
        self.p1.scene().addItem(self.p0_1)
        self.p1.getAxis('right').linkToView(self.p0_1)
        self.p0_1.setXLink(self.p1)

        self.p1.getAxis('bottom').setLabel("Time passed",
                                           units="s",
                                           color='yellow')
        # Use automatic downsampling and clipping to reduce the drawing load
        self.pw1.setDownsampling(mode='peak')
        self.pw1.setClipToView(True)

        # Initialize and set titles and axis names for both plots
        self.clear_vars_graphs()
        self.combo0.activated[str].connect(self.onActivated0)
        self.guvtype_cb.activated[str].connect(self.onActivated1)
        self.cb_logdata.toggled.connect(self.logdata)

        # run or cancel the main script
        self.runstopButton.clicked.connect(self.runstop)
        self.clearButton.clicked.connect(self.set_clear)
        self.clearButton.setEnabled(False)

    def logdata(self):

        if self.cb_logdata.isChecked():
            self.time_str = time.strftime("%y%m%d-%H%M")

            head, tail = os.path.split(str(self.file_edit.text()))
            self.log_guv_str = ''.join(
                [head, '/log_', self.guvtype_str, '_', self.time_str])
            self.lcd.display(self.time_str)
            self.file_edit.setText(self.log_guv_str)
            self.file_edit.setEnabled(True)
        else:
            self.file_edit.setEnabled(False)

    def onActivated0(self, text):

        old_st = self.schroll_pts

        self.schroll_pts = int(str(text))

        if old_st > self.schroll_pts:
            self.set_clear()

    def onActivated1(self, text):

        old_guvtype = self.guvtype_str
        self.guvtype_str = str(text)

        if old_guvtype != self.guvtype_str:
            head, tail = os.path.split(str(self.file_edit.text()))
            self.log_guv_str = ''.join(
                [head, '/log_', self.guvtype_str, '_', self.time_str])
            self.file_edit.setText(self.log_guv_str)
            self.set_clear()
            '''
			self.config.set(self.last_used_scan, 'guvtype', self.guvtype_str) 
			with open('config.ini', 'w') as configfile:
				self.config.write(configfile)
			'''

    def createTable(self):

        tableWidget = QTableWidget()
        #tableWidget.setFixedWidth(175)

        # set row count
        #tableWidget.setRowCount(20)

        # set column count
        tableWidget.setColumnCount(2)

        # hide grid
        tableWidget.setShowGrid(False)

        # hide vertical header
        vh = tableWidget.verticalHeader()
        vh.setVisible(False)

        # set the font
        font = QFont("Courier New", 9)
        tableWidget.setFont(font)
        tableWidget.setStyleSheet("color: blue")

        # place content into individual table fields
        #tableWidget.setItem(0,0, QTableWidgetItem("abe"))

        tableWidget.setHorizontalHeaderLabels(
            ["Time[s]", "Channel power density"])
        #tableWidget.setVerticalHeaderLabels(["aa","bb","cc","dd"])

        # set horizontal header properties
        hh = tableWidget.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        tableWidget.resizeColumnsToContents()

        # enable sorting
        #tableWidget.setSortingEnabled(True)

        return tableWidget

    def set_cancel(self):

        self.worker.abort()
        self.clearButton.setEnabled(True)
        self.runstopButton.setText("START")

    def set_clear(self):

        self.clear_vars_graphs()
        self.clearButton.setEnabled(False)
        self.clearButton.setText("Cleared")

    def runstop(self):

        sender = self.sender()
        if sender.text() == "START":
            self.set_run()
        elif sender.text() == "STOP":
            self.set_cancel()

    def set_run(self):

        if self.cb_logdata.isChecked():
            # Check if folder exists and if not create it
            head, tail = os.path.split(str(self.file_edit.text()))
            if head:
                if head[0] == '/':
                    QMessageBox.critical(
                        self, 'Message',
                        'Path name should not start with a forward slash (/)')
                    return
            else:
                QMessageBox.critical(self, 'Message',
                                     'No path to folder(s) provided!')
                return

            try:
                os.makedirs(os.path.dirname(str(self.file_edit.text())),
                            exist_ok=True)
            except Exception as e:
                QMessageBox.critical(
                    self, 'Message',
                    ''.join(["Folder named ", head, " not valid!\n",
                             str(e)]))
                return
            self.log_guv_str = str(self.file_edit.text())
            self.config.set(self.last_used_scan, 'log_guv',
                            ','.join([self.log_guv_str,
                                      str(True)]))
        else:
            self.config.set(self.last_used_scan, 'log_guv',
                            ','.join([self.log_guv_str,
                                      str(False)]))

        with open('config.ini', 'w') as configfile:
            self.config.write(configfile)

        try:
            self.GUV = GUV.GUV([
                str(self.ipportEdit.text()),
                str(self.tcpportEdit.text()), self.guvtype_str
            ], False, self.config)
        except Exception as e:
            reply = QMessageBox.critical(
                self, ''.join([self.guvtype_str, ' TEST MODE']), ''.join([
                    self.guvtype_str,
                    " could not return valid echo signal. Check the port name and check the connection.\n",
                    str(e),
                    "\n\nShould the program proceeds into the TEST MODE?"
                ]), QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.GUV = GUV.GUV([
                    str(self.ipportEdit.text()),
                    str(self.tcpportEdit.text()), self.guvtype_str
                ], True, self.config)
            else:
                return

        #self.set_clear()
        self.runstopButton.setEnabled(True)
        self.runstopButton.setText("STOP")

        self.clearButton.setEnabled(False)
        self.combo0.setEnabled(False)
        self.ipportEdit.setEnabled(False)
        self.tcpportEdit.setEnabled(False)
        self.guvtype_cb.setEnabled(False)
        self.cb_logdata.setEnabled(False)
        self.file_edit.setEnabled(False)
        self.isRunning = True

        setrun_obj = type('setscan_obj', (object, ), {'guv': self.GUV})

        self.worker = GUV_Worker(setrun_obj)
        self.worker.signals.update0.connect(self.update0)
        self.worker.signals.finished.connect(self.finished)

        # Execute
        self.threadpool.start(self.worker)

    def update0(self, times, volts):

        self.tal += 1
        times = [i + self.stoptime for i in times]

        # set row height
        self.tableWidget.setRowCount(self.tal + 1)
        self.tableWidget.setRowHeight(self.tal, 12)

        # add row elements
        self.tableWidget.setItem(self.tal, 0,
                                 QTableWidgetItem(format(times[0], '.2e')))
        self.tableWidget.setItem(
            self.tal, 1,
            QTableWidgetItem(', '.join(
                [format(float(i), '.2e') for i in volts])))

        if self.tal > self.schroll_pts:
            self.times[:-1] = self.times[
                1:]  # shift data in the array one sample left
            self.times[-1] = times
            self.plot_volts_tr[:-1] = self.plot_volts_tr[
                1:]  # shift data in the array one sample left
            self.plot_volts_tr[-1] = volts
        else:
            self.times.append(times)
            self.plot_volts_tr.append(volts)

        ## Handle view resizing
        def updateViews():
            ## view has resized; update auxiliary views to match
            self.p0_1.setGeometry(self.p1.vb.sceneBoundingRect())
            #p3.setGeometry(p1.vb.sceneBoundingRect())

            ## need to re-update linked axes since this was called
            ## incorrectly while views had different shapes.
            ## (probably this should be handled in ViewBox.resizeEvent)
            self.p0_1.linkedViewChanged(self.p1.vb, self.p0_1.XAxis)
            #p3.linkedViewChanged(p1.vb, p3.XAxis)

        updateViews()
        self.p1.vb.sigResized.connect(updateViews)

        times_ = list(map(list, zip(*self.times)))
        plot_volts_tr_ = list(map(list, zip(*self.plot_volts_tr)))

        for i in range(len(times_)):
            self.curves[i].setData(times_[i], plot_volts_tr_[i])
            #self.curve2.setData(self.times, self.plot_volts_tr)

    def finished(self):

        self.stoptime = self.times[-1][-1]
        self.isRunning = False
        self.ipportEdit.setEnabled(True)
        self.tcpportEdit.setEnabled(True)
        self.guvtype_cb.setEnabled(True)
        self.cb_logdata.setEnabled(True)
        if self.cb_logdata.isChecked():
            self.file_edit.setEnabled(True)
        else:
            self.file_edit.setEnabled(False)
        self.combo0.setEnabled(True)
        self.clearButton.setEnabled(True)
        self.clearButton.setText("Clear")

    def clear_vars_graphs(self):

        # PLOT 2 initial canvas settings
        self.stoptime = 0
        self.tal = -1
        self.times = []
        self.plot_volts_tr = []
        for i in range(20):
            self.curves[i].clear()
        self.curve2.clear()
        self.tableWidget.clearContents()

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Message',
                                     "Quit now? Changes will not be saved!",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:

            if hasattr(self, 'GUV'):
                if self.isRunning:
                    QMessageBox.warning(
                        self, 'Message',
                        "Run in progress. Cancel the scan then quit!")
                    event.ignore()
                    return

            event.accept()
        else:
            event.ignore()
コード例 #55
0
class LyricView(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        NotificationCenter.subscribe(NotificationName.update, self.setLyric)

        self.offset = 0
        self.setWindowTitle('Lyric')
        self.setWindowOpacity(0.5)
        self.setWindowFlags(PyQt5.QtCore.Qt.CustomizeWindowHint
                            | PyQt5.QtCore.Qt.WindowStaysOnTopHint)
        self.main_layout = QGridLayout()

        self.scrollArea = QScrollArea()
        self.scrollArea.setGeometry(QRect(10, 10, 201, 121))
        self.scrollArea.setWidgetResizable(True)

        self.sec_layout = QGridLayout()
        self.fontsize_label = QLabel()
        self.fontsize_label.setText('Font Size')
        self.sec_layout.addWidget(self.fontsize_label, 0, 0, 1, 1)

        self.fontsize_minus_button = QPushButton('-')
        self.fontsize_minus_button.clicked.connect(self.minus)
        self.sec_layout.addWidget(self.fontsize_minus_button, 0, 1, 1, 1)

        self.fontsize_plus_button = QPushButton('+')
        self.fontsize_plus_button.clicked.connect(self.plus)
        self.sec_layout.addWidget(self.fontsize_plus_button, 0, 2, 1, 1)

        self.transparent_label = QLabel()
        self.transparent_label.setText('Transparency')
        self.sec_layout.addWidget(self.transparent_label, 0, 5, 1, 1)

        self.transparent_slider = QSlider(PyQt5.QtCore.Qt.Horizontal)
        self.transparent_slider.setRange(0, 100)
        self.transparent_slider.setValue(50)
        self.transparent_slider.valueChanged[int].connect(
            self.transparentSlideValueChanged)
        self.sec_layout.addWidget(self.transparent_slider, 0, 6, 1, 1)

        self.main_layout.addLayout(self.sec_layout, 1, 0, 1, 1)

        self.lyric_view = QLabel()
        self.fontsize = 20
        self.lyric_view.setStyleSheet("font: %dpt Consolas" % (self.fontsize))
        self.lyric_view.setAlignment(PyQt5.QtCore.Qt.AlignCenter)
        self.lyric_view.setText('')

        self.scrollArea.setWidget(self.lyric_view)

        self.main_layout.addWidget(self.scrollArea, 0, 0, 1, 9)

        self.thd_layout = QGridLayout()
        self.artist_label = QLabel('Artist : ')
        self.thd_layout.addWidget(self.artist_label, 0, 0, 1, 1)
        self.artist_input = QLineEdit()
        self.thd_layout.addWidget(self.artist_input, 0, 1, 1, 1)
        self.title_label = QLabel('Title : ')
        self.thd_layout.addWidget(self.title_label, 0, 2, 1, 1)
        self.title_input = QLineEdit()
        self.thd_layout.addWidget(self.title_input, 0, 3, 1, 1)
        self.search_button = QPushButton('Search')
        self.search_button.clicked.connect(self.searchLyric)
        self.thd_layout.addWidget(self.search_button, 0, 4, 1, 1)
        self.main_layout.addLayout(self.thd_layout, 2, 0, 1, 1)

        self.setLayout(self.main_layout)

    def minus(self):
        self.fontsize -= 1
        if self.fontsize <= 1:
            self.fontsize = 1
        self.lyric_view.setStyleSheet("font: %dpt Consolas" % (self.fontsize))

    def plus(self):
        self.fontsize += 1
        self.lyric_view.setStyleSheet("font: %dpt Consolas" % (self.fontsize))

    def transparentSlideValueChanged(self):
        self.setWindowOpacity(self.transparent_slider.value() * 0.01)

    def mousePressEvent(self, event):
        self.offset = event.pos()

    def mouseMoveEvent(self, event):
        x = event.globalX()
        y = event.globalY()
        x_w = self.offset.x()
        y_w = self.offset.y()
        self.move(x - x_w, y - y_w)

    def searchLyric(self):
        self.setLyricHelper(
            [self.artist_input.text(),
             self.title_input.text()])

    def setLyric(self, info):
        data = []
        for i in ['-', ':', ',']:
            if i in info:
                data = info.split(i)
                break

        if len(data) != 2:
            data = ['', '']

        self.artist_input.setText(data[0])
        self.title_input.setText(data[1])
        self.setLyricHelper(data)

    def setLyricHelper(self, data):
        lyric_loader = LyricLoader(data)
        lines = lyric_loader.lyric.split('<br>')
        lyric = ''
        for i in lines:
            lyric += i[10:] + '\r\n'
        self.lyric_view.setText(lyric)
コード例 #56
0
class MainWindow(QMainWindow, Ui_MainWindow):
    # Maintain the list of browser windows so that they do not get garbage
    # collected.
    _window_list = []

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

        MainWindow._window_list.append(self)

        self.setupUi(self)

        # Qt Designer (at least to v4.2.1) can't handle arbitrary widgets in a
        # QToolBar - even though uic can, and they are in the original .ui
        # file.  Therefore we manually add the problematic widgets.
        self.lblAddress = QLabel("Address", self.tbAddress)
        self.tbAddress.insertWidget(self.actionGo, self.lblAddress)
        self.addressEdit = QLineEdit(self.tbAddress)
        self.tbAddress.insertWidget(self.actionGo, self.addressEdit)

        self.addressEdit.returnPressed.connect(self.actionGo.trigger)
        self.actionBack.triggered.connect(self.WebBrowser.GoBack)
        self.actionForward.triggered.connect(self.WebBrowser.GoForward)
        self.actionStop.triggered.connect(self.WebBrowser.Stop)
        self.actionRefresh.triggered.connect(self.WebBrowser.Refresh)
        self.actionHome.triggered.connect(self.WebBrowser.GoHome)
        self.actionSearch.triggered.connect(self.WebBrowser.GoSearch)

        self.pb = QProgressBar(self.statusBar())
        self.pb.setTextVisible(False)
        self.pb.hide()
        self.statusBar().addPermanentWidget(self.pb)

        self.WebBrowser.dynamicCall('GoHome()')

    def closeEvent(self, e):
        MainWindow._window_list.remove(self)
        e.accept()

    def on_WebBrowser_TitleChange(self, title):
        self.setWindowTitle("Qt WebBrowser - " + title)

    def on_WebBrowser_ProgressChange(self, a, b):
        if a <= 0 or b <= 0:
            self.pb.hide()
            return

        self.pb.show()
        self.pb.setRange(0, b)
        self.pb.setValue(a)

    def on_WebBrowser_CommandStateChange(self, cmd, on):
        if cmd == 1:
            self.actionForward.setEnabled(on)
        elif cmd == 2:
            self.actionBack.setEnabled(on)

    def on_WebBrowser_BeforeNavigate(self):
        self.actionStop.setEnabled(True)

    def on_WebBrowser_NavigateComplete(self, _):
        self.actionStop.setEnabled(False)

    @pyqtSlot()
    def on_actionGo_triggered(self):
        self.WebBrowser.dynamicCall('Navigate(const QString&)',
                                    self.addressEdit.text())

    @pyqtSlot()
    def on_actionNewWindow_triggered(self):
        window = MainWindow()
        window.show()
        if self.addressEdit.text().isEmpty():
            return

        window.addressEdit.setText(self.addressEdit.text())
        window.actionStop.setEnabled(True)
        window.on_actionGo_triggered()

    @pyqtSlot()
    def on_actionAbout_triggered(self):
        QMessageBox.about(
            self, "About WebBrowser",
            "This Example has been created using the ActiveQt integration into Qt Designer.\n"
            "It demonstrates the use of QAxWidget to embed the Internet Explorer ActiveX\n"
            "control into a Qt application.")

    @pyqtSlot()
    def on_actionAboutQt_triggered(self):
        QMessageBox.aboutQt(self, "About Qt")
コード例 #57
0
ファイル: mainwindow.py プロジェクト: ag-pyqt/EbookCreator
class MainWindow(QMainWindow):
    htmlReady = pyqtSignal(str)

    def __init__(self, app):
        QMainWindow.__init__(self)
        self.install_directory = os.getcwd()

        self.app = app
        self.book = None
        self.last_book = ""
        self.filename = ""
        self._part_is_new = False
        self.tread_running = False
        self.initTheme()
        self.createUi()
        self.loadPlugins()
        self.createMenus()
        self.createStatusBar()
        self.readSettings()

        self.text_edit.textChanged.connect(self.textChanged)

    def initTheme(self):
        settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                             QCoreApplication.organizationName(),
                             QCoreApplication.applicationName())
        self.theme = settings.value("theme", "DarkFusion")
        hilite_color = settings.value(
            "hiliteColor",
            self.palette().highlight().color().name())
        self.changeStyle(self.theme, hilite_color)

    def showEvent(self, event):
        if self.last_book:
            self.loadBook(self.last_book)

    def changeStyle(self, theme, hilite_color):
        self.theme = theme
        if theme == "DarkFusion":
            QApplication.setStyle(DarkFusion(hilite_color))
        else:
            QApplication.setStyle(QStyleFactory.create(theme))
            pal = self.app.palette()
            pal.setColor(QPalette.Highlight, QColor(hilite_color))
            self.app.setPalette(pal)

    def createUi(self):
        self.content = Expander("Content", ":/images/parts.svg")
        self.images = Expander("Images", ":/images/images.svg")
        self.settings = Expander("Settings", ":/images/settings.svg")

        self.setWindowTitle(QCoreApplication.applicationName() + " " +
                            QCoreApplication.applicationVersion())
        vbox = QVBoxLayout()
        vbox.addWidget(self.content)
        vbox.addWidget(self.images)
        vbox.addWidget(self.settings)
        vbox.addStretch()

        self.content_list = QListWidget()
        self.content_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        content_box = QVBoxLayout()
        content_box.addWidget(self.content_list)
        self.item_edit = QLineEdit()
        self.item_edit.setMaximumHeight(0)
        self.item_edit.editingFinished.connect(self.editItemFinished)
        self.item_anim = QPropertyAnimation(self.item_edit,
                                            "maximumHeight".encode("utf-8"))
        content_box.addWidget(self.item_edit)
        button_layout = QHBoxLayout()
        plus_button = FlatButton(":/images/plus.svg")
        self.edit_button = FlatButton(":/images/edit.svg")
        self.trash_button = FlatButton(":/images/trash.svg")
        self.up_button = FlatButton(":/images/up.svg")
        self.down_button = FlatButton(":/images/down.svg")
        self.trash_button.enabled = False
        self.up_button.enabled = False
        self.down_button.enabled = False
        button_layout.addWidget(plus_button)
        button_layout.addWidget(self.up_button)
        button_layout.addWidget(self.down_button)
        button_layout.addWidget(self.edit_button)
        button_layout.addWidget(self.trash_button)
        content_box.addLayout(button_layout)
        self.content.addLayout(content_box)
        plus_button.clicked.connect(self.addPart)
        self.trash_button.clicked.connect(self.dropPart)
        self.up_button.clicked.connect(self.partUp)
        self.down_button.clicked.connect(self.partDown)
        self.edit_button.clicked.connect(self.editPart)

        self.image_list = QListWidget()
        self.image_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        image_box = QVBoxLayout()
        image_box.addWidget(self.image_list)
        image_button_layout = QHBoxLayout()
        image_plus_button = FlatButton(":/images/plus.svg")
        self.image_trash_button = FlatButton(":/images/trash.svg")
        self.image_trash_button.enabled = False
        image_button_layout.addWidget(image_plus_button)
        image_button_layout.addWidget(self.image_trash_button)
        image_box.addLayout(image_button_layout)
        self.images.addLayout(image_box)
        image_plus_button.clicked.connect(self.addImage)
        self.image_trash_button.clicked.connect(self.dropImage)

        scroll_content = QWidget()
        scroll_content.setLayout(vbox)
        scroll = QScrollArea()
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll.setWidget(scroll_content)
        scroll.setWidgetResizable(True)
        scroll.setMaximumWidth(200)
        scroll.setMinimumWidth(200)

        self.navigationdock = QDockWidget("Navigation", self)
        self.navigationdock.setAllowedAreas(Qt.LeftDockWidgetArea
                                            | Qt.RightDockWidgetArea)
        self.navigationdock.setWidget(scroll)
        self.navigationdock.setObjectName("Navigation")
        self.addDockWidget(Qt.LeftDockWidgetArea, self.navigationdock)

        self.splitter = QSplitter()
        self.text_edit = MarkdownEdit()
        self.text_edit.setFont(QFont("Courier", 11))
        self.preview = QWebEngineView()
        self.preview.setMinimumWidth(300)
        self.setWindowTitle(QCoreApplication.applicationName())

        self.splitter.addWidget(self.text_edit)
        self.splitter.addWidget(self.preview)
        self.setCentralWidget(self.splitter)

        self.content.expanded.connect(self.contentExpanded)
        self.images.expanded.connect(self.imagesExpanded)
        self.settings.expanded.connect(self.settingsExpanded)
        self.settings.clicked.connect(self.openSettings)
        self.content_list.currentItemChanged.connect(self.partSelectionChanged)
        self.image_list.currentItemChanged.connect(self.imageSelectionChanged)
        self.image_list.itemDoubleClicked.connect(self.insertImage)

        self.text_edit.undoAvailable.connect(self.undoAvailable)
        self.text_edit.redoAvailable.connect(self.redoAvailable)
        self.text_edit.copyAvailable.connect(self.copyAvailable)

        QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged)

    def undoAvailable(self, value):
        self.undo_act.setEnabled(value)

    def redoAvailable(self, value):
        self.redo_act.setEnabled(value)

    def copyAvailable(self, value):
        self.copy_act.setEnabled(value)
        self.cut_act.setEnabled(value)

    def clipboardDataChanged(self):
        md = QApplication.clipboard().mimeData()
        self.paste_act.setEnabled(md.hasText())

    def openSettings(self):
        dlg = Settings(self.book, self.install_directory)
        dlg.exec()
        if dlg.saved:
            self.setWindowTitle(QCoreApplication.applicationName() + " - " +
                                self.book.name)

    def addPart(self):
        self.item_edit.setText("")
        self.item_edit.setFocus()
        self.item_anim.setStartValue(0)
        self.item_anim.setEndValue(23)
        self.item_anim.start()
        self._part_is_new = True

    def addItem(self):
        text = self.item_edit.text()
        if text:
            if not self.book.getPart(text):
                self.book.addPart(text)
                self.loadBook(self.last_book)

    def updateItem(self):
        text = self.item_edit.text()
        if text:
            if not self.book.getPart(text):
                self.book.updatePart(
                    self.content_list.currentItem().data(1).name, text)
                self.loadBook(self.last_book)

    def editItemFinished(self):
        if self._part_is_new:
            self.addItem()
        else:
            self.updateItem()
        self.item_anim.setStartValue(23)
        self.item_anim.setEndValue(0)
        self.item_anim.start()

    def editPart(self):
        item = self.content_list.currentItem().data(1).name
        self.item_edit.setText(item)
        self.item_edit.setFocus()
        self.item_anim.setStartValue(0)
        self.item_anim.setEndValue(23)
        self.item_anim.start()
        self._part_is_new = False

    def dropPart(self):
        item = self.content_list.currentItem().data(1).name
        msgBox = QMessageBox()
        msgBox.setText("You are about to delete the part <i>" + item + "</i>")
        msgBox.setInformativeText("Do you really want to delete the item?")
        msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        msgBox.setDefaultButton(QMessageBox.Cancel)
        ret = msgBox.exec()
        if ret == QMessageBox.Yes:
            self.book.dropPart(item)
            self.loadBook(self.last_book)

    def addImage(self):
        fileName = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("Image Files(*.png *.jpg *.bmp *.gif);;All (*)")
        dialog.setWindowTitle("Load Image")
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        if dialog.exec_():
            fileName = dialog.selectedFiles()[0]
        del dialog
        if not fileName:
            return

        base = os.path.basename(fileName)
        if not os.path.exists(
                os.path.join(self.book.source_path, "images", base)):
            copy(fileName, os.path.join(self.book.source_path, "images"))
        item = QListWidgetItem()
        item.setText(Path(fileName).name)
        item.setData(
            1,
            os.path.join(self.book.source_path, "images",
                         Path(fileName).name))
        self.image_list.addItem(item)

    def dropImage(self):
        item = self.image_list.currentItem()
        image = item.data(1)
        filename = os.path.join(self.book.source_path, "parts", image)
        os.remove(filename)
        self.loadImages()

    def loadImages(self):
        self.image_list.clear()
        for root, dir, files in os.walk(
                os.path.join(self.book.source_path, "images")):
            for file in files:
                filename = os.path.join(self.book.source_path, "images",
                                        Path(file).name)
                item = QListWidgetItem()
                item.setToolTip("Doubleclick image to insert into text")
                item.setText(Path(file).name)
                item.setData(1, filename)
                self.image_list.addItem(item)

    def partUp(self):
        pos = self.content_list.currentRow()
        item = self.content_list.takeItem(pos)
        self.content_list.insertItem(pos - 1, item)
        self.content_list.setCurrentRow(pos - 1)
        self.book.partUp(item.data(1).name)

    def partDown(self):
        pos = self.content_list.currentRow()
        item = self.content_list.takeItem(pos)
        self.content_list.insertItem(pos + 1, item)
        self.content_list.setCurrentRow(pos + 1)
        self.book.partDown(item.data(1).name)

    def partSelectionChanged(self, item):
        if item:
            part = item.data(1)
            self.filename = os.path.join(self.book.source_path, "parts",
                                         part.src)
            with open(self.filename, "r") as f:
                t = f.read()
                self.text_edit.setPlainText(t)
            self.trash_button.enabled = True
            self.up_button.enabled = self.content_list.currentRow() > 0
            self.down_button.enabled = self.content_list.currentRow(
            ) < self.content_list.count() - 1
            self.edit_button.enabled = True
        else:
            self.text_edit.setText("")
            self.trash_button.enabled = False
            self.up_button.enabled = False
            self.down_button.enabled = False
            self.edit_button.enabled = False

    def imageSelectionChanged(self, item):
        if item:
            self.image_trash_button.enabled = True
        else:
            self.image_trash_button.enabled = False

    def contentExpanded(self, value):
        if value:
            self.images.setExpanded(False)
            self.settings.setExpanded(False)

    def imagesExpanded(self, value):
        if value:
            self.content.setExpanded(False)
            self.settings.setExpanded(False)

    def appearanceExpanded(self, value):
        if value:
            self.content.setExpanded(False)
            self.images.setExpanded(False)
            self.settings.setExpanded(False)

    def settingsExpanded(self, value):
        if value:
            self.content.setExpanded(False)
            self.images.setExpanded(False)

    def closeEvent(self, event):
        self.writeSettings()
        event.accept()

    def createMenus(self):
        new_icon = QIcon(QPixmap(":/images/new.svg"))
        open_icon = QIcon(QPixmap(":/images/open.svg"))
        book_icon = QIcon(QPixmap(":/images/book.svg"))
        bold_icon = QIcon(QPixmap(":/images/bold.svg"))
        italic_icon = QIcon(QPixmap(":/images/italic.svg"))
        image_icon = QIcon(QPixmap(":/images/image.svg"))
        table_icon = QIcon(QPixmap(":/images/table.svg"))
        á_icon = QIcon(QPixmap(":/images/á.svg"))
        ã_icon = QIcon(QPixmap(":/images/ã.svg"))
        é_icon = QIcon(QPixmap(":/images/é.svg"))
        ê_icon = QIcon(QPixmap(":/images/ê.svg"))
        ó_icon = QIcon(QPixmap(":/images/ó.svg"))

        new_act = QAction(new_icon, "&New", self)
        new_act.setShortcuts(QKeySequence.New)
        new_act.setStatusTip("Create a new ebook project")
        new_act.triggered.connect(self.newFile)
        new_act.setToolTip("Create new ebook project")

        open_act = QAction(open_icon, "&Open", self)
        open_act.setShortcuts(QKeySequence.Open)
        open_act.setStatusTip("Open an existing ebook project")
        open_act.triggered.connect(self.open)
        open_act.setToolTip("Open an existing ebook project")

        book_act = QAction(book_icon, "&Create Book", self)
        book_act.setShortcuts(QKeySequence.SaveAs)
        book_act.setStatusTip("Create an ebook")
        book_act.triggered.connect(self.create)
        book_act.setToolTip("Create an ebook")

        pdf_act = QAction("Create &PDF", self)
        pdf_act.setStatusTip("Create PDF")
        pdf_act.setToolTip("Create PDF")
        pdf_act.triggered.connect(self.pdfExport)

        settings_act = QAction("&Settings", self)
        settings_act.setStatusTip("Open settings dialog")
        settings_act.triggered.connect(self.settingsDialog)
        settings_act.setToolTip("Open settings dialog")

        exit_act = QAction("E&xit", self)
        exit_act.setShortcuts(QKeySequence.Quit)
        exit_act.setStatusTip("Exit the application")
        exit_act.triggered.connect(self.close)

        self.undo_act = QAction("Undo", self)
        self.undo_act.setShortcut(QKeySequence.Undo)
        self.undo_act.setEnabled(False)
        self.undo_act.triggered.connect(self.doUndo)

        self.redo_act = QAction("Redo", self)
        self.redo_act.setShortcut(QKeySequence.Redo)
        self.redo_act.setEnabled(False)
        self.undo_act.triggered.connect(self.doRedo)

        self.cut_act = QAction("Cu&t", self)
        self.cut_act.setShortcut(QKeySequence.Cut)
        self.cut_act.triggered.connect(self.doCut)
        self.cut_act.setEnabled(False)

        self.copy_act = QAction("&Copy", self)
        self.copy_act.setShortcut(QKeySequence.Copy)
        self.copy_act.triggered.connect(self.doCopy)
        self.copy_act.setEnabled(False)

        self.paste_act = QAction("&Paste", self)
        self.paste_act.setShortcut(QKeySequence.Paste)
        self.paste_act.triggered.connect(self.doPaste)
        self.paste_act.setEnabled(False)

        bold_act = QAction(bold_icon, "Bold", self)
        bold_act.setShortcut(Qt.CTRL + Qt.Key_B)
        bold_act.triggered.connect(self.bold)

        italic_act = QAction(italic_icon, "Italic", self)
        italic_act.setShortcut(Qt.CTRL + Qt.Key_I)
        italic_act.triggered.connect(self.italic)

        image_act = QAction(image_icon, "Image", self)
        image_act.setShortcut(Qt.CTRL + Qt.Key_G)
        image_act.triggered.connect(self.insertImage)
        image_act.setToolTip("Insert an image")

        table_act = QAction(table_icon, "Table", self)
        table_act.setShortcut(Qt.CTRL + Qt.Key_T)
        table_act.triggered.connect(self.insertTable)
        table_act.setToolTip("Insert a table")

        á_act = QAction(á_icon, "á", self)
        á_act.triggered.connect(self.insertLetterA1)
        á_act.setToolTip("Insert letter á")

        ã_act = QAction(ã_icon, "ã", self)
        ã_act.triggered.connect(self.insertLetterA2)
        ã_act.setToolTip("Insert letter ã")

        é_act = QAction(é_icon, "é", self)
        é_act.triggered.connect(self.insertLetterE1)
        é_act.setToolTip("Insert letter é")

        ê_act = QAction(ê_icon, "ê", self)
        ê_act.triggered.connect(self.insertLetterE2)
        ê_act.setToolTip("Insert letter ê")

        ó_act = QAction(ó_icon, "ó", self)
        ó_act.triggered.connect(self.insertLetterO1)
        ó_act.setToolTip("Insert letter ó")

        about_act = QAction("&About", self)
        about_act.triggered.connect(self.about)
        about_act.setStatusTip("Show the application's About box")

        spell_act = QAction("&Spellcheck", self)
        spell_act.setShortcut(Qt.CTRL + Qt.Key_P)
        spell_act.triggered.connect(self.spellCheck)
        spell_act.setStatusTip("Spellcheck")

        file_menu = self.menuBar().addMenu("&File")
        file_menu.addAction(new_act)
        file_menu.addAction(open_act)
        file_menu.addAction(book_act)
        file_menu.addAction(pdf_act)
        file_menu.addSeparator()
        file_menu.addAction(settings_act)
        file_menu.addSeparator()
        file_menu.addAction(exit_act)

        edit_menu = self.menuBar().addMenu("&Edit")
        edit_menu.addAction(self.undo_act)
        edit_menu.addAction(self.redo_act)
        edit_menu.addSeparator()
        edit_menu.addAction(self.cut_act)
        edit_menu.addAction(self.copy_act)
        edit_menu.addAction(self.paste_act)

        format_menu = self.menuBar().addMenu("&Format")
        format_menu.addAction(bold_act)
        format_menu.addAction(italic_act)

        insert_menu = self.menuBar().addMenu("&Insert")
        insert_menu.addAction(image_act)
        insert_menu.addAction(table_act)

        for key in Plugins.generatorPluginNames():
            gen = Plugins.getGeneratorPlugin(key)
            if gen:
                act = QAction(gen.display_name, self)
                #act.triggered.connect(self.insertTable)
                #act.setToolTip("Insert a table")
                insert_menu.addAction(act)
                act.triggered.connect(gen.menu_action)

        help_menu = self.menuBar().addMenu("&Help")
        help_menu.addAction(about_act)
        help_menu.addAction(spell_act)

        file_tool_bar = self.addToolBar("File")
        file_tool_bar.addAction(new_act)
        file_tool_bar.addAction(open_act)
        file_tool_bar.addAction(book_act)

        format_tool_bar = self.addToolBar("Format")
        format_tool_bar.addAction(bold_act)
        format_tool_bar.addAction(italic_act)

        insert_toolbar = self.addToolBar("Insert")
        insert_toolbar.addAction(image_act)
        insert_toolbar.addAction(table_act)
        insert_toolbar.addAction(á_act)
        insert_toolbar.addAction(ã_act)
        insert_toolbar.addAction(é_act)
        insert_toolbar.addAction(ê_act)
        insert_toolbar.addAction(ó_act)

    def doUndo(self):
        self.text_edit.undo()

    def doRedo(self):
        self.text_edit.redo()

    def doCut(self):
        self.text_edit.cut()

    def doCopy(self):
        self.text_edit.copy()

    def doPaste(self):
        self.text_edit.paste()

    def insertImage(self):
        if not self.book:
            QMessageBox.warning(self, QCoreApplication.applicationName(),
                                "You have to load or create a book first!")
            return
        if not self.filename:
            QMessageBox.warning(
                self, QCoreApplication.applicationName(),
                "You have to select part from the book content first!")
            return
        if self.image_list.count() == 0:
            QMessageBox.warning(
                self, QCoreApplication.applicationName(),
                "You have to add an image to the image list first!")
            return
        if not self.image_list.currentItem():
            QMessageBox.warning(
                self, QCoreApplication.applicationName(),
                "You have to select an image from the image list first!")
            return

        item = self.image_list.currentItem()
        filename = item.text()
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        base = filename.split(".")[0].replace("_", "-")
        cursor.insertText("![" + base + "](../images/" + filename + " \"" +
                          base + "\")")
        cursor.setPosition(pos)
        self.text_edit.setTextCursor(cursor)

    def insertTable(self):
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        cursor.insertText(
            "| alignLeft | alignCenter | unAligned | alignRight |\n"
            "|  :---     |   :---:     |   ---     |   ---:     |\n"
            "|  cell a   |   cell b    |   cell c  |   cell d   |\n"
            "|  cell e   |   cell f    |   cell g  |   cell h   |\n")
        cursor.setPosition(pos)
        self.text_edit.setTextCursor(cursor)

    def insertLetterA1(self):
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        cursor.insertText("á")
        cursor.setPosition(pos + 1)
        self.text_edit.setTextCursor(cursor)

    def insertLetterA2(self):
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        cursor.insertText("ã")
        cursor.setPosition(pos + 1)
        self.text_edit.setTextCursor(cursor)

    def insertLetterE1(self):
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        cursor.insertText("é")
        cursor.setPosition(pos + 1)
        self.text_edit.setTextCursor(cursor)

    def insertLetterE2(self):
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        cursor.insertText("ê")
        cursor.setPosition(pos + 1)
        self.text_edit.setTextCursor(cursor)

    def insertLetterO1(self):
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        cursor.insertText("ó")
        cursor.setPosition(pos + 1)
        self.text_edit.setTextCursor(cursor)

    def createStatusBar(self):
        self.statusBar().showMessage("Ready")

    def about(self):
        QMessageBox.about(
            self, "About " + QCoreApplication.applicationName(),
            "EbookCreator\nVersion: " + QCoreApplication.applicationVersion() +
            "\n(C) Copyright 2020 CrowdWare. All rights reserved.\n\nThis program is provided AS IS with NO\nWARRANTY OF ANY KIND, INCLUDING THE\nWARRANTY OF DESIGN, MERCHANTABILITY AND\nFITNESS FOR A PATICULAR PURPOSE."
        )

    def newFile(self):
        dlg = ProjectWizard(self.install_directory, parent=self)
        dlg.loadBook.connect(self.loadBook)
        dlg.show()

    def open(self):
        fileName = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("EbookCreator (book.qml);;All (*)")
        dialog.setWindowTitle("Load Ebook")
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        dialog.setDirectory(os.path.join(self.install_directory, "sources"))
        if dialog.exec_():
            fileName = dialog.selectedFiles()[0]
        del dialog
        if not fileName:
            return
        self.loadBook(fileName)

    def writeSettings(self):
        settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                             QCoreApplication.organizationName(),
                             QCoreApplication.applicationName())
        settings.setValue("geometry", self.saveGeometry())
        settings.setValue("lastBook", self.last_book)

    def readSettings(self):
        settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                             QCoreApplication.organizationName(),
                             QCoreApplication.applicationName())
        geometry = settings.value("geometry", QByteArray())
        self.last_book = settings.value("lastBook")
        if not geometry:
            availableGeometry = QApplication.desktop().availableGeometry(self)
            self.resize(availableGeometry.width() / 3,
                        availableGeometry.height() / 2)
            self.move((availableGeometry.width() - self.width()) / 2,
                      (availableGeometry.height() - self.height()) / 2)
        else:
            self.restoreGeometry(geometry)

    def bold(self):
        if not self.filename:
            QMessageBox.warning(
                self, QCoreApplication.applicationName(),
                "You have to select part from the book content first!")
            return
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        if not cursor.hasSelection():
            cursor.select(QTextCursor.WordUnderCursor)
        cursor.insertText("**" + cursor.selectedText() + "**")
        cursor.setPosition(pos + 2)
        self.text_edit.setTextCursor(cursor)

    def italic(self):
        if not self.filename:
            QMessageBox.warning(
                self, QCoreApplication.applicationName(),
                "You have to select part from the book content first!")
            return
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        if not cursor.hasSelection():
            cursor.select(QTextCursor.WordUnderCursor)
        cursor.insertText("*" + cursor.selectedText() + "*")
        cursor.setPosition(pos + 1)
        self.text_edit.setTextCursor(cursor)

    def create(self):
        filename = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("ePub3 (*.epub);;All (*)")
        dialog.setWindowTitle("Create Ebook")
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setDirectory(self.book.source_path)
        dialog.setDefaultSuffix("epub")
        if dialog.exec_():
            filename = dialog.selectedFiles()[0]
        del dialog
        if not filename:
            return
        QApplication.setOverrideCursor(Qt.WaitCursor)
        createEpub(filename, self.book, self)
        QApplication.restoreOverrideCursor()

    def loadStatusChanged(self, status):
        if status == 1:
            self.book = self.component.create()
            if self.book is not None:
                self.book.setFilename(self.last_book)
                self.book.setWindow(self)
            else:
                for error in self.component.errors():
                    print(error.toString())
                return

            self.content_list.clear()
            for part in self.book.parts:
                item = QListWidgetItem()
                item.setText(part.name)
                item.setData(1, part)
                self.content_list.addItem(item)

            self.loadImages()
            self.setWindowTitle(QCoreApplication.applicationName() + " - " +
                                self.book.name)

            self.content.setExpanded(True)
            self.content_list.setCurrentRow(0)
        elif status == 3:
            for error in self.component.errors():
                print(error.toString())
            return

    def loadBook(self, filename):
        self.last_book = filename
        self.filename = ""
        engine = QQmlEngine()
        self.component = QQmlComponent(engine)
        self.component.statusChanged.connect(self.loadStatusChanged)
        self.component.loadUrl(QUrl.fromLocalFile(filename))

    def settingsDialog(self):
        dlg = SettingsDialog(self.theme,
                             self.palette().highlight().color().name(),
                             parent=self)
        dlg.exec()
        if dlg.theme != self.theme or dlg.hilite_color != self.palette(
        ).highlight().color().name():
            settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                                 QCoreApplication.organizationName(),
                                 QCoreApplication.applicationName())
            settings.setValue("theme", dlg.theme)
            settings.setValue("hiliteColor", dlg.hilite_color)

            msgBox = QMessageBox()
            msgBox.setText("Please restart the app to change the theme!")
            msgBox.exec()

    def textChanged(self):
        text = self.text_edit.toPlainText()
        if self.filename:
            with open(self.filename, "w") as f:
                f.write(text)

        self.lock = Lock()
        with self.lock:
            if not self.tread_running:
                self.tread_running = True
                self.htmlReady.connect(self.previewReady)
                thread = Thread(target=self.createHtml, args=(text, ))
                thread.daemon = True
                thread.start()

    def previewReady(self, html):
        self.preview.setHtml(
            html,
            baseUrl=QUrl(
                Path(os.path.join(self.book.source_path, "parts",
                                  "index.html")).as_uri()))
        self.htmlReady.disconnect()
        with self.lock:
            self.tread_running = False

    def createHtml(self, text):
        html = '<html>\n<head>\n'
        html += '<link href="../css/pastie.css" rel="stylesheet" type="text/css"/>\n'
        html += '<link href="../css/stylesheet.css" rel="stylesheet" type="text/css"/>\n'
        html += '</head>\n<body>\n'
        html += markdown(text,
                         html4tags=False,
                         extras=[
                             "fenced-code-blocks", "wiki-tables", "tables",
                             "header-ids"
                         ])
        html += '\n</body>\n</html>'
        html = addLineNumbers(html)
        self.htmlReady.emit(html)

    def pdfExport(self):
        p = PdfExport(self.book, self.statusBar())

    def spellCheck(self):
        if not self.filename:
            QMessageBox.warning(
                self, QCoreApplication.applicationName(),
                "You have to select part from the book content first!")
            return
        cursor = self.text_edit.textCursor()
        pos = cursor.position()
        if not cursor.hasSelection():
            cursor.select(QTextCursor.WordUnderCursor)
        spell = Speller(lang='en')
        changed = spell(cursor.selectedText())
        if changed != cursor.selectedText():
            cursor.insertText(changed)
            self.text_edit.setTextCursor(cursor)

    def loadPlugins(self):
        # check if we are running in a frozen environment (pyinstaller --onefile)
        if getattr(sys, "frozen", False):
            bundle_dir = sys._MEIPASS
            # if we are running in a onefile environment, then copy all plugin to /tmp/...
            if bundle_dir != os.getcwd():
                os.mkdir(os.path.join(bundle_dir, "plugins"))
                for root, dirs, files in os.walk(
                        os.path.join(os.getcwd(), "plugins")):
                    for file in files:
                        shutil.copy(os.path.join(root, file),
                                    os.path.join(bundle_dir, "plugins"))
                        print("copy", file)
                    break  # do not copy __pycache__
        else:
            bundle_dir = os.getcwd()

        plugins_dir = os.path.join(bundle_dir, "plugins")
        for root, dirs, files in os.walk(plugins_dir):
            for file in files:
                modulename, ext = os.path.splitext(file)
                if ext == ".py":
                    module = import_module("plugins." + modulename)
                    for name, klass in inspect.getmembers(
                            module, inspect.isclass):
                        if klass.__module__ == "plugins." + modulename:
                            instance = klass()
                            if isinstance(instance, GeneratorInterface):
                                Plugins.addGeneratorPlugin(name, instance)
                                instance.setTextEdit(self.text_edit)
                                #instance.registerContenType()
            break  # not to list __pycache__
コード例 #58
0
ファイル: email_tab.py プロジェクト: JoeEmp/AirMemo
    def setupUi(self):
        self.gridLayoutWidget = QWidget(self)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 500, 350))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")

        self.tips_lab = QLabel(self.gridLayoutWidget)
        self.tips_lab.setMaximumSize(QtCore.QSize(130, 15))
        self.tips_lab.setText('暂不支持stmp')
        self.tips_lab.setObjectName("tips_lab")
        self.gridLayout.addWidget(self.tips_lab, 0, 0, 1, 1)

        self.email_list = QListWidget(self.gridLayoutWidget)
        for record in self._email_records:
            item = QListWidgetItem(record['addr'])
            if record['is_default'] == 1:
                brush = QtGui.QBrush(QtGui.QColor(1, 203, 31))
                brush.setStyle(QtCore.Qt.NoBrush)
                item.setForeground(brush)
            item.data = record
            self.email_list.addItem(item)
        self.email_list.itemClicked.connect(self.set_email_config_form)
        self.gridLayout.addWidget(self.email_list, 1, 0, 4, 4)

        self.default_email_btn = QPushButton(self.gridLayoutWidget)
        self.default_email_btn.setText('设置默认')
        self.default_email_btn.clicked.connect(self._selectDefualt)
        self.gridLayout.addWidget(self.default_email_btn, 5, 0, 1, 1)

        self.del_email_btn = QPushButton(self.gridLayoutWidget)
        self.del_email_btn.setText('删除')
        self.del_email_btn.clicked.connect(self.del_email_config)
        self.gridLayout.addWidget(self.del_email_btn, 5, 3, 1, 1)

        self.add_email_btn = QPushButton(self.gridLayoutWidget)
        self.add_email_btn.setText('添加邮箱')
        self.add_email_btn.clicked.connect(self.set_email_config_form)
        self.gridLayout.addWidget(self.add_email_btn, 5, 1, 1, 1)

        self.email_lab = QLabel(self.gridLayoutWidget)
        self.email_lab.setText('邮箱地址')
        self.gridLayout.addWidget(self.email_lab, 1, 4, 1, 1)

        self.email_le = QLineEdit(self.gridLayoutWidget)
        self.gridLayout.addWidget(self.email_le, 1, 5, 1, 2)

        self.password_lab = QLabel(self.gridLayoutWidget)
        self.password_lab.setText('密码')
        self.gridLayout.addWidget(self.password_lab, 2, 4, 1, 1)

        self.password_le = QLineEdit(self.gridLayoutWidget)
        self.gridLayout.addWidget(self.password_le, 2, 5, 1, 2)
        self.password_le.setEchoMode(QLineEdit.Password)

        self.ssl_lab = QLabel(self.gridLayoutWidget)
        self.ssl_lab.setText('ssl端口')
        self.gridLayout.addWidget(self.ssl_lab, 3, 4, 1, 1)

        self.ssl_rbtn = QRadioButton(self.gridLayoutWidget)
        self.ssl_rbtn.setText("")
        self.ssl_rbtn.setObjectName("ssl_rbtn")
        self.ssl_rbtn.clicked.connect(self.chcek_radio_slot)
        self.gridLayout.addWidget(self.ssl_rbtn, 3, 5, 1, 1)

        self.ssl_port_le = QLineEdit(self.gridLayoutWidget)
        self.ssl_port_le.setObjectName("ssl_le")
        self.gridLayout.addWidget(self.ssl_port_le, 3, 6, 1, 1)

        self.sender_le = QLineEdit(self.gridLayoutWidget)
        self.sender_le.setObjectName("sender_le")
        self.gridLayout.addWidget(self.sender_le, 4, 5, 1, 2)

        self.sender_lab = QLabel(self.gridLayoutWidget)
        self.sender_lab.setText('发信名称')
        self.gridLayout.addWidget(self.sender_lab, 4, 4, 1, 1)

        self.save_email_btn = QPushButton(self.gridLayoutWidget)
        self.save_email_btn.setText('保存')
        self.save_email_btn.clicked.connect(self.save_email_config)
        self.gridLayout.addWidget(self.save_email_btn, 5, 6, 1, 1)
コード例 #59
0
ファイル: mainwindow.py プロジェクト: ag-pyqt/EbookCreator
    def createUi(self):
        self.content = Expander("Content", ":/images/parts.svg")
        self.images = Expander("Images", ":/images/images.svg")
        self.settings = Expander("Settings", ":/images/settings.svg")

        self.setWindowTitle(QCoreApplication.applicationName() + " " +
                            QCoreApplication.applicationVersion())
        vbox = QVBoxLayout()
        vbox.addWidget(self.content)
        vbox.addWidget(self.images)
        vbox.addWidget(self.settings)
        vbox.addStretch()

        self.content_list = QListWidget()
        self.content_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        content_box = QVBoxLayout()
        content_box.addWidget(self.content_list)
        self.item_edit = QLineEdit()
        self.item_edit.setMaximumHeight(0)
        self.item_edit.editingFinished.connect(self.editItemFinished)
        self.item_anim = QPropertyAnimation(self.item_edit,
                                            "maximumHeight".encode("utf-8"))
        content_box.addWidget(self.item_edit)
        button_layout = QHBoxLayout()
        plus_button = FlatButton(":/images/plus.svg")
        self.edit_button = FlatButton(":/images/edit.svg")
        self.trash_button = FlatButton(":/images/trash.svg")
        self.up_button = FlatButton(":/images/up.svg")
        self.down_button = FlatButton(":/images/down.svg")
        self.trash_button.enabled = False
        self.up_button.enabled = False
        self.down_button.enabled = False
        button_layout.addWidget(plus_button)
        button_layout.addWidget(self.up_button)
        button_layout.addWidget(self.down_button)
        button_layout.addWidget(self.edit_button)
        button_layout.addWidget(self.trash_button)
        content_box.addLayout(button_layout)
        self.content.addLayout(content_box)
        plus_button.clicked.connect(self.addPart)
        self.trash_button.clicked.connect(self.dropPart)
        self.up_button.clicked.connect(self.partUp)
        self.down_button.clicked.connect(self.partDown)
        self.edit_button.clicked.connect(self.editPart)

        self.image_list = QListWidget()
        self.image_list.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        image_box = QVBoxLayout()
        image_box.addWidget(self.image_list)
        image_button_layout = QHBoxLayout()
        image_plus_button = FlatButton(":/images/plus.svg")
        self.image_trash_button = FlatButton(":/images/trash.svg")
        self.image_trash_button.enabled = False
        image_button_layout.addWidget(image_plus_button)
        image_button_layout.addWidget(self.image_trash_button)
        image_box.addLayout(image_button_layout)
        self.images.addLayout(image_box)
        image_plus_button.clicked.connect(self.addImage)
        self.image_trash_button.clicked.connect(self.dropImage)

        scroll_content = QWidget()
        scroll_content.setLayout(vbox)
        scroll = QScrollArea()
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll.setWidget(scroll_content)
        scroll.setWidgetResizable(True)
        scroll.setMaximumWidth(200)
        scroll.setMinimumWidth(200)

        self.navigationdock = QDockWidget("Navigation", self)
        self.navigationdock.setAllowedAreas(Qt.LeftDockWidgetArea
                                            | Qt.RightDockWidgetArea)
        self.navigationdock.setWidget(scroll)
        self.navigationdock.setObjectName("Navigation")
        self.addDockWidget(Qt.LeftDockWidgetArea, self.navigationdock)

        self.splitter = QSplitter()
        self.text_edit = MarkdownEdit()
        self.text_edit.setFont(QFont("Courier", 11))
        self.preview = QWebEngineView()
        self.preview.setMinimumWidth(300)
        self.setWindowTitle(QCoreApplication.applicationName())

        self.splitter.addWidget(self.text_edit)
        self.splitter.addWidget(self.preview)
        self.setCentralWidget(self.splitter)

        self.content.expanded.connect(self.contentExpanded)
        self.images.expanded.connect(self.imagesExpanded)
        self.settings.expanded.connect(self.settingsExpanded)
        self.settings.clicked.connect(self.openSettings)
        self.content_list.currentItemChanged.connect(self.partSelectionChanged)
        self.image_list.currentItemChanged.connect(self.imageSelectionChanged)
        self.image_list.itemDoubleClicked.connect(self.insertImage)

        self.text_edit.undoAvailable.connect(self.undoAvailable)
        self.text_edit.redoAvailable.connect(self.redoAvailable)
        self.text_edit.copyAvailable.connect(self.copyAvailable)

        QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged)
コード例 #60
0
    def __init__(self, parent=None):
        super().__init__(parent)
        NotificationCenter.subscribe(NotificationName.update, self.setLyric)

        self.offset = 0
        self.setWindowTitle('Lyric')
        self.setWindowOpacity(0.5)
        self.setWindowFlags(PyQt5.QtCore.Qt.CustomizeWindowHint
                            | PyQt5.QtCore.Qt.WindowStaysOnTopHint)
        self.main_layout = QGridLayout()

        self.scrollArea = QScrollArea()
        self.scrollArea.setGeometry(QRect(10, 10, 201, 121))
        self.scrollArea.setWidgetResizable(True)

        self.sec_layout = QGridLayout()
        self.fontsize_label = QLabel()
        self.fontsize_label.setText('Font Size')
        self.sec_layout.addWidget(self.fontsize_label, 0, 0, 1, 1)

        self.fontsize_minus_button = QPushButton('-')
        self.fontsize_minus_button.clicked.connect(self.minus)
        self.sec_layout.addWidget(self.fontsize_minus_button, 0, 1, 1, 1)

        self.fontsize_plus_button = QPushButton('+')
        self.fontsize_plus_button.clicked.connect(self.plus)
        self.sec_layout.addWidget(self.fontsize_plus_button, 0, 2, 1, 1)

        self.transparent_label = QLabel()
        self.transparent_label.setText('Transparency')
        self.sec_layout.addWidget(self.transparent_label, 0, 5, 1, 1)

        self.transparent_slider = QSlider(PyQt5.QtCore.Qt.Horizontal)
        self.transparent_slider.setRange(0, 100)
        self.transparent_slider.setValue(50)
        self.transparent_slider.valueChanged[int].connect(
            self.transparentSlideValueChanged)
        self.sec_layout.addWidget(self.transparent_slider, 0, 6, 1, 1)

        self.main_layout.addLayout(self.sec_layout, 1, 0, 1, 1)

        self.lyric_view = QLabel()
        self.fontsize = 20
        self.lyric_view.setStyleSheet("font: %dpt Consolas" % (self.fontsize))
        self.lyric_view.setAlignment(PyQt5.QtCore.Qt.AlignCenter)
        self.lyric_view.setText('')

        self.scrollArea.setWidget(self.lyric_view)

        self.main_layout.addWidget(self.scrollArea, 0, 0, 1, 9)

        self.thd_layout = QGridLayout()
        self.artist_label = QLabel('Artist : ')
        self.thd_layout.addWidget(self.artist_label, 0, 0, 1, 1)
        self.artist_input = QLineEdit()
        self.thd_layout.addWidget(self.artist_input, 0, 1, 1, 1)
        self.title_label = QLabel('Title : ')
        self.thd_layout.addWidget(self.title_label, 0, 2, 1, 1)
        self.title_input = QLineEdit()
        self.thd_layout.addWidget(self.title_input, 0, 3, 1, 1)
        self.search_button = QPushButton('Search')
        self.search_button.clicked.connect(self.searchLyric)
        self.thd_layout.addWidget(self.search_button, 0, 4, 1, 1)
        self.main_layout.addLayout(self.thd_layout, 2, 0, 1, 1)

        self.setLayout(self.main_layout)