Example #1
1
    def layoutWidgets(self):
        formLayout = QGridLayout()
        formLayout.setSpacing(20)
        formLayout.setColumnStretch(0, 5)
        formLayout.setColumnStretch(1, 2)
        formLayout.setColumnStretch(2, 2)
        formLayout.setColumnStretch(4, 5)
        formLayout.setRowStretch(0, 1)
        
        formLayout.addWidget(self.title, 1, 1, 1, 2)
        formLayout.setRowMinimumHeight(2, 50)
        formLayout.addWidget(self.subtitle, 3, 1, 1, 2)
        formLayout.addWidget(self.idLabel, 4, 1)
        formLayout.addWidget(self.idLineEdit, 4, 2)
        formLayout.addWidget(self.ageLabel, 5, 1)
        formLayout.addWidget(self.ageSpinBox, 5, 2)
        formLayout.addWidget(self.genderLabel, 6, 1)
        formLayout.addLayout(self.genderLayout, 6, 2)
        formLayout.addWidget(self.fieldLabel, 7, 1)
        formLayout.addWidget(self.fieldComboBox, 7, 2)
        formLayout.setRowMinimumHeight(8, 30)
        # formLayout.addWidget(self.next_button, 9, 2)
        formLayout.setRowStretch(10, 1)

        self.setLayout(formLayout)
Example #2
0
    def __init__(self, parent=None):
        """asdf."""
        super(Form, self).__init__(parent)

        # Componentes
        self.name_label = QLabel("Nombre:")
        self.name_line = QLineEdit()
        self.submit_button = QPushButton("Aceptar")

        # Layout vertical
        button_layout_1 = QVBoxLayout()
        button_layout_1.addWidget(self.name_label)
        button_layout_1.addWidget(self.name_line)
        button_layout_1.addWidget(self.submit_button)

        # Layout Principal
        main_layout = QGridLayout()
        main_layout.addLayout(button_layout_1, 0, 1)

        # Propiedades de ventana inicial
        self.setLayout(main_layout)
        self.setWindowTitle("Hola Qt5")

        # Eventos
        self.submit_button.clicked.connect(self.submit_line)
Example #3
0
    def __init__(self, parent=None):
        super(TZprompt, self).__init__(parent)

        #self.idDates = QCheckBox("Import ID and created/modified dates")

        promptLabel = QLabel("Time Zone in which the Tellico data was entered:")

        self.zoneName = QComboBox(self)
        current = -1
        self.suppliedTZ = 'America/Chicago'
        for i, zone in enumerate (pytz.common_timezones):
            self.zoneName.addItem(zone, i)
            if self.suppliedTZ == zone:
                current = i
        self.zoneName.setCurrentIndex(current)

        self.submitButton = QPushButton("Submit")
        self.submitButton.isDefault()


        buttonLayout1 = QVBoxLayout()
        #buttonLayout1.addWidget(self.idDates)
        buttonLayout1.addWidget(promptLabel)
        buttonLayout1.addWidget(self.zoneName)
        buttonLayout1.addWidget(self.submitButton)

        self.submitButton.clicked.connect(self.TZsubmitted)

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

        self.setLayout(mainLayout)
        self.setWindowTitle("Time Zone")
Example #4
0
    def __initWidgets(self):
        minimalSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        # List of subtitles
        subListDelegate = SubListItemDelegate()
        self._model = QStandardItemModel(0, 3, self)
        self._model.setHorizontalHeaderLabels([_("Begin"), _("End"), _("Subtitle")])
        self._subList = QTableView(self)
        self._subList.setModel(self._model)
        self._subList.setItemDelegateForColumn(0, subListDelegate)
        self._subList.setItemDelegateForColumn(1, subListDelegate)
        self._subList.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)

        self._searchBar = SearchBar(self)
        self._searchBar.hide()

        # Top toolbar
        toolbar = QHBoxLayout()
        toolbar.setAlignment(Qt.AlignLeft)
        #toolbar.addWidget(someWidget....)
        toolbar.addStretch(1)

        # Main layout
        grid = QGridLayout()
        grid.setSpacing(10)
        grid.setContentsMargins(0, 3, 0, 0)
        grid.addLayout(toolbar, 0, 0, 1, 1) # stretch to the right
        grid.addWidget(self._subList, 1, 0)
        grid.addWidget(self._searchBar, 2, 0)
        self.setLayout(grid)
Example #5
0
File: qt.py Project: asfin/electrum
    def create_encrypt_tab(self):
        w = QWidget()

        layout = QGridLayout(w)

        message_e = QTextEdit()
        layout.addWidget(QLabel(_('Message')), 1, 0)
        layout.addWidget(message_e, 1, 1)
        layout.setRowStretch(2, 2)

        recipient_e = QTextEdit()
        recipient_e.setPlaceholderText('''-----BEGIN PGP PUBLIC KEY BLOCK-----''')
        recipient_e.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont))
        layout.addWidget(QLabel(_('Recipient key')), 2, 0)
        layout.addWidget(recipient_e, 2, 1)

        encrypted_e = QTextEdit()
        encrypted_e.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont))
        layout.addWidget(QLabel(_('Encrypted')), 3, 0)
        layout.addWidget(encrypted_e, 3, 1)
        layout.setRowStretch(3, 1)

        hbox = QHBoxLayout()
        b = QPushButton(_('Encrypt'))
        b.clicked.connect(lambda: self.do_encrypt(message_e, recipient_e, encrypted_e))
        hbox.addWidget(b)

        b = QPushButton(_('Decrypt'))
        b.clicked.connect(lambda: self.do_decrypt(encrypted_e, message_e))
        hbox.addWidget(b)

        layout.addLayout(hbox, 4, 1)
        return w
Example #6
0
File: qt.py Project: asfin/electrum
    def create_signature_tab(self):
        w = QWidget()

        layout = QGridLayout(w)

        message_e = QTextEdit()
        layout.addWidget(QLabel(_('Message')), 1, 0)
        layout.addWidget(message_e, 1, 1)
        layout.setRowStretch(2, 2)

        encrypted_e = QTextEdit()
        encrypted_e.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont))
        layout.addWidget(QLabel(_('Signed')), 2, 0)
        layout.addWidget(encrypted_e, 2, 1)
        layout.setRowStretch(2, 2)

        hbox = QHBoxLayout()
        b = QPushButton(_('Sign'))
        b.clicked.connect(lambda: self.do_sign(message_e, encrypted_e))
        hbox.addWidget(b)

        b = QPushButton(_('Verify'))
        b.clicked.connect(lambda: self.do_verify(encrypted_e, message_e))
        hbox.addWidget(b)

        layout.addLayout(hbox, 3, 1)
        return w
Example #7
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")
Example #8
0
File: gui.py Project: kharyuk/astro
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__()
        widget = QWidget(self)
        self.setCentralWidget(widget)
        self.layout = QGridLayout(widget)
        self.layout.setSpacing(10)
        
        self.flist = self.load_flist()
        self.code_int = 0
        self.code = self.flist[self.code_int]['code']
        
        self.dictpar = self.load_parameter()
        tmp_data = eval(self.dictpar[self.code]['vphi'])
        shape = [2, len(tmp_data)]
        
        self.settings_dirname = './'#CATLISTDIR
        self.settings_filename = USERPARFILE
        self.day_start = datetime.datetime.today()
        self.day_end = self.day_start + datetime.timedelta(days=10)
        self.mpf = 12
        
        chooseCatWgt = ChooseCatalogueList(self)
        self.layout.addWidget(chooseCatWgt, 0, 0, 1, 1)
        
        datein = DateInputW(self)
        self.layout.addWidget(datein, 1, 0, 1, 2)
        self.layout.addLayout(datein.layout, 1, 0, 1, 2)
        
        parameterWgt = tableVmag(self, tmp_data, shape)
        self.layout.addWidget(parameterWgt, 0, 1, 1, 1)
        #self.layout.addLayout(parameterWgt.layout, 0, 1, 1, 1)
        
        mainWork = MainProcess(self)
        self.layout.addWidget(mainWork, 2, 0, 1, 2)
        
        self.setGeometry(100, 100, 720, 480)
        self.setFixedSize(720, 480)
        self.setWindowTitle(u'Соединения Солнца и неподвижных объектов небесной сферы: расчёт')
        self.show()

    def load_flist(self):
        flist = []
        with open(CATLISTDIR+CATLISTFILE, 'rb') as csvfile:
            fid = csv.DictReader(csvfile, delimiter=',', quotechar="'")
            for row in fid:
                flist.append(row)
        return flist
        
    def load_parameter(self):
        exists = os.path.isfile(USERPARFILE)
        if not exists:
            shutil.copy(CATLISTDIR+DFLTPARFILE, USERPARFILE)
        dictpar = {}
        with open(USERPARFILE, 'rb') as csvfile:
            fid = csv.DictReader(csvfile, delimiter=',', quotechar="'")
            for row in fid:
                dictpar[row['code']] = removekey(row, 'code')
        return dictpar
Example #9
0
    def init_widgets(self):

        layout = QGridLayout()

        # String -> Float
        catScore = float(self.score[0])*100
        dogScore = float(self.score[1])*100

        # Result Labels
        resultLayout = QHBoxLayout()
        resultLabel1 = QLabel('この画像は')
        resultLabel1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        if( catScore > dogScore ):
            resultLabel2 = QLabel('猫')
        else:
            resultLabel2 = QLabel('犬')
        resultLabel2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        font = resultLabel2.font()
        font.setPointSize(24)
        resultLabel2.setFont(font)
        resultLabel3 = QLabel('ですね?')
        resultLabel3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        resultLayout.addWidget(resultLabel1)
        resultLayout.addWidget(resultLabel2)
        resultLayout.addWidget(resultLabel3)
        resultLayout.addStretch(10)
        layout.addLayout(resultLayout, 0, 0)

        # Tipycal Image Label
        tipImgLabel = QLabel()
        if( catScore > dogScore ):
            pixmap = QPixmap(CAT_IMAGE)
        else:
            pixmap = QPixmap(DOG_IMAGE)
        pixmap = pixmap.scaled(IMAGE_WIDTH, IMAGE_HEIGHT, QtCore.Qt.KeepAspectRatio)
        tipImgLabel.setPixmap(pixmap)
        layout.addWidget(tipImgLabel, 1, 0)

        # Score Labels
        scoreLayout = QVBoxLayout()
        dogScoreLabel = QLabel('cat={0:.1f}%'.format(catScore))
        catScoreLabel = QLabel('dog={0:.1f}%'.format(dogScore))
        dogScoreLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        catScoreLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        scoreLayout.addWidget(dogScoreLabel)
        scoreLayout.addWidget(catScoreLabel)
        scoreLayout.addStretch(10)
        layout.addLayout(scoreLayout, 1, 1, 1, 1)

        # Close Button
        closeButton = QPushButton('閉じる')
        closeButton.clicked.connect(self.close)
        layout.addWidget(closeButton, 2, 1)

        # Title
        self.setWindowTitle('画像識別')

        self.setLayout(layout)
Example #10
0
    def createTextFormatsGroupBox(self):
        self.textFormatsGroupBox = QGroupBox("Text Formats")

        self.weekdayColorCombo = self.createColorComboBox()
        self.weekdayColorCombo.setCurrentIndex(
                self.weekdayColorCombo.findText("Black"))

        self.weekdayColorLabel = QLabel("&Weekday color:")
        self.weekdayColorLabel.setBuddy(self.weekdayColorCombo)

        self.weekendColorCombo = self.createColorComboBox()
        self.weekendColorCombo.setCurrentIndex(
                self.weekendColorCombo.findText("Red"))

        self.weekendColorLabel = QLabel("Week&end color:")
        self.weekendColorLabel.setBuddy(self.weekendColorCombo)

        self.headerTextFormatCombo = QComboBox()
        self.headerTextFormatCombo.addItem("Bold")
        self.headerTextFormatCombo.addItem("Italic")
        self.headerTextFormatCombo.addItem("Plain")

        self.headerTextFormatLabel = QLabel("&Header text:")
        self.headerTextFormatLabel.setBuddy(self.headerTextFormatCombo)

        self.firstFridayCheckBox = QCheckBox("&First Friday in blue")

        self.mayFirstCheckBox = QCheckBox("May &1 in red")

        self.weekdayColorCombo.currentIndexChanged.connect(
                self.weekdayFormatChanged)
        self.weekendColorCombo.currentIndexChanged.connect(
                self.weekendFormatChanged)
        self.headerTextFormatCombo.currentIndexChanged.connect(
                self.reformatHeaders)
        self.firstFridayCheckBox.toggled.connect(self.reformatCalendarPage)
        self.mayFirstCheckBox.toggled.connect(self.reformatCalendarPage)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.firstFridayCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.mayFirstCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.weekdayColorLabel, 0, 0)
        outerLayout.addWidget(self.weekdayColorCombo, 0, 1)
        outerLayout.addWidget(self.weekendColorLabel, 1, 0)
        outerLayout.addWidget(self.weekendColorCombo, 1, 1)
        outerLayout.addWidget(self.headerTextFormatLabel, 2, 0)
        outerLayout.addWidget(self.headerTextFormatCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        self.textFormatsGroupBox.setLayout(outerLayout)

        self.weekdayFormatChanged()
        self.weekendFormatChanged()

        self.reformatHeaders()
        self.reformatCalendarPage()
Example #11
0
    def interfejs(self):

        # etykiety
        etykieta1 = QLabel("Liczba 1:", self)
        etykieta2 = QLabel("Liczba 2:", self)
        etykieta3 = QLabel("Wynik:", self)

        # przypisanie widgetów do układu tabelarycznego
        ukladT = QGridLayout()
        ukladT.addWidget(etykieta1, 0, 0)
        ukladT.addWidget(etykieta2, 0, 1)
        ukladT.addWidget(etykieta3, 0, 2)

        # 1-liniowe pola edycyjne
        self.liczba1Edt = QLineEdit()
        self.liczba2Edt = QLineEdit()
        self.wynikEdt = QLineEdit()

        self.wynikEdt.readonly = True
        self.wynikEdt.setToolTip('Wpisz <b>liczby</b> i wybierz działanie...')

        ukladT.addWidget(self.liczba1Edt, 1, 0)
        ukladT.addWidget(self.liczba2Edt, 1, 1)
        ukladT.addWidget(self.wynikEdt, 1, 2)

        # przyciski
        dodajBtn = QPushButton("&Dodaj", self)
        odejmijBtn = QPushButton("&Odejmij", self)
        dzielBtn = QPushButton("&Mnóż", self)
        mnozBtn = QPushButton("D&ziel", self)
        koniecBtn = QPushButton("&Koniec", self)
        koniecBtn.resize(koniecBtn.sizeHint())

        ukladH = QHBoxLayout()
        ukladH.addWidget(dodajBtn)
        ukladH.addWidget(odejmijBtn)
        ukladH.addWidget(dzielBtn)
        ukladH.addWidget(mnozBtn)

        ukladT.addLayout(ukladH, 2, 0, 1, 3)
        ukladT.addWidget(koniecBtn, 3, 0, 1, 3)

        # przypisanie utworzonego układu do okna
        self.setLayout(ukladT)

        koniecBtn.clicked.connect(self.koniec)
        dodajBtn.clicked.connect(self.dzialanie)
        odejmijBtn.clicked.connect(self.dzialanie)
        mnozBtn.clicked.connect(self.dzialanie)
        dzielBtn.clicked.connect(self.dzialanie)

        self.liczba1Edt.setFocus()
        self.setGeometry(20, 20, 300, 100)
        self.setWindowIcon(QIcon('kalkulator.png'))
        self.setWindowTitle("Prosty kalkulator")
        self.show()
Example #12
0
    def __init__(self, parent=None):
        super(FindDialog, self).__init__(parent)

        label = QLabel("Find &what:")
        lineEdit = QLineEdit()
        label.setBuddy(lineEdit)

        caseCheckBox = QCheckBox("Match &case")
        fromStartCheckBox = QCheckBox("Search from &start")
        fromStartCheckBox.setChecked(True)

        findButton = QPushButton("&Find")
        findButton.setDefault(True)

        moreButton = QPushButton("&More")
        moreButton.setCheckable(True)
        moreButton.setAutoDefault(False)

        extension = QWidget()

        wholeWordsCheckBox = QCheckBox("&Whole words")
        backwardCheckBox = QCheckBox("Search &backward")
        searchSelectionCheckBox = QCheckBox("Search se&lection")

        buttonBox = QDialogButtonBox(Qt.Vertical)
        buttonBox.addButton(findButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(moreButton, QDialogButtonBox.ActionRole)

        moreButton.toggled.connect(extension.setVisible)

        extensionLayout = QVBoxLayout()
        extensionLayout.setContentsMargins(0, 0, 0, 0)
        extensionLayout.addWidget(wholeWordsCheckBox)
        extensionLayout.addWidget(backwardCheckBox)
        extensionLayout.addWidget(searchSelectionCheckBox)
        extension.setLayout(extensionLayout)

        topLeftLayout = QHBoxLayout()
        topLeftLayout.addWidget(label)
        topLeftLayout.addWidget(lineEdit)

        leftLayout = QVBoxLayout()
        leftLayout.addLayout(topLeftLayout)
        leftLayout.addWidget(caseCheckBox)
        leftLayout.addWidget(fromStartCheckBox)

        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addLayout(leftLayout, 0, 0)
        mainLayout.addWidget(buttonBox, 0, 1)
        mainLayout.addWidget(extension, 1, 0, 1, 2)
        mainLayout.setRowStretch(2, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Extension")
        extension.hide()
Example #13
0
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        grid = QGridLayout()
        grid.addWidget(self.create_top_group(), 0, 0)
        grid.addLayout(self.create_mid_group(), 1, 0)
        grid.addWidget(self.create_bottom_group(), 2, 0)
        self.setLayout(grid)

        self.setWindowTitle("UJ Editor")
        self.resize(1280, 640)
Example #14
0
    def initUI(self):
        """Draw the UI."""

        QToolTip.setFont(QFont('SansSerif', 12))

        grid = QGridLayout()
        self.setLayout(grid)

        lbl_source = QLabel('Source:', self)
        lbl_source.setAlignment(Qt.AlignCenter)

        lbl_destination = QLabel('Destination:', self)
        lbl_destination.setAlignment(Qt.AlignCenter)

        self.cmb_source = QComboBox(self)
        self.populate_cmb_source()
        self.cmb_source.activated.connect(self.source_activated)
        self.cmb_source.setToolTip("Select either a source USB device "
                                   "or a source 'nb' backup directory")

        self.cmb_destination = QComboBox(self)
        self.populate_cmb_destination()
        self.cmb_destination.activated.connect(self.destination_activated)
        self.cmb_destination.setToolTip('Select a destination USB device')

        self.lbl_status = QLabel('', self)
        self.lbl_status.setAlignment(Qt.AlignLeft)
        self.btn_copy = QPushButton('Copy', self)
#        self.btn_copy.setFixedWidth(80)
        self.btn_copy.setFixedWidth(self.btn_copy.width())
        self.btn_copy.clicked.connect(self.start_copy)
        self.btn_copy.setEnabled(False)

        hbox = QHBoxLayout()
        hbox.addWidget(self.lbl_status, Qt.AlignLeft)
        hbox.addStretch(1)
        hbox.addWidget(self.btn_copy, Qt.AlignRight)
        hbox.maximumSize()

        grid.addWidget(lbl_source, 0, 0, Qt.AlignRight)
        grid.addWidget(self.cmb_source, 0, 1)

        grid.addWidget(lbl_destination, 1, 0, Qt.AlignRight)
        grid.addWidget(self.cmb_destination, 1, 1)

        grid.addLayout(hbox, 2, 1)

        grid.setColumnStretch(0, 0)
        grid.setColumnStretch(1, 1)

        self.setWindowTitle('%s %s' % (ProgName, ProgVersion))
        self.setMinimumWidth(MinimumWidth)
        self.show()
        self.setFixedHeight(self.height())
Example #15
0
    def __init__(self, parent=None):
        super(AddressBook, self).__init__(parent)

        self.contacts = SortedDict()
        self.oldName = ''
        self.oldAddress = ''

        nameLabel = QLabel("Name:")
        self.nameLine = QLineEdit()
        self.nameLine.setReadOnly(True)

        addressLabel = QLabel("Address:")
        self.addressText = QTextEdit()
        self.addressText.setReadOnly(True)

        self.addButton = QPushButton("Add")
        self.addButton.show()
        self.submitButton = QPushButton("Submit")
        self.submitButton.hide()
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.hide()
        self.nextButton = QPushButton("Next")
        self.nextButton.setEnabled(False)
        self.previousButton = QPushButton("Previous")
        self.previousButton.setEnabled(False)

        self.addButton.clicked.connect(self.addContact)
        self.submitButton.clicked.connect(self.submitContact)
        self.cancelButton.clicked.connect(self.cancel)
        self.nextButton.clicked.connect(self.next)
        self.previousButton.clicked.connect(self.previous)

        buttonLayout1 = QVBoxLayout()
        buttonLayout1.addWidget(self.addButton, Qt.AlignTop)
        buttonLayout1.addWidget(self.submitButton)
        buttonLayout1.addWidget(self.cancelButton)
        buttonLayout1.addStretch()

        buttonLayout2 = QHBoxLayout()
        buttonLayout2.addWidget(self.previousButton)
        buttonLayout2.addWidget(self.nextButton)

        mainLayout = QGridLayout()
        mainLayout.addWidget(nameLabel, 0, 0)
        mainLayout.addWidget(self.nameLine, 0, 1)
        mainLayout.addWidget(addressLabel, 1, 0, Qt.AlignTop)
        mainLayout.addWidget(self.addressText, 1, 1)
        mainLayout.addLayout(buttonLayout1, 1, 2)
        mainLayout.addLayout(buttonLayout2, 3, 1)

        self.setLayout(mainLayout)
        self.setWindowTitle("Very Simple Address Book")
Example #16
0
    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)

        # row 0 of grid
        label = QLabel('Name:')
        label.setAlignment(Qt.AlignRight)
        grid.addWidget(label, 0, 0)

        self.qle_name = QLineEdit(self)
        grid.addWidget(self.qle_name, 0, 1)

        label = QLabel('    ')      # add a little spacer
        grid.addWidget(label, 0, 2)

        label = QLabel('Age:')
        label.setAlignment(Qt.AlignRight)
        grid.addWidget(label, 0, 3)

        self.qle_age = QLineEdit(self)
        grid.addWidget(self.qle_age, 0, 4)

        # row 1 of grid
        label = QLabel('Height:')
        label.setAlignment(Qt.AlignRight)
        grid.addWidget(label, 1, 3)

        self.qle_height = QLineEdit(self)
        grid.addWidget(self.qle_height, 1, 4)

        # row 2 - could use some vertical separation - just put empty label
        label = QLabel('')
        grid.addWidget(label, 2, 4)

        # row 3 of grid - a horizontal box containing buttons
        hbox = QHBoxLayout()

        hbox.addStretch(1)

        btn = QPushButton('Load', self)
        btn.clicked.connect(self.loadUser)
        hbox.addWidget(btn)

        btn = QPushButton('Clear', self)
        hbox.addWidget(btn)
        btn.clicked.connect(self.clearFields)

        btn = QPushButton('Save', self)
        hbox.addWidget(btn)
        btn.clicked.connect(self.saveUser)

        grid.addLayout(hbox, 3, 4, 4, 1)
Example #17
0
    def layoutMetronomeWidget(self, layout):
        grid = QGridLayout()
        grid.addWidget(self.metronomeLabel, 0, 0)

        box = QHBoxLayout(spacing=0)
        box.addWidget(self.metronomeNote)
        box.addWidget(self.metronomeEqualSign)
        box.addWidget(self.metronomeValue)
        box.addWidget(self.metronomeTempo)
        grid.addLayout(box, 0, 1)

        grid.addWidget(self.metronomeRound, 1, 1)
        layout.addLayout(grid)
Example #18
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.parent = parent
        self.feuille = parent.feuille
        gbs = QGridLayout()
        gbs.setSpacing(10)

        gbs.addWidget(QLabel("Titre : "), 1, 1)
        self.titre = titre = QLineEdit(self)
        titre.setText(self.feuille.infos("titre"))
        titre.setMinimumWidth(300)
        gbs.addWidget(titre, 1, 2)

        gbs.addWidget(QLabel("Auteur : "), 2, 1)
        self.auteur = auteur = QLineEdit(self)
        auteur.setText(self.feuille.infos("auteur"))
        auteur.setMinimumWidth(300)
        gbs.addWidget(auteur, 2, 2)

        gbs.addWidget(QLabel("Version : "), 3, 1)
        self.version = version = QLineEdit(self)
        version.setText(self.feuille.infos("version"))
        version.setMinimumWidth(300)
        gbs.addWidget(version, 3, 2)

        gbs.addWidget(QLabel("Resumé : "), 4, 1)
        self.resume = resume = QTextEdit(self)
        resume.setPlainText(self.feuille.infos("resume"))
        resume.setMinimumSize(300, 50)
        gbs.addWidget(resume, 4, 2)

        gbs.addWidget(QLabel("Notes : "), 5, 1)
        self.notes = notes = QTextEdit(self)
        notes.setPlainText(self.feuille.infos("notes"))
        notes.setMinimumSize(300, 100)
        gbs.addWidget(notes, 5, 2)

        boutons = QGridLayout()
        boutons.setSpacing(10)
        ok = QPushButton('OK', clicked=self.ok)
        appliquer = QPushButton("Appliquer", clicked=self.appliquer)
        effacer = QPushButton("Effacer", clicked=self.effacer)
        annuler = QPushButton("Annuler", clicked=self.parent.parent.close)

        boutons.addWidget(ok, 1, 0)
        boutons.addWidget(appliquer, 1, 1)
        boutons.addWidget(effacer, 1, 2)
        boutons.addWidget(annuler, 1, 3)
        gbs.addLayout(boutons, 6, 2)

        self.setLayout(gbs)
Example #19
0
    def __init__(self, parent=None):
        super(WidgetGallery, self).__init__(parent)

        self.originalPalette = QApplication.palette()

        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())

        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)

        self.useStylePaletteCheckBox = QCheckBox("&Use style's standard palette")
        self.useStylePaletteCheckBox.setChecked(True)

        disableWidgetsCheckBox = QCheckBox("&Disable widgets")

        self.createTopLeftGroupBox()
        self.createTopRightGroupBox()
        self.createBottomLeftTabWidget()
        self.createBottomRightGroupBox()
        self.createProgressBar()

        styleComboBox.activated[str].connect(self.changeStyle)
        self.useStylePaletteCheckBox.toggled.connect(self.changePalette)
        disableWidgetsCheckBox.toggled.connect(self.topLeftGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(self.topRightGroupBox.setDisabled)
        disableWidgetsCheckBox.toggled.connect(self.bottomLeftTabWidget.setDisabled)
        disableWidgetsCheckBox.toggled.connect(self.bottomRightGroupBox.setDisabled)

        topLayout = QHBoxLayout()
        topLayout.addWidget(styleLabel)
        topLayout.addWidget(styleComboBox)
        topLayout.addStretch(1)
        topLayout.addWidget(self.useStylePaletteCheckBox)
        topLayout.addWidget(disableWidgetsCheckBox)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.topLeftGroupBox, 1, 0)
        mainLayout.addWidget(self.topRightGroupBox, 1, 1)
        mainLayout.addWidget(self.bottomLeftTabWidget, 2, 0)
        mainLayout.addWidget(self.bottomRightGroupBox, 2, 1)
        mainLayout.addWidget(self.progressBar, 3, 0, 1, 2)
        mainLayout.setRowStretch(1, 1)
        mainLayout.setRowStretch(2, 1)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Styles")
        self.changeStyle('Windows')
Example #20
0
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # Initiating UI Items
        self.pagesLabel = QLabel("Pages:")
        self.pageFirst = QLineEdit()
        self.pageFirst.setPlaceholderText("First Page #")
        self.pageLast = QLineEdit()
        self.pageLast.setPlaceholderText("Last Page #")
        self.execButton = QPushButton("&Execute")
        self.execButton.setToolTip("Execute the PDF split")

        self.iPathLabel = QLabel("Input File:")
        self.iPathText = QLineEdit()
        self.inputButton = QPushButton("&Load")
        self.inputButton.setToolTip("Load a PDF file")

        self.oPathLabel = QLabel("Output File:")
        self.oPathText = QLineEdit()
        self.outputButton = QPushButton("&Save")
        self.outputButton.setToolTip("Save as a PDF file")


        # Positioning GUI by grid format
        secLayout = QGridLayout()
        secLayout.addWidget(self.pageFirst, 0, 0)
        secLayout.addWidget(self.pageLast, 0, 1)

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.pagesLabel, 0, 0)
        mainLayout.addLayout(secLayout, 0, 1)
        mainLayout.addWidget(self.execButton, 0, 2)
        mainLayout.addWidget(self.iPathLabel, 1, 0)
        mainLayout.addWidget(self.iPathText, 1, 1)
        mainLayout.addWidget(self.inputButton, 1, 2)
        mainLayout.addWidget(self.oPathLabel, 2, 0)
        mainLayout.addWidget(self.oPathText, 2, 1)
        mainLayout.addWidget(self.outputButton, 2, 2)


        # Button Events
        self.inputButton.clicked.connect(self.loadFromFile)
        self.outputButton.clicked.connect(self.saveToFile)
        self.execButton.clicked.connect(self.runSplit)

        self.setLayout(mainLayout)
        self.setWindowTitle("PyDF Splitter")
        self.resize(600, 100)
Example #21
0
    def __initUI__(self):
        """Initialize the GUI."""
        self.manager_updates = None

        # ---- AboutTextBox

        self.AboutTextBox = QTextBrowser()
        self.AboutTextBox.installEventFilter(self)
        self.AboutTextBox.setReadOnly(True)
        self.AboutTextBox.setFixedWidth(850)
        self.AboutTextBox.setFrameStyle(0)
        self.AboutTextBox.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.AboutTextBox.setOpenExternalLinks(True)

        self.AboutTextBox.setStyleSheet('QTextEdit {background-color:"white"}')
        self.AboutTextBox.document().setDocumentMargin(0)
        self.set_html_in_AboutTextBox()

        # ---- toolbar

        self.ok_btn = QPushButton('OK')
        self.ok_btn.clicked.connect(self.close)

        self.btn_check_updates = QPushButton(' Check for Updates ')
        self.btn_check_updates.clicked.connect(
                self._btn_check_updates_isclicked)

        toolbar = QGridLayout()
        toolbar.addWidget(self.btn_check_updates, 0, 1)
        toolbar.addWidget(self.ok_btn, 0, 2)
        toolbar.setContentsMargins(0, 0, 0, 0)
        toolbar.setColumnStretch(0, 100)

        # ---- Main Grid

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(self.AboutTextBox, 0, 1)
        grid.addLayout(toolbar, 1, 1)

        grid.setColumnStretch(1, 500)
        grid.setContentsMargins(10, 10, 10, 10)

        self.setLayout(grid)
        self.ok_btn.setFocus()
Example #22
0
	def __init__(self, widget, title = str(), accept = None, reject = None, results = list()):
		super().__init__()
		self.result = None
		lay = QGridLayout(self)
		self.btn_lay = QGridLayout()
		self.accept_btn = QPushButton('Accept')
		self.reject_btn = QPushButton('Reject')
		if accept:
			self.setAcceptMethod(accept)
		if reject:
			if isinstance(reject, Callable):
				self.setRejectMethod(reject)
			else:
				self.reject_btn.clicked.connect(self.reject)
				self.btn_lay.addWidget(self.reject_btn, 0,1)
		lay.addWidget(widget, 0, 0)
		lay.addLayout(self.btn_lay, 1,0,Qt.AlignRight)
		self.setWindowTitle(title)
Example #23
0
 def enemyClick(self, enemy):
     # Opens an info screen on the enemy
     if self.parent.gameover == False and enemy.isDead == False:
     
         if self.parent.isTowerSelected == False:
             # self.statusBarMessage("Enemy clicked")
             self.enemyPopUp = QFrame()
             self.enemyPopUp.setGeometry(500, 500, 100, 100)
         
             grid = QGridLayout()
             self.enemyPopUp.setLayout(grid)
         
             enemyStats = QLabel("Enemy Stats")
             name = QLabel("Name: " + str(enemy.name))
             speed = QLabel("Speed: " + str(enemy.speed))
             health = QLabel("Health: {:.0f}".format(enemy.health))
             pixmap = QLabel()
             pixmap.setPixmap(enemy.picture)
         
             vbox = QVBoxLayout()
             vbox.addWidget(enemyStats)
             vbox.addWidget(name)
             vbox.addWidget(speed)
             vbox.addWidget(health)
 
             grid.addLayout(vbox, 0, 0)
         
             vbox2 = QVBoxLayout()
             vbox2.addWidget(pixmap)
             vbox2.addStretch()
             
             doneButton = QPushButton("Done")
             vbox2.addWidget(doneButton)
             grid.addLayout(vbox2, 0, 1)
             
             location = QPoint(QCursor.pos())
             self.enemyPopUp.move(location.x() - 100, location.y())
             self.enemyPopUp.show()
             doneButton.clicked.connect(self.enemyPopUp.hide)
     
     elif self.parent.gameover == True:
         self.statusBarMessage("The game has ended. Stop doing stuff.")
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
 
        nameLabel = QLabel("Name:")
        self.nameLine = QLineEdit()
        self.submitButton = QPushButton("&amp;Submit")
 
        buttonLayout1 = QVBoxLayout()
        buttonLayout1.addWidget(nameLabel)
        buttonLayout1.addWidget(self.nameLine)
        buttonLayout1.addWidget(self.submitButton)
 
        self.submitButton.clicked.connect(self.submitContact)
 
        mainLayout = QGridLayout()
        # mainLayout.addWidget(nameLabel, 0, 0)
        mainLayout.addLayout(buttonLayout1, 0, 1)
 
        self.setLayout(mainLayout)
        self.setWindowTitle("Hello Qt")
Example #25
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.contacts = {}
        self.oldName = ''
        self.oldAddress = ''

        nameLabel = QLabel("Name:")
        self.nameLine = QLineEdit()
        self.nameLine.setReadOnly(True)

        addressLabel = QLabel("Address:")
        self.addressText = QTextEdit()
        self.addressText.setReadOnly(True)

        self.addButton = QPushButton("&Add")
        self.addButton.show()
        self.submitButton = QPushButton("&Submit")
        self.submitButton.hide()
        self.cancelButton = QPushButton("&Cancel")
        self.cancelButton.hide()

        self.addButton.clicked.connect(self.addContact)
        self.submitButton.clicked.connect(self.submitContact)
        self.cancelButton.clicked.connect(self.cancel)

        leftLayout = QVBoxLayout()
        leftLayout.addWidget(self.addButton, Qt.AlignTop)
        leftLayout.addWidget(self.submitButton)
        leftLayout.addWidget(self.cancelButton)
        leftLayout.addStretch()

        mainLayout = QGridLayout()
        mainLayout.addWidget(nameLabel, 0, 0)
        mainLayout.addWidget(self.nameLine, 0, 1)
        mainLayout.addWidget(addressLabel, 1, 0, Qt.AlignTop)
        mainLayout.addWidget(self.addressText, 1, 1)
        mainLayout.addLayout(leftLayout, 1, 2)

        self.setLayout(mainLayout)
        self.setWindowTitle("Simple Address Book")
    def __init__(self, parent=None):

        super(Window, self).__init__(parent)

        inputButton = self.createButton("&Select input folder", self.browseForInput)
        inputLabel = QLabel("Input path: ")
        self.inputPath = QLabel(QDir.currentPath())
        self.inputStats = QLabel("")
        self.inputFiles = []
        self.sampleImage = SampleImageWidget(self)

        outputButton = self.createButton("&Select output folder", self.browseForOutput)
        outputLabel = QLabel("Output path:")
        self.outputPath = QLabel(QDir.currentPath())

        startButton = self.createButton("&Start processing", self.process)
        quitButton = self.createButton("&Exit", self.quit)

        mainLayout = QGridLayout()

        mainLayout.addWidget(inputButton, 0, 0)
        mainLayout.addWidget(inputLabel, 0, 1)
        mainLayout.addWidget(self.inputPath, 0, 2)
        mainLayout.addWidget(self.inputStats, 1, 0)
        mainLayout.addWidget(self.sampleImage, 1, 1)

        mainLayout.addWidget(outputButton, 2, 0)
        mainLayout.addWidget(outputLabel, 2, 1)
        mainLayout.addWidget(self.outputPath, 2, 2)

        buttonsLayout = QHBoxLayout()
        buttonsLayout.addStretch()
        buttonsLayout.addWidget(startButton)
        buttonsLayout.addWidget(quitButton)

        mainLayout.addLayout(buttonsLayout, 3, 0)

        self.setLayout(mainLayout)

        self.setWindowTitle("Find Files")
        self.resize(700, 300)
    def setUpDialogFooter(self):
        footerLayout = QGridLayout()
        footerLayout.setColumnStretch(0, 4)

        footerLayout.addWidget(QLabel("Torrent priority"), 0, 1)
        self.priorityComboBox = QComboBox(self)
        self.priorityComboBox.addItems(["High", "Normal", "Low"])
        self.priorityComboBox.setCurrentIndex(1)
        footerLayout.addWidget(self.priorityComboBox, 0, 2)

        secondRowLayout = QHBoxLayout()

        OKButton = QPushButton("Open", self)
        OKButton.setFocus()
        OKButton.clicked.connect(self.accept)
        cancelButton = QPushButton("Cancel", self)
        cancelButton.clicked.connect(self.reject)
        secondRowLayout.addWidget(OKButton)
        secondRowLayout.addWidget(cancelButton)
        footerLayout.addLayout(secondRowLayout, 1, 2)

        self.layout.addLayout(footerLayout)
Example #28
0
def add_to_grid(*items):
    """Add items to a QGrid layout easily.

    Keyword arguments:
    *items -- list with lists of items to be added.
              items in the same list will be added to the same line of grid.
    """
    layout = QGridLayout()
    # for now it adds only 1 item per cell.
    for x, _list in enumerate(items):
        for y, item in enumerate(_list):
            if isinstance(item, QWidget):
                layout.addWidget(item, x, y)
            elif isinstance(item, QLayout):
                layout.addLayout(item, x, y)
            elif isinstance(item, QSpacerItem):
                layout.addItem(item, x, y)
            elif item is None:
                pass
            else:
                raise TypeError("Argument of wrong type!")
    return layout
Example #29
0
    def createIconSizeGroupBox(self):
        self.iconSizeGroupBox = QGroupBox("Icon Size")

        self.smallRadioButton = QRadioButton()
        self.largeRadioButton = QRadioButton()
        self.toolBarRadioButton = QRadioButton()
        self.listViewRadioButton = QRadioButton()
        self.iconViewRadioButton = QRadioButton()
        self.tabBarRadioButton = QRadioButton()
        self.otherRadioButton = QRadioButton("Other:")

        self.otherSpinBox = IconSizeSpinBox()
        self.otherSpinBox.setRange(8, 128)
        self.otherSpinBox.setValue(64)

        self.smallRadioButton.toggled.connect(self.changeSize)
        self.largeRadioButton.toggled.connect(self.changeSize)
        self.toolBarRadioButton.toggled.connect(self.changeSize)
        self.listViewRadioButton.toggled.connect(self.changeSize)
        self.iconViewRadioButton.toggled.connect(self.changeSize)
        self.tabBarRadioButton.toggled.connect(self.changeSize)
        self.otherRadioButton.toggled.connect(self.changeSize)
        self.otherSpinBox.valueChanged.connect(self.changeSize)

        otherSizeLayout = QHBoxLayout()
        otherSizeLayout.addWidget(self.otherRadioButton)
        otherSizeLayout.addWidget(self.otherSpinBox)
        otherSizeLayout.addStretch()

        layout = QGridLayout()
        layout.addWidget(self.smallRadioButton, 0, 0)
        layout.addWidget(self.largeRadioButton, 1, 0)
        layout.addWidget(self.toolBarRadioButton, 2, 0)
        layout.addWidget(self.listViewRadioButton, 0, 1)
        layout.addWidget(self.iconViewRadioButton, 1, 1)
        layout.addWidget(self.tabBarRadioButton, 2, 1)
        layout.addLayout(otherSizeLayout, 3, 0, 1, 2)
        layout.setRowStretch(4, 1)
        self.iconSizeGroupBox.setLayout(layout)
    def init_ui(self):
        grid = QGridLayout()
        grid.setSpacing(10)
        hbox_button = QHBoxLayout()
        list_edits = []
        list_labels = []

        position_label = [(i, 0) for i in range(len(self.column))]
        position_edit = [(i, 1) for i in range(len(self.column))]

        for label, pos in zip(self.column, position_label):
            lb = QLabel(label)
            list_labels.append(lb)
            grid.addWidget(lb, *pos)

        for pos in position_edit:
            qle = QLineEdit(self)
            list_edits.append(qle)
            qle.textChanged[str].connect(self.on_changed)
            grid.addWidget(qle, *pos)

        self.dic_edit_label = \
            {x[0]: x[1] for x in zip(list_edits, list_labels)}

        ok_button = QPushButton('Ok', self)
        ok_button.clicked.connect(self.is_ok)
        cancel_button = QPushButton('Cancel', self)
        cancel_button.clicked.connect(self.close)

        hbox_button.addWidget(ok_button)
        hbox_button.addWidget(cancel_button)

        grid.addLayout(hbox_button, len(self.column) + 1, 0)

        self.setLayout(grid)

        self.setGeometry(900, 300, 350, 300)
        self.setWindowTitle('Edit information')
        self.show()
Example #31
0
class Item(QWidget):
    def __init__(
        self,
        parent,
        func,
        titulo="",
        label="",
        icone="",
    ):
        super(Item, self).__init__(parent)
        self.salvo = True
        self.layout = QGridLayout(self)
        self.layout.setSpacing(0)
        self.func = func
        self.titulo = titulo
        self.label = label
        self.icone = icone
        self.label_titulo = QLabel(self.titulo)
        self.label_titulo.setFont(QFont('SansSerif', 15))
        self.label_descricao = QLabel(self.label)
        self.label_titulo.setStyleSheet(
            "border:2px solid #404040; background:#404040;")
        self.label_descricao.setStyleSheet(
            "border:2px solid #404040; background:#404040;")
        palavras = QVBoxLayout(self)
        self.layout.addLayout(palavras, 0, 0)
        palavras.addWidget(self.label_titulo)
        palavras.addWidget(self.label_descricao)

        self.setFixedHeight(100)

    def mousePressEvent(self, evento_mouse):
        """
        Chama a funcao func
        :param evento_mouse:
            evento
        :return:
            None
        """

    def mousePressEvent(self, mouse_event):
        self.func()

    def enterEvent(self, evento):
        """
        Cria animacao e linhas verdes quando on hover do mouse
        :param evento:
            evento de entrada do mouse
        :return:
            None
        """
        self.label_titulo.setStyleSheet(
            "border-top: 2px solid #5cb50d;background:#404040;")
        self.label_descricao.setStyleSheet(
            "border-top: 2px solid #404040;background:#404040;")

    def leaveEvent(self, evento):
        """
        Remove animacao e linhas verdes quando sai do hver do mouse
        :param evento:
            evento
        :return:
            None
        """
        self.label_titulo.setStyleSheet(
            "border:2px solid #404040;background:#404040;")
        self.label_descricao.setStyleSheet(
            "border:2px solid #404040;background:#404040;")
Example #32
0
class BoasVindas(QWidget):
    def __init__(self, parent):
        super(BoasVindas, self).__init__(parent)
        self.caminho = 0
        # Layout do monitor serial com grid
        self.layout = QGridLayout(self)
        self.parent = parent
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.setColumnStretch(0, 1)
        # Onde vai entrar o achar
        # self.layout.setColumnStretch(1, 12)
        self.layout.setRowStretch(0, 1)
        self.layout.setRowStretch(1, 1)
        self.layout.setSpacing(5)
        self.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(Mascote(self), 0, 0)
        self.setAutoFillBackground(True)
        self.itens = QVBoxLayout(self)
        self.popular_itens()
        self.salvo = True

    def popular_itens(self):
        """
        Caixas do boas vindas
        :return:
            None
        """
        novo = Item(self, self.parent.nova_aba, "Rascunho em Branco",
                    "Crie um novo rascunho do zero",
                    os.path.join('recursos', 'novoArquivo.png'))
        aprender_mais = Item(
            self, self.abrir_site, "Não sabe como começar?",
            "Visite nosso site para ler um de nossos tutoriais!", "")
        self.layout.addLayout(self.itens, 0, 0)
        self.itens.addWidget(novo)
        self.itens.addWidget(aprender_mais)
        self.setFixedHeight(300)

    @staticmethod
    def abrir_site():
        """
        Direciona para o nosso site brino.cc/tutoriais.php
        :return:
            None
        """

    @staticmethod
    def abrir_site():
        """
               Direciona para o nosso site brino.cc/tutoriais.php
               :return:
                   None
        """
        webbrowser.open("http://brino.cc/tutoriais.php", 1, True)

    def get_caminho(self):
        """
        Retorna o caminho
        :return caminho:
            Caminho
        """
        return self.caminho
Example #33
0
    def billwidget(self):

        # buyer information
        # buyers name
        self.buyer_name = QLineEdit()
        self.buyer_name.resize(100, 100)
        self.buyer_name.setPlaceholderText("Janath Jsk")
        # customizing the line edit
        self.buyer_name.setStyleSheet("color: rgb(120, 60, 5)")
        # buyer_name clear button
        buyer_name_clear = QPushButton()
        buyer_name_clear.setIcon(QIcon("icons/005-cancel.png"))
        buyer_name_clear.setIconSize(QSize(19, 19))
        buyer_name_clear.clicked.connect(self.buyer_name.clear)

        # buyers mobile number
        self.buyer_mobile = QLineEdit()
        self.buyer_mobile.resize(100, 100)
        self.buyer_mobile.setInputMask("000-000-0000")

        # buyer mobile clear
        buyer_mobile_clear = QPushButton()
        buyer_mobile_clear.setIcon(QIcon("icons/005-cancel.png"))
        buyer_mobile_clear.setIconSize(QSize(19, 19))
        buyer_mobile_clear.clicked.connect(self.buyer_mobile.clear)
        buyer_mobile_clear.setObjectName("clear")

        # buyers address
        self.buyers_address = QTextEdit()

        # buyer address clear
        address_clear_bt = QPushButton()
        address_clear_bt.setIcon(QIcon("icons/005-cancel.png"))
        address_clear_bt.setIconSize(QSize(19, 19))
        address_clear_bt.clicked.connect(self.buyers_address.clear)

        # create main layout and set as central widget
        bill_layout = QVBoxLayout()

        # create layout and add to main layout
        form_layout = QFormLayout()
        form_layout.setSpacing(0)

        # horizontal layout for buyer name and clear
        name_h_layout = QHBoxLayout()
        name_h_layout.addWidget(self.buyer_name)
        name_h_layout.addWidget(buyer_name_clear)
        # add name horizontal to form layout
        form_layout.addRow("Name", name_h_layout)

        # create horizontal layout for mobile number and clear button
        mobile_h_layout = QHBoxLayout()
        mobile_h_layout.addWidget(self.buyer_mobile)
        mobile_h_layout.addWidget(buyer_mobile_clear)
        # add mobile horizontal layout in form layout
        form_layout.addRow("Mobile Number", mobile_h_layout)

        # add address and clear button
        address_layout = QHBoxLayout()
        address_layout.addWidget(self.buyers_address)
        address_layout.addWidget(address_clear_bt)

        # add address and address clear button to form layout
        form_layout.addRow("Address", address_layout)

        # create buyer information box
        buyer_information_gp = QGroupBox("Buyer Information")
        # set the form layout as buyer information layout
        buyer_information_gp.setLayout(form_layout)

        # add buyer information box to bill_layout
        bill_layout.addWidget(buyer_information_gp)
        bill_layout.addStretch()

        # create the combo box for selecting the item from the sqlite3 table items
        # create item_dict and store the quantity and price in item_dict
        self.items_dict = {}

        # create the item query for getting data from items table
        items_query = QSqlQuery()
        items_query.exec_("SELECT name, quantity, price FROM items")
        # store the selected data in items_dict
        while items_query.next():
            self.items_dict[items_query.value(0)] = (items_query.value(1),
                                                     items_query.value(2))

        # create item list and store the items_dict keys
        items_list = list(self.items_dict.keys())
        # create the combo for selecting the item and when index was changed connect to Quantity to enable the quantity
        # box and set the range
        self.items_combo = QComboBox()
        self.items_combo.addItems(items_list)
        self.items_combo.currentIndexChanged.connect(self.Quantity)

        # create the spin box to enter the quatity
        self.item_quantity = QSpinBox()
        self.item_quantity.setEnabled(False)

        # create the form layout item and quantity information
        item_form = QFormLayout()
        item_form.addRow("Item Name: ", self.items_combo)
        item_form.addRow("Quantity: ", self.item_quantity)

        # create the add push button to add the item in bill
        add_bt = QPushButton("Add to Bill")
        add_bt.clicked.connect(self.AddToBill)

        # create horizontal layout for button
        bt_h_l = QHBoxLayout()
        bt_h_l.addStretch()
        bt_h_l.addWidget(add_bt)
        bt_h_l.addStretch()

        # create the vertical layout for item information box
        item_v_l = QVBoxLayout()
        item_v_l.addLayout(item_form)
        item_v_l.addLayout(bt_h_l)

        # create the group box for item information
        items_inf = QGroupBox("Add items")
        items_inf.setLayout(item_v_l)

        # add item information group to bill_layout
        bill_layout.addWidget(items_inf)

        # items buyed
        self.bill_model = QStandardItemModel()
        self.bill_table = QTableView()
        self.bill_table.SelectionMode(3)
        self.bill_table.setModel(self.bill_model)

        # set the column count for bill_model
        self.bill_model.setColumnCount(4)

        # strech the column of bill_table
        self.bill_table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        # set the horizontal header labels
        header = ["ITEMS", "QUANTITY", "PRICE", "TOTAL"]
        self.bill_model.setHorizontalHeaderLabels(header)

        # create grid layout
        bill1_layout = QGridLayout()
        bill1_layout.addLayout(bill_layout, 0, 0)
        bill1_layout.addWidget(self.bill_table, 0, 1)
        # set bill_tab layout as bill_layout

        self.bill_tab.setLayout(bill1_layout)
Example #34
0
    def __init__(self, parent=None, aw=None):
        super(autosaveDlg, self).__init__(parent, aw)
        self.setModal(True)
        self.setWindowTitle(
            QApplication.translate("Form Caption", "Autosave", None))

        settings = QSettings()
        if settings.contains("autosaveGeometry"):
            self.restoreGeometry(settings.value("autosaveGeometry"))

        self.helpdialog = None

        self.prefixEdit = QLineEdit(self.aw.qmc.autosaveprefix)
        self.prefixEdit.setToolTip(
            QApplication.translate("Tooltip", "Automatic generated name",
                                   None))
        self.prefixEdit.textChanged.connect(self.prefixChanged)
        prefixpreviewLabel = QLabel()
        prefixpreviewLabel.setAlignment(
            Qt.Alignment(Qt.AlignCenter | Qt.AlignRight))
        prefixpreviewLabel.setText(
            QApplication.translate("Label", "Preview:", None))
        self.prefixPreview = QLabel()
        self.prefixpreviewrecordingLabel = QLabel()
        self.prefixpreviewrecordingLabel.setAlignment(
            Qt.Alignment(Qt.AlignCenter | Qt.AlignRight))
        self.prefixPreviewrecording = QLabel()
        self.prefixChanged()

        autochecklabel = QLabel(
            QApplication.translate("CheckBox", "Autosave [a]", None))
        self.autocheckbox = QCheckBox()
        self.autocheckbox.setToolTip(
            QApplication.translate(
                "Tooltip",
                "ON/OFF of automatic saving when pressing keyboard letter [a]",
                None))
        self.autocheckbox.setChecked(self.aw.qmc.autosaveflag)

        addtorecentfileslabel = QLabel(
            QApplication.translate("CheckBox", "Add to recent file list",
                                   None))
        self.addtorecentfiles = QCheckBox()
        self.addtorecentfiles.setToolTip(
            QApplication.translate(
                "Tooltip",
                "Add auto saved file names to the recent files list", None))
        self.addtorecentfiles.setChecked(
            self.aw.qmc.autosaveaddtorecentfilesflag)

        autopdflabel = QLabel(
            QApplication.translate("CheckBox", "Save also", None))
        self.autopdfcheckbox = QCheckBox()
        self.autopdfcheckbox.setToolTip(
            QApplication.translate("Tooltip",
                                   "Save image alongside .alog profiles",
                                   None))
        self.autopdfcheckbox.setChecked(self.aw.qmc.autosaveimage)
        imageTypes = ["PDF", "SVG", "PNG", "JPEG", "BMP", "CSV", "JSON"]
        self.imageTypesComboBox = QComboBox()
        self.imageTypesComboBox.addItems(imageTypes)
        self.imageTypesComboBox.setCurrentIndex(
            imageTypes.index(self.aw.qmc.autosaveimageformat))
        prefixlabel = QLabel()
        prefixlabel.setAlignment(Qt.Alignment(Qt.AlignBottom | Qt.AlignRight))
        prefixlabel.setText(
            QApplication.translate("Label", "File Name Prefix", None))

        # connect the ArtisanDialog standard OK/Cancel buttons
        self.dialogbuttons.accepted.connect(self.autoChanged)
        self.dialogbuttons.rejected.connect(self.close)
        self.helpButton = self.dialogbuttons.addButton(QDialogButtonBox.Help)
        self.setButtonTranslations(
            self.helpButton, "Help",
            QApplication.translate("Button", "Help", None))
        self.dialogbuttons.button(QDialogButtonBox.Help).clicked.connect(
            self.showautosavehelp)

        pathButton = QPushButton(QApplication.translate(
            "Button", "Path", None))
        pathButton.setFocusPolicy(Qt.NoFocus)
        self.pathEdit = QLineEdit(self.aw.qmc.autosavepath)
        self.pathEdit.setToolTip(
            QApplication.translate(
                "Tooltip",
                "Sets the directory to store batch profiles when using the letter [a]",
                None))
        pathButton.clicked.connect(self.getpath)

        pathAlsoButton = QPushButton(
            QApplication.translate("Button", "Path", None))
        pathAlsoButton.setFocusPolicy(Qt.NoFocus)
        self.pathAlsoEdit = QLineEdit(self.aw.qmc.autosavealsopath)
        self.pathAlsoEdit.setToolTip(
            QApplication.translate(
                "Tooltip", "Sets the directory to store the save also files",
                None))
        pathAlsoButton.clicked.connect(self.getalsopath)

        # this intermediate layout is needed to add the 'addtorecentfiles' checkbox into the existing grid layout.
        autochecklabelplus = QHBoxLayout()
        autochecklabelplus.addWidget(autochecklabel)
        autochecklabelplus.addWidget(self.addtorecentfiles)
        autochecklabelplus.addWidget(addtorecentfileslabel)
        autochecklabelplus.addStretch()

        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.dialogbuttons)
        autolayout = QGridLayout()
        autolayout.addWidget(self.autocheckbox, 0, 0, Qt.AlignRight)
        autolayout.addLayout(autochecklabelplus, 0, 1)
        autolayout.addWidget(prefixlabel, 1, 0)
        autolayout.addWidget(self.prefixEdit, 1, 1, 1, 2)
        autolayout.addWidget(prefixpreviewLabel, 2, 0)
        autolayout.addWidget(self.prefixPreview, 2, 1)
        autolayout.addWidget(self.prefixpreviewrecordingLabel, 3, 0)
        autolayout.addWidget(self.prefixPreviewrecording, 3, 1)
        autolayout.addWidget(pathButton, 4, 0)
        autolayout.addWidget(self.pathEdit, 4, 1, 1, 2)
        autolayout.addWidget(self.autopdfcheckbox, 5, 0, Qt.AlignRight)
        autolayout.addWidget(autopdflabel, 5, 1)
        autolayout.addWidget(self.imageTypesComboBox, 5, 2)
        autolayout.addWidget(pathAlsoButton, 6, 0)
        autolayout.addWidget(self.pathAlsoEdit, 6, 1, 1, 2)
        autolayout.setColumnStretch(0, 0)
        autolayout.setColumnStretch(1, 10)
        autolayout.setColumnStretch(2, 0)
        mainLayout = QVBoxLayout()
        mainLayout.addLayout(autolayout)
        mainLayout.addStretch()
        mainLayout.addSpacing(10)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)
        self.dialogbuttons.button(QDialogButtonBox.Ok).setFocus()
        self.setFixedHeight(self.sizeHint().height())
    def build_ui(self):
        min_width = 150
        max_width = 200

        layout = QGridLayout()
        self.setLayout(layout)

        ####
        #
        # Build up the sim settings tab
        #
        #  Choose Sim: | ComboBox |
        #  Choose shock finder: | ComboBox |
        #
        ####

        layout.addWidget(QLabel('Choose sim'), 0, 0)
        self.sim_combo = QComboBox(self)
        self.update_sim_list()
        self.sim_combo.currentIndexChanged.connect(self.sim_selection_changed)
        layout.addWidget(self.sim_combo, 0, 1)

        layout.addWidget(QLabel('Choose Shock Finder'), 1, 0)
        self.shock_combo = QComboBox(self)
        self.update_shock_opts()
        self.shock_combo.currentIndexChanged.connect(self.shock_finder_changed)
        layout.addWidget(self.shock_combo, 1, 1)

        ####
        #
        #  prtl stride:
        #  | QLineEdit | | x | average 1D |
        #
        ####

        sim_ind = self.sim_selected.sim_num
        sim_params = self.main_params['sim_params'][sim_ind]

        layout.addWidget(QLabel('Prtl Stride'), 2, 0)

        self.prtl_stride_edit = QLineEdit(self)
        self.prtl_stride_edit.setText(str(sim_params['PrtlStride']))
        self.prtl_stride_edit.setMaximumWidth(max_width)
        self.prtl_stride_edit.setMinimumWidth(min_width)
        self.prtl_stride_edit.returnPressed.connect(self.stride_changed)
        layout.addWidget(self.prtl_stride_edit, 2, 1)
        self.average1D_cb = QCheckBox("Average1D")
        self.average1D_cb.setChecked(sim_params['Average1D'])
        self.average1D_cb.stateChanged.connect(self.avg_changed)

        layout.addWidget(self.average1D_cb, 3, 0)

        # radio buttons to choose plane.
        row = QHBoxLayout()
        row.addWidget(QLabel('Choose 2D-plane:'))

        self.slice_radio_btns = []
        radiobutton = QRadioButton("x-y")
        radiobutton.plane = 0
        radiobutton.toggled.connect(self.radio_clicked)
        self.slice_radio_btns.append(radiobutton)
        row.addWidget(radiobutton)

        radiobutton = QRadioButton("x-z")
        radiobutton.plane = 1
        radiobutton.toggled.connect(self.radio_clicked)
        self.slice_radio_btns.append(radiobutton)

        row.addWidget(radiobutton)

        radiobutton = QRadioButton("y-z")
        radiobutton.plane = 2
        radiobutton.toggled.connect(self.radio_clicked)
        self.slice_radio_btns.append(radiobutton)

        row.addWidget(radiobutton)
        layout.addLayout(row, 4, 0, 1, 2)

        # Now do the sliders

        self.sliders_dict = {}
        for i, ax in enumerate(['x', 'y', 'z']):
            row = QHBoxLayout()
            sld_obj = {}
            sld_obj['label'] = QLabel(self)
            sld_obj['sld'] = QSlider(Qt.Horizontal, self)
            sld_obj['sld'].ax = ax
            # update the text box whenever sld is change
            sld_obj['sld'].valueChanged.connect(self.scale_handler)
            # only update the plot when the user releases the mouse
            sld_obj['sld'].mouseReleaseEvent = partial(self.update_slice_val,
                                                       ax)

            # self.sld.setRange(self.param.minimum, self.param.maximum)
            sld_obj['sld'].setFocusPolicy(Qt.NoFocus)
            sld_obj['sld'].setPageStep(1)

            row.addWidget(QLabel(f'{ax}-slice'))
            row.addWidget(sld_obj['sld'])
            row.addWidget(sld_obj['label'])
            self.sliders_dict[ax] = sld_obj

            layout.addLayout(row, 5 + i, 0, 1, 2)

        self.update_slice_widgets()
Example #36
0
class readingUI(QMainWindow):
    def __init__(self):

        # Inherit from parent (QMainWindow)
        super().__init__()

        self.defaultPath = 'C:\\Users\\ianho\\Dropbox\\Excel Documents'

        self.setWindowTitle('DXL360 Readings')
        self.setFixedSize(500, 520)
        self.move(400, 200)
        self._centralWidget = QWidget(self)

        self.layout = QGridLayout()

        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.layout)

        # Initialize UI elements
        self.createInputLayout()
        self.createTable()
        self.createReadButton()
        self.createStartButton()
        self.createClearButton()
        self.createExportButton()
        self.createStatusLabel()

        # Place UI elements into grid slots
        self.layoutElements()

    def createInputLayout(self):

        # ----- Initialize input layout ----- #

        self._inputLayout = QGridLayout()

        # ----- Assign elements to variables so we can access them later ----- #
        self.labels = {}
        labels = {
            'lbCOMPort': 'COM Port:',
            'lbDate': 'Date:',
            'lbArmID': 'Arm ID:',
            'lbArmDesc': 'Arm Description:',
            'lbFilePath': 'Output file path:',
            'lbFileName': 'Output file name:'
        }

        self.lineEdits = {}
        lineEdits = {
            'edCOMPort':
            '3',
            'edDate':
            str(datetime.now().strftime('%b')) + '. ' +
            str(datetime.now().day) + ', ' + str(datetime.now().year),
            'edArmID':
            str(datetime.now().strftime('%I%M%S')),
            'edArmDesc':
            '',
            'edFilePath':
            self.defaultPath,
            'edFileName':
            'readings'
        }

        # ----- Initialize input form elements, set default values ----- #
        for labelName, labelText in labels.items():
            self.labels[labelName] = QLabel(labelText)

        for lineEditName, lineEditText in lineEdits.items():
            self.lineEdits[lineEditName] = QLineEdit(lineEditText)

        labelKeys = list(self.labels.keys())
        lineEditKeys = list(self.lineEdits.keys())

        for row in range(len(labels)):
            self._inputLayout.addWidget(self.labels[labelKeys[row]], row, 0)
            self._inputLayout.addWidget(self.lineEdits[lineEditKeys[row]], row,
                                        1)

        # ----- Format input form elements ----- #

        for row in range(len(self.labels)):
            self._inputLayout.itemAtPosition(row, 0).setAlignment(Qt.AlignLeft)
            self._inputLayout.itemAtPosition(row, 1).setAlignment(Qt.AlignLeft)

        for lineEdit in self.lineEdits.values():
            lineEdit.setCursorPosition(0)

        self.lineEdits['edFilePath'].setToolTip(
            self.lineEdits['edFilePath'].text())

    def createTable(self):
        self.defaultArmPos = [
            '+45', '+40', '+30', '+15', '0', '-15', '-30', '-45', '-60', '-75'
        ]

        self.readingTbl = QTableWidget(len(self.defaultArmPos), 2)
        self.readingTbl.setFixedSize(185, 325)

        self.readingTbl.setHorizontalHeaderLabels(
            ['Arm Position', 'FR5 Angle'])

        self.readingTbl.setColumnWidth(0, 80)
        self.readingTbl.setColumnWidth(1, 80)

        for row in range(self.readingTbl.rowCount()):
            self.readingTbl.setItem(row, 0,
                                    QTableWidgetItem(self.defaultArmPos[row]))

    # ----- Create some buttons ----- #

    def createStartButton(self):
        self.startButton = QPushButton('Start')
        self.startButton.setFixedHeight(30)
        self.startButton.setFont(QFont('Calibri', 16))

    def createClearButton(self):
        self.clearButton = QPushButton('Clear')
        self.clearButton.setFixedHeight(30)
        self.clearButton.setFont(QFont('Calibri', 16))

    def createReadButton(self):
        self.readButton = QPushButton('Take reading')
        self.readButton.setFont(QFont('Calibri', 24))
        self.readButton.setFixedSize(200, 100)
        self.readButton.setEnabled(False)

    def createExportButton(self):
        self.exportButton = QPushButton('Export Data')
        self.exportButton.setFixedHeight(30)
        self.exportButton.setFont(QFont('Calibri', 16))
        self.exportButton.setEnabled(False)

    def createStatusLabel(self):
        self.statusLabel = QLabel('Click "Start" to begin!')
        self.statusLabel.setFixedHeight(30)
        self.statusLabel.setFont(QFont('Calibri', 16))
        self.statusLabel.setAlignment(Qt.AlignLeft)

    def layoutElements(self):
        self.layout.addLayout(self._inputLayout, 0, 0)

        # --- Layout start/clear buttons --- #
        self.vertLayout1 = QVBoxLayout()

        self.vertLayout1.addWidget(self.startButton, 0)
        self.vertLayout1.itemAt(0).setAlignment(Qt.AlignHCenter)

        self.vertLayout1.addWidget(self.clearButton, 1)
        self.vertLayout1.itemAt(1).setAlignment(Qt.AlignHCenter)

        self.vertLayout1.addWidget(self.exportButton, 2)
        self.vertLayout1.itemAt(2).setAlignment(Qt.AlignHCenter)

        self.layout.addLayout(self.vertLayout1, 1, 0)
        # ----------------------------------- #

        self.layout.addWidget(self.readingTbl, 0, 1, 3, 1)
        self.layout.itemAtPosition(0, 1).setAlignment(Qt.AlignTop)

        self.layout.addWidget(self.readButton, 2, 0)
        self.layout.itemAtPosition(2, 0).setAlignment(Qt.AlignHCenter)

        self.layout.addWidget(self.statusLabel, 2, 1)

    # ----- Define some methods ----- #

    def clearInputs(self):
        for row in range(self.readingTbl.rowCount()):
            self.readingTbl.setItem(row, 1, QTableWidgetItem(''))

        self.readingTbl.setCurrentCell(0, 1)

    def isReading(self):
        if self.startButton.text() == 'Start':
            self.count = 0

            for row in range(self.readingTbl.rowCount()):
                if self.readingTbl.item(row, 0).text() != '':
                    self.count += 1

            self.readButton.setEnabled(True)
            self.startButton.setText('Stop')
            self.exportButton.setEnabled(True)
            self.statusLabel.setText('Ready!')

        elif self.startButton.text() == 'Stop':
            self.startButton.setText('Start')
            self.readButton.setEnabled(False)
            self.exportButton.setEnabled(False)
            self.clearButton.setEnabled(False)
Example #37
0
class TrailerPlayer(QWidget):
    """Sub-class of the QWidget class"""
    def __init__(self, parent=None, *args, **kwargs):
        """Initialize class attributes"""
        super(TrailerPlayer, self).__init__()
        self.disabled = None  # Video button clicked
        self.scroll = None  # scroll area
        self.init_ui()
        self.refresh()

    def init_ui(self):
        """Create local components"""
        self.glayout = QGridLayout()  # main Grid Layout
        self.vlayout = QVBoxLayout()  # WebView Layout
        self.hlayout = QHBoxLayout()  # additional buttons
        self.webview = QWebEngineView()  # WebView object
        self.webview.load(
            QUrl("http://www.youtube.com/embed/hI9GyhX7yHM?rel"
                 "=0&modestbranding=0&autohide=1&mute=0&showinfo"
                 "=0&controls=1&autoplay=1"))  # default url
        # refresh button
        self.btn_size = QSize(16, 16)
        refresh = Button()
        refresh.setEnabled(False)
        refresh.setFixedWidth(24)
        refresh.setToolTip('Refresh')
        refresh.setStatusTip('Refresh')
        icon = QIcon()
        path = os.path.join(os.path.dirname(__file__), "Icons")
        icon.addPixmap(QPixmap(os.path.join(path, "refresh-24.png")))
        icon.addPixmap(QPixmap(os.path.join(path, "cancel-24.png")),
                       QIcon.Disabled)
        refresh.setIcon(icon)
        refresh.clicked.connect(self.refresh)
        refresh.setCursor(QCursor(Qt.PointingHandCursor))
        self.rfresh = refresh

        # Stream button
        stream = Button()
        stream.setFixedWidth(24)
        stream.setToolTip("Stream video")
        stream.setStatusTip("Stream video")
        stream.setIconSize(self.btn_size)
        stream.setIcon(QIcon(os.path.join(path, 'streaming-media-30.png')))
        stream.clicked.connect(self.search)
        stream.setCursor(QCursor(Qt.PointingHandCursor))

        btns_widget = QWidget()
        self.hlayout.addWidget(self.rfresh, 0)
        self.hlayout.addWidget(stream, 1)
        btns_widget.setLayout(self.hlayout)
        btns_widget.setFixedWidth(330)

        self.vlayout.addWidget(self.webview)
        self.vlayout.setAlignment(Qt.AlignTop)
        self.setLayout(self.glayout)
        self.glayout.addLayout(self.vlayout, 0, 0)
        self.add_scroll_box()
        self.glayout.addWidget(btns_widget, 1, 1)
        QShortcut(
            QKeySequence(Qt.Key_Space),  # Space key responds to None
            self,
            lambda: None,
            context=Qt.ApplicationShortcut)

    def refresh(self):
        """refrsh movie information"""
        self.rfresh.setEnabled(False)
        thread = MyThread(self)
        thread.finished.connect(self.add_scroll_box)
        thread.start()

    def add_scroll_box(self):
        """Create Scroll area and its components"""
        if self.scroll:
            self.disabled = None
            self.scroll.setParent(None)
            self.rfresh.setEnabled(True)

        self.scroll = QScrollArea(
        )  # Scroll Area which contains the widgets, set as the centralWidget
        self.widget = QWidget(
        )  # Widget that contains the collection of Vertical Box
        self.vbox = QVBoxLayout(
        )  # The Vertical Box that contains the Horizontal Boxes of  labels and buttons
        self.labels_buttons()
        self.vbox.setAlignment(Qt.AlignVCenter)
        self.widget.setLayout(self.vbox)

        # Scroll Area Properties
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.widget)
        self.scroll.setStyleSheet('background-color:rgba(0, 0, 0, 0)')
        self.scroll.setFixedWidth(330)
        self.glayout.addWidget(self.scroll, 0, 1)

    def labels_buttons(self):
        """Create labels and buttons"""
        posters_dir = os.path.join(trailers_dir, 'posters')
        clearing = []
        for type_ in data_dict.values():
            for cat in type_.values():
                for single in cat:
                    path = os.path.join(posters_dir,
                                        single['poster'].split('/')[-1])
                    if single['title'] not in clearing:
                        self.labels(path, single)
                        clearing.append(single['title'])

    def labels(self, path, single):
        """Create labels"""
        if os.path.exists(path):
            widget = QWidget()
            v_box = QVBoxLayout()
            image = QPixmap(path)
            imageLabel = QLabel(parent=widget)
            imageLabel.setPixmap(image)
            imageLabel.setGeometry(0, 0, image.width(), image.height())
            v_box.addWidget(imageLabel)
            v_box.setAlignment(Qt.AlignVCenter)
            widget.setLayout(v_box)
            widget.setStyleSheet('background-color:rgba(255, 255, 255, 50)')
            widget.setFixedWidth(image.width())
            self.vbox.addWidget(widget)
            for trailer in single['trailers']:  # create associated buttons
                self.buttons(trailer[0], trailer[1], v_box)

    def buttons(self, text, url, box):
        """Create Button"""
        button = TrailerButton()
        button.setFixedHeight(24)
        button.setText(text)
        button.setFont(QFont('arial', 8))
        button.setToolTip(text)
        button.setStatusTip(text)
        button.setCursor(QCursor(Qt.PointingHandCursor))
        button.clicked.connect(lambda event, url=url: self.load(event, url))
        box.addWidget(button)

    def load(self, event, url):
        """Load new url to webview"""
        if self.disabled:
            self.disabled.setEnabled(True)
        self.disabled = self.sender()
        self.disabled.setEnabled(False)
        self.webview.load(QUrl(url))

    def search(self):
        """Stream videos from url"""
        dlg = UrlDialog(self)
        if dlg.exec_():
            if self.disabled:
                self.disabled.setEnabled(True)
            text = dlg.text
            url = text
            if text:
                if text.find('youtu.be') > -1:
                    code = text.split('/')[-1]
                    url = YOURL.format(code)
                elif text.find('youtube') > -1 and text.find('watch') > -1:
                    link = text.split('?')[-1]
                    code = link.split('&')[0][2:]
                    url = YOURL.format(code)
                elif text.find('youtube') > -1 and text.find('embed') > -1:
                    link = text.split('?')[0]
                    code = link.split('/')[-1]
                    url = YOURL.format(code)
                self.webview.load(QUrl(url))
    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)

        # Digit Buttons
        self.digitButton = [x for x in range(0, 10)]

        for i in range(len(self.digitButton)):
            self.digitButton[i] = Button(str(i), self.buttonClicked)

        # . and = Buttons
        self.decButton = Button('.', self.buttonClicked)
        self.eqButton = Button('=', self.buttonClicked)

        # Operator Buttons
        self.mulButton = Button('*', self.buttonClicked)
        self.divButton = Button('/', self.buttonClicked)
        self.addButton = Button('+', self.buttonClicked)
        self.subButton = Button('-', self.buttonClicked)

        # Parentheses Buttons
        self.lparButton = Button('(', self.buttonClicked)
        self.rparButton = Button(')', self.buttonClicked)

        # Clear Button
        self.clearButton = Button('C', self.buttonClicked)

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

        mainLayout.addWidget(self.display, 0, 0, 1, 2)

        numLayout = QGridLayout()

        for i in range(1, len(self.digitButton)):
            d = i % 3
            j = i // 3
            if i % 3 == 0:
                numLayout.addWidget(self.digitButton[i], 2 - (j - 1),
                                    2)  #2-를 해주어 역방향으로 바꿈
            else:
                numLayout.addWidget(self.digitButton[i], 2 - j, d - 1)

        numLayout.addWidget(self.digitButton[0], 3, 0)

        numLayout.addWidget(self.decButton, 3, 1)
        numLayout.addWidget(self.eqButton, 3, 2)

        mainLayout.addLayout(numLayout, 1, 0)

        opLayout = QGridLayout()

        opLayout.addWidget(self.mulButton, 0, 0)
        opLayout.addWidget(self.divButton, 0, 1)
        opLayout.addWidget(self.addButton, 1, 0)
        opLayout.addWidget(self.subButton, 1, 1)

        opLayout.addWidget(self.lparButton, 2, 0)
        opLayout.addWidget(self.rparButton, 2, 1)

        opLayout.addWidget(self.clearButton, 3, 0)

        mainLayout.addLayout(opLayout, 1, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle("My Calculator")
Example #39
0
    def interface(self):
        """
         set defqault parametres to  gui and layout
        :return:  None

        """
        self.setStyleSheet("background-color: beige;")
        self.resize(400, 400)
        self.setWindowTitle("Surveyor's Calculator")
        self.show()

        # Labels
        label_1 = QLabel("Point 1:", self)
        label_2 = QLabel("Point 2:", self)
        label_3 = QLabel("Point 3:", self)
        label_4 = QLabel("Angle:", self)
        label_5 = QLabel("Result", self)

        #user input
        self.point1 = QLineEdit()
        self.point2 = QLineEdit()
        self.point3 = QLineEdit()
        self.angle = QLineEdit()
        self.result = QLineEdit()

        self.result.readonly = True
        self.result.setToolTip('Insert number and choose action...')

        Layout = QGridLayout()
        Layout.addWidget(label_1, 0, 0)
        Layout.addWidget(label_2, 0, 2)
        Layout.addWidget(label_3, 0, 4)
        Layout.addWidget(label_4, 1, 0)
        Layout.addWidget(label_5, 1, 2)
        Layout.addWidget(self.point1, 0, 1)
        Layout.addWidget(self.point2, 0, 3)
        Layout.addWidget(self.point3, 0, 5)
        Layout.addWidget(self.angle, 1, 1)
        Layout.addWidget(self.result, 1, 3)

        #Buttons
        azimuth_button = QPushButton("Azimuth", self)
        length_button = QPushButton("Length", self)
        grad_button = QPushButton("Grad", self)
        degree_button = QPushButton("Degree", self)
        horizontal_angle_button = QPushButton("Horizontal Angle", self)
        gauss_area_button = QPushButton("Gauss Area", self)
        import_data = QPushButton("Import coordinates", self)
        end_button = QPushButton("Finish work on today", self)
        radian_button = QPushButton("Radian", self)
        end_button.resize(end_button.sizeHint())

        # adding buttons to layout
        Layout2 = QHBoxLayout()
        Layout2.addWidget(azimuth_button)
        Layout2.addWidget(length_button)
        Layout2.addWidget(grad_button)
        Layout2.addWidget(degree_button)
        Layout2.addWidget(radian_button)
        Layout2.addWidget(horizontal_angle_button)
        Layout2.addWidget(gauss_area_button)
        Layout2.addWidget(import_data)

        Layout.addLayout(Layout2, 2, 0, 2, 3)
        self.setLayout(Layout)
        self.setGeometry(20, 20, 400, 100)
        self.setWindowIcon(QIcon('surveyor.jpg'))
        Layout.addWidget(end_button, 3, 0, 2, 3)

        end_button.clicked.connect(self.end)
        azimuth_button.clicked.connect(self.perform_an_action)
        length_button.clicked.connect(self.perform_an_action)
        grad_button.clicked.connect(self.perform_an_action)
        degree_button.clicked.connect(self.perform_an_action)
        horizontal_angle_button.clicked.connect(self.perform_an_action)
        gauss_area_button.clicked.connect(self.perform_an_action)
        radian_button.clicked.connect(self.perform_an_action)
Example #40
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)

        # Layout settings.
        numLayout = QGridLayout()
        opLayout = QGridLayout()
        constantLayout = QGridLayout()
        funcLayout = QGridLayout()

        buttonGroups = {
            'num': {
                'buttons': numPadList,
                'layout': numLayout,
                'columns': 3
            },
            'op': {
                'buttons': operatorList,
                'layout': opLayout,
                'columns': 2
            },
            'constants': {
                'buttons': constantList,
                'layout': constantLayout,
                '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

        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(constantLayout, 2, 0)
        mainLayout.addLayout(funcLayout, 2, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("My Calculator")
Example #41
0
    def __init__(self, parent=None, imageoperator=None):
        super(MainGUI, self).__init__(parent)

        self.inputfile = None
        self.batchfilenames = None

        self.imageoperator = imageoperator

        self.originalPalette = QApplication.palette()

        self.btnFileOpen = QPushButton("Choose image file...")
        self.btnFileOpen.clicked.connect(self.getfile)

        self.leInputImage = QLabel()
        self.leInputImage.setPixmap(
            QPixmap(
                os.path.abspath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 '..', '..', '..', 'resources',
                                 'emptyspace.png'))).scaledToHeight(400))

        self.leOutputImage = QLabel()
        self.leOutputImage.setPixmap(
            QPixmap(
                os.path.abspath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 '..', '..', '..', 'resources',
                                 'emptyspace.png'))).scaledToHeight(400))

        self.createBottomLeftTabWidget()
        self.createBottomRightTabWidget()
        self.createProgressBar()

        # Top row of GUI, with image displays
        topLeftLayout = QGroupBox("Input Image")
        layout = QVBoxLayout()
        layout.addWidget(self.leInputImage)
        layout.addWidget(self.btnFileOpen)
        layout.addStretch(1)
        topLeftLayout.setLayout(layout)

        topRightLayout = QGroupBox("Output Image")
        layout = QVBoxLayout()
        layout.addWidget(self.leOutputImage)
        layout.addStretch(1)
        topRightLayout.setLayout(layout)

        topLayout = QHBoxLayout()
        topLayout.addWidget(topLeftLayout)
        topLayout.addWidget(topRightLayout)

        # Bottom row of GUI, with processing functions
        bottomLeftLayout = QGroupBox("Processing")
        layout = QVBoxLayout()
        layout.addWidget(self.bottomLeftTabWidget)
        layout.addStretch(1)
        bottomLeftLayout.setLayout(layout)

        bottomRightLayout = QGroupBox("Results")
        layout = QVBoxLayout()
        layout.addWidget(self.bottomRightTabWidget)
        layout.addStretch(1)
        bottomRightLayout.setLayout(layout)

        bottomLayout = QHBoxLayout()
        bottomLayout.addWidget(bottomLeftLayout)
        bottomLayout.addWidget(bottomRightLayout)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 2)
        mainLayout.addLayout(bottomLayout, 1, 0, 1, 2)
        mainLayout.addWidget(self.bottomLeftTabWidget, 1, 0)
        mainLayout.addWidget(self.bottomRightTabWidget, 1, 1)
        mainLayout.addWidget(self.progressBar, 3, 0, 1, 2)
        mainLayout.setRowStretch(0, 1)
        mainLayout.setRowStretch(1, 1)
        mainLayout.setRowMinimumHeight(1, 200)
        mainLayout.setColumnStretch(0, 1)
        mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Pituitary Cytokeratin Spatial Frequency")
        QApplication.setStyle(QStyleFactory.create('Fusion'))
        QApplication.setPalette(QApplication.style().standardPalette())
Example #42
0
class MutantWindow(QDialog):
    def __init__(self, parent=None):
        super(MutantWindow, self).__init__(parent)
        self.setWindowTitle('Mutant Interactive Analysis')
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.show_standard = False
        self.para_dict = {}
        self.mutant_enzyme = E_NONE
        self.enz_box = None

        enz = extract_enzyme_set("para.txt", PARAMETER_NO)
        self.base = ODEAnalysis(SYSTEM, 1, enz)
        if PARAMETER_NO == 0:
            self.base.normalize_enzymes()
        self.base.attain_steady_state()

        self.parameter_box = QGridLayout()
        self.ss_label = QLabel("Steady State Ratios: PIP2: 0.05, PI4P:0.05, "
                               "DAG: 0.008, PA: 0.1677")

        self.grid = QGridLayout()
        self.plot()
        self.set_layout()

    @property
    def enzyme_parameters(self):
        p_box = QGridLayout()
        col = 0
        row = 1
        for i in ENZYME_NAMES:
            main_box_layout = QGroupBox(i.upper())
            main_box = QVBoxLayout()
            main_box_layout.setLayout(main_box)
            main_box_layout.setContentsMargins(1, 10, 10, 1)

            box = QHBoxLayout()
            box.addWidget(QLabel("Vmax"))
            v = MySpinBox()
            v.setValue(self.base.enz[i].v)
            if i == E_PLC or i == E_SOURCE:
                v.setEnabled(False)
            box.addWidget(v)
            box.addWidget(QLabel("Km"))
            k = MySpinBox()
            k.setValue(self.base.enz[i].k)
            v.valueChanged.connect(partial(self.on_parameter_change, i, "v",
                                           v))
            k.valueChanged.connect(partial(self.on_parameter_change, i, "k",
                                           k))
            self.para_dict[i] = {
                "v": v, "k": k
            }
            box.addWidget(k)
            box.addStretch()
            if col == 3:
                row += 1
                col = 1
            else:
                col += 1
            main_box.addLayout(box)

            p_box.addWidget(main_box_layout, row, col)
        self.parameter_box = p_box
        return p_box

    @property
    def mutant_list(self):
        e_box = QHBoxLayout()
        e_box.setContentsMargins(30, 1, 1, 1)
        e_box.addStretch()
        e_box.addWidget(QLabel("Mutant Enzyme : "))
        self.enz_box = QComboBox(self)
        self.enz_box.addItem(E_NONE)
        for e in ENZYME_NAMES:
            self.enz_box.addItem(e)
            self.enz_box.activated[str].connect(self.on_mutant_selection)
        e_box.addWidget(self.enz_box)
        e_box.addStretch()
        return e_box

    @property
    def reset_btn(self):
        btn = QPushButton("Reset")
        btn.clicked[bool].connect(self.on_reset_click)
        return btn

    @property
    def print_btn(self):
        btn = QPushButton("Print Parameters")
        btn.clicked[bool].connect(self.print)
        return btn

    @property
    def toggle_plot(self):
        btn = QPushButton("Toggle Plot")
        btn.clicked[bool].connect(self.on_toggle_plot)
        return btn

    def on_toggle_plot(self):
        if self.show_standard:
            self.show_standard = False
        else:
            self.show_standard = True
        self.plot()

    def print(self):
        enz = {}
        for k in self.base.enz:
            enz[k] = self.base.enz[k].properties

        data = {"Enzymes": enz}
        print(json.dumps(data))

    def reset(self):
        enz = extract_enzyme_set("para.txt", PARAMETER_NO)
        self.base = ODEAnalysis(SYSTEM, 1, enz)
        if PARAMETER_NO == 0:
            self.base.normalize_enzymes()
        self.base.attain_steady_state()
        for key in self.para_dict:
            self.para_dict[key]["v"].setValue(self.base.enz[key].v)
            self.para_dict[key]["k"].setValue(self.base.enz[key].k)

    def on_reset_click(self):
        self.mutant_enzyme = E_NONE
        self.enz_box.setCurrentIndex(0)
        self.reset()
        self.plot()

    def on_parameter_change(self, enzyme, pro, new_val):
        if pro == "v":
            self.base.enz[enzyme].v = new_val.value()
        elif pro == "k":
            self.base.enz[enzyme].k = new_val.value()
        self.plot()

    def on_mutant_selection(self, value):
        self.mutant_enzyme = value
        self.reset()
        self.plot()

    def plot(self):
        self.figure.clear()
        self.base.attain_steady_state()
        s = self.base.steady_state
        p = s[I_PMPI] + s[I_ERPI]
        e_pip2 = abs((s[I_PIP2] / p) / 0.05 - 1)
        e_pi4p = abs((s[I_PI4P] / p) / 0.05 - 1)
        e_dag = abs((s[I_DAG] / p) / 0.008 - 1)
        e_pa = abs(((s[I_PMPA] + s[I_ERPA]) / p) / 0.1677 - 1)
        e_cdpdag = abs((s[I_CDPDAG] / p) / 0.001 - 1)
        error = e_pip2 + e_pi4p + e_dag + e_pa + e_cdpdag
        self.ss_label.setText("Steady State Ratios \n(w.r.t. Total PI): "
                              "\n\nPIP2: %.4f, \nPI4P: %.4f, "
                              "\nDAG: %.4f, \nPA: %.4f, \nCDPDAG: "
                              "%.4f\n\n\nTotal WT Error: "
                              "%.3f %% \n\nPMPI/ERPI: "
                              "%.4f\nPMPA/ERPA: %.4f" %
                              (s[I_PIP2] / p, s[I_PI4P] / p, s[I_DAG] / p,
                               (s[I_PMPA] + s[I_ERPA]) / p, s[I_CDPDAG] / p,
                               error * 100,
                               s[I_PMPI] / s[I_ERPI], s[I_PMPA] / s[I_ERPA]))

        if self.show_standard:
            self.standard_plot()
        else:
            self.individual_plot()
        self.canvas.draw()

    def individual_plot(self):
        s = [x for x in self.base.steady_state]
        s.append(
            self.base.steady_state[I_PMPA] + self.base.steady_state[I_ERPA])
        s.append(
            self.base.steady_state[I_PMPI] + self.base.steady_state[I_ERPI])

        if self.mutant_enzyme != E_NONE:
            self.base.enz[self.mutant_enzyme].v *= MUTANT_DEPLETION

        self.base.attain_steady_state()
        mt = [x for x in self.base.steady_state]
        mt.append(
            self.base.steady_state[I_PMPA] + self.base.steady_state[I_ERPA])
        mt.append(
            self.base.steady_state[I_PMPI] + self.base.steady_state[I_ERPI])

        ax = self.figure.add_subplot(111)
        ind = np.arange(len(LIPID_NAMES) + 2)  # the x locations for the groups
        width = 0.35  # the width of the bars

        ax.bar(ind, np.asanyarray(mt) / np.asanyarray(s), width)
        ax.set_xticks(ind)

        plt.axhline(1, linestyle="--")
        # plt.yscale("log")
        nm = [L_PMPI, L_PI4P, L_PIP2, L_DAG, L_PMPA, L_ERPA, L_CDPDAG,
              L_ERPI, "PA", "PI"]
        ax.set_xticklabels(nm)

        if self.mutant_enzyme != E_NONE:
            self.base.enz[self.mutant_enzyme].v /= MUTANT_DEPLETION

    def standard_plot(self):
        s = [x for x in self.base.steady_state]
        self.base.enz[E_DAGK].v *= MUTANT_DEPLETION

        self.base.attain_steady_state()
        mt_rdga = [x for x in self.base.steady_state]

        self.base.enz[E_DAGK].v /= MUTANT_DEPLETION

        self.base.enz[E_LAZA].v *= MUTANT_DEPLETION

        self.base.attain_steady_state()
        mt_laza = [x for x in self.base.steady_state]

        self.base.enz[E_LAZA].v /= MUTANT_DEPLETION

        ax = self.figure.add_subplot(111)
        ind = np.arange(4)  # the x locations for the groups
        width = 0.35  # the width of the bars

        exp_observations = [1, 1, 1, 2.5]

        val1 = get_ratios(s, mt_rdga)
        val2 = get_ratios(s, mt_laza)
        vals = val1[0], val1[1], val2[0], val2[1]

        legends = ["DAG/PI\n(rdga3)", "PA/PI\n(rdga3)", "DAG/PI\n(laza22)",
                   "PA/PI\n(laza22)"]
        ax.bar(ind, exp_observations, width, color='#3c6df0', label="WT")
        ax.bar(ind + width, vals, width, color='#fe6100', label="MT")
        ax.set_xticks(ind + width / 2)
        plt.axhline(1, linestyle="--")
        plt.axhline(2.5, linestyle="--")
        ax.set_xticklabels(legends)
        plt.legend(loc=0)

    def set_layout(self):

        btn_layout = QVBoxLayout()
        btn_layout.addWidget(self.reset_btn)
        btn_layout.addWidget(self.print_btn)
        btn_layout.addWidget(self.toggle_plot)

        self.grid.addWidget(self.ss_label, 2, 1)
        self.grid.addWidget(self.toolbar, 1, 0)
        self.grid.addWidget(self.canvas, 2, 0)
        self.grid.addLayout(self.mutant_list, 3, 1)
        self.grid.addLayout(self.enzyme_parameters, 4, 0)
        self.grid.addLayout(btn_layout, 4, 1)
        self.setLayout(self.grid)
Example #43
0
    def init_ui(self):
        vbl_0 = QVBoxLayout(self)

        self.label_title = QLabel(_("Select resources"), self)
        font = QFont()
        font.setPointSize(18)
        font.setBold(True)
        self.label_title.setFont(font)
        self.label_title.setContentsMargins(2, 5, 5, 7)
        self.label_title.setStyleSheet(Style.h2())
        lbl_color = QLabel("   ", self)
        lbl_color.setStyleSheet(Style.select_title())
        hbox = QHBoxLayout()
        hbox.addWidget(lbl_color)
        hbox.addWidget(self.label_title, 1)
        self.btn_help = QPushButton(_("Help..."), self)
        self.btn_help.clicked.connect(self.on_button_help_clicked)
        hbox.addWidget(self.btn_help)
        hbox.setContentsMargins(0, 0, 0, 5)  # left, top, right, bottom
        vbl_0.addLayout(hbox)

        self.grp_simple = QGroupBox(_("Simpel selection: One directory"))
        self.grp_simple.setCheckable(True)
        self.grp_simple.toggled.connect(self.on_grp_simple_toggle)

        # simple group
        self.lbl_simple = QLabel(_("Location"))
        self.edt_simple = QLineEdit()
        self.edt_simple.editingFinished.connect(self.on_edt_simple_finished)
        vbox_simple = QVBoxLayout()
        vbox_simple.setSpacing(0)
        self.btn_simple_brws = QPushButton(_("Browse"))
        self.btn_simple_brws.clicked.connect(self.on_btn_simple_brws_clicked)
        vbox_simple.addWidget(self.btn_simple_brws)
        self.btn_simple_play = QPushButton(_("Play..."))
        self.btn_simple_play.clicked.connect(self.on_btn_simple_play_clicked)
        vbox_simple.addWidget(self.btn_simple_play)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.lbl_simple)
        hbox2.addWidget(self.edt_simple)
        hbox2.addLayout(vbox_simple)
        self.grp_simple.setLayout(hbox2)
        vbl_0.addWidget(self.grp_simple)

        self.grp_selector = QGroupBox(_("Advanced: Create a selector"))
        self.grp_selector.setCheckable(True)
        self.grp_selector.toggled.connect(self.on_grp_selector_toggle)
        grid = QGridLayout()

        # selector group: selector file
        self.lbl_saved_as = QLabel(_("Selector"))
        self.lbl_selector_file = QLabel()
        self.lbl_selector_file.setTextInteractionFlags(
            Qt.TextSelectableByMouse)
        grid.addWidget(self.lbl_saved_as, 1, 1)
        grid.addWidget(self.lbl_selector_file, 1, 2, 1, 2)

        # selector group: includes
        self.lbl_includes = QLabel(_("Includes"))
        self.lbl_includes.setAlignment(Qt.AlignTop)
        self.txt_includes = QPlainTextEdit()
        self.txt_includes.installEventFilter(self)
        self.btn_incl_directory = QPushButton(_("Add directory"))
        self.btn_incl_directory.clicked.connect(
            self.on_btn_incl_directory_clicked)
        self.btn_incl_files = QPushButton(_("Add files"))
        self.btn_incl_files.clicked.connect(self.on_btn_incl_files_clicked)
        self.btn_incl_import = QPushButton(_("Import entries"))
        self.btn_incl_import.clicked.connect(self.on_btn_incl_import_clicked)
        grid.addWidget(self.lbl_includes, 2, 1)
        grid.addWidget(self.txt_includes, 2, 2)
        vbox_inc = QVBoxLayout()
        vbox_inc.setSpacing(0)
        vbox_inc.addWidget(self.btn_incl_directory)
        vbox_inc.addWidget(self.btn_incl_files)
        vbox_inc.addWidget(self.btn_incl_import)
        vbox_inc.addStretch(1)
        grid.addLayout(vbox_inc, 2, 3)

        # selector group: excludes
        self.lbl_excludes = QLabel(_("Excludes"))
        self.lbl_excludes.setAlignment(Qt.AlignTop)
        self.txt_excludes = QPlainTextEdit()
        self.txt_excludes.installEventFilter(self)
        self.btn_excl_directory = QPushButton(_("Add directory"))
        self.btn_excl_directory.clicked.connect(
            self.on_btn_excl_directory_clicked)
        self.btn_excl_files = QPushButton(_("Add files"))
        self.btn_excl_files.clicked.connect(self.on_btn_excl_files_clicked)
        self.btn_excl_import = QPushButton(_("Import entries"))
        self.btn_excl_import.clicked.connect(self.on_btn_excl_import_clicked)
        grid.addWidget(self.lbl_excludes, 3, 1)
        grid.addWidget(self.txt_excludes, 3, 2)
        vbox_exc = QVBoxLayout()
        vbox_exc.setSpacing(0)
        vbox_exc.addWidget(self.btn_excl_directory)
        vbox_exc.addWidget(self.btn_excl_files)
        vbox_exc.addWidget(self.btn_excl_import)
        vbox_exc.addStretch(1)
        grid.addLayout(vbox_exc, 3, 3)

        # selector group: bottom buttons
        self.btn_open_selector = QPushButton(_("Open..."))
        self.btn_open_selector.clicked.connect(
            self.on_btn_open_selector_clicked)
        self.btn_save_selector_as = QPushButton(_("Save as..."))
        self.btn_save_selector_as.clicked.connect(
            self.on_btn_save_selector_as_clicked)
        self.btn_play_selected = QPushButton(_("Play..."))
        self.btn_play_selected.clicked.connect(
            self.on_btn_play_selected_clicked)
        hbox3 = QHBoxLayout()
        hbox3.addStretch(1)
        hbox3.addWidget(self.btn_open_selector)
        hbox3.addWidget(self.btn_save_selector_as)
        grid.addLayout(hbox3, 4, 1, 1, 2)
        grid.addWidget(self.btn_play_selected, 4, 3)

        self.grp_selector.setLayout(grid)
        vbl_0.addWidget(self.grp_selector)

        self.setLayout(vbl_0)
    def setupUi(self):

        grid_0 = QGridLayout()

        self.lb4 = QLabel("Active gmail account:", self)
        self.lb5 = QLabel(self.emailset_str[0], self)
        self.lb5.setStyleSheet("color: magenta")
        grid_0.addWidget(self.lb4, 0, 0)
        grid_0.addWidget(self.lb5, 0, 1)

        self.btnNewGmail = QPushButton("Register account", self)
        self.btnNewGmail.clicked.connect(self.btn_newgmail)
        self.btnNewGmail.setEnabled(False)
        grid_0.addWidget(self.btnNewGmail, 1, 0)

        self.cb_passwd = QCheckBox('Show', self)
        self.cb_passwd.toggle()
        self.cb_passwd.setChecked(True)

        grid_2 = QGridLayout()
        self.le2 = QLineEdit("username", self)
        self.le2.setFixedWidth(100)
        self.le2.textChanged.connect(self.on_text_changed2)
        self.le3 = QLineEdit("password", self)
        self.le3.setFixedWidth(100)
        #self.le3.setEchoMode(QLineEdit.Password)
        self.le3.textChanged.connect(self.on_text_changed2)
        grid_2.addWidget(self.le2, 0, 0)
        grid_2.addWidget(self.le3, 0, 1)
        grid_2.addWidget(self.cb_passwd, 0, 2)
        grid_0.addLayout(grid_2, 1, 1)

        self.lb1 = QLabel("Receiver(s) comma(,) separated:", self)
        self.le1 = QLineEdit()
        self.le1.setText(', '.join([i for i in self.emailrec_str]))
        self.le1.textChanged.connect(self.on_text_changed)
        grid_0.addWidget(self.lb1, 2, 0)
        grid_0.addWidget(self.le1, 2, 1)

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

        self.lb2 = QLabel("Send notification when scan is done?", self)
        self.cb2 = QComboBox(self)
        mylist = ["yes", "no"]
        self.cb2.addItems(mylist)
        self.cb2.setCurrentIndex(mylist.index(self.emailset_str[1]))
        grid_0.addWidget(self.lb2, 3, 0)
        grid_0.addWidget(self.cb2, 3, 1)

        self.lb3 = QLabel("Send data when scan is done?", self)
        self.cb3 = QComboBox(self)
        self.cb3.addItems(mylist)
        self.cb3.setCurrentIndex(mylist.index(self.emailset_str[2]))
        grid_0.addWidget(self.lb3, 4, 0)
        grid_0.addWidget(self.cb3, 4, 1)

        if self.emailset_str[2] == "yes":
            self.emailset_str[1] = "no"
            self.cb2.setCurrentIndex(mylist.index("no"))
            self.cb2.setEnabled(False)
            self.save_()
        elif self.emailset_str[2] == "no":
            self.cb2.setEnabled(True)

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

        self.btnSave = QPushButton("Changes saved", self)
        self.btnSave.clicked.connect(self.btn_accepted)
        self.btnSave.setEnabled(False)

        grid_1 = QGridLayout()
        grid_1.addWidget(self.btnSave, 0, 0)

        self.cb2.activated[str].connect(self.onActivated2)
        self.cb3.activated[str].connect(self.onActivated3)
        self.cb_passwd.toggled.connect(self.passwd)

        v0 = QVBoxLayout()
        v0.addLayout(grid_0)
        v0.addLayout(grid_1)

        self.setLayout(v0)
        self.setWindowTitle("E-mail settings")
Example #45
0
    def __init__(self):
        QDialog.__init__(self)
        self.resize(230, 150)
        self.setWindowTitle("Info")

        main_grid = QGridLayout(self)
        build_grid = QGridLayout(self)
        link_grid = QGridLayout(self)
        version_grid = QGridLayout(self)

        # Title
        lbl_title = QLabel(self)
        font = QFont()
        font.setPointSize(16)
        lbl_title.setFont(font)
        lbl_title.setText("GeODin QGIS 1.2")

        # GeODin Icon
        i_geodin = QLabel(self)
        i_geodin.setPixmap(
            QPixmap(":\plugins\GeODinQGIS\icons\logo.png").scaled(40, 40))

        # Fugro Icon
        i_fugro = QLabel(self)
        i_fugro.setPixmap(
            QPixmap(":\plugins\GeODinQGIS\icons\fugro.png").scaled(70, 70))

        # enter registry and get GeODin build number
        key = OpenKey(HKEY_CURRENT_USER, r"Software\GeODin-System\System", 0,
                      KEY_READ)
        build, dummy = QueryValueEx(key, 'Build')
        CloseKey(key)

        lbl_build = QLabel(self)
        lbl_build.setText("Build number:")

        lbl_number = QLabel(self)
        lbl_number.setText(build)

        # add URL's to GeODin and Fugro websites
        link_geodin = QLabel(self)
        link_geodin.setText(
            '''<a href='http://www.geodin.com'>http://www.geodin.com</a>''')
        link_geodin.setOpenExternalLinks(True)

        link_fugro = QLabel(self)
        link_fugro.setText(
            '''<a href='http://www.fugro.de'>http://www.fugro.de</a>''')
        link_fugro.setOpenExternalLinks(True)

        lbl_version1 = QLabel(self)
        lbl_version1.setText("Full functionality only with GeODin 8.2")
        lbl_version2 = QLabel(self)

        # Ok-Button to exit
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Ok)
        buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.ok)

        main_grid.addWidget(i_geodin, 0, 0)
        main_grid.addWidget(lbl_title, 0, 1)
        main_grid.addWidget(QLabel(self), 1, 0)
        main_grid.addWidget(i_fugro, 2, 0)
        main_grid.addWidget(buttonBox, 4, 1)

        build_grid.addWidget(lbl_build, 0, 0)
        build_grid.addWidget(lbl_number, 0, 1)

        link_grid.addWidget(link_geodin, 0, 0)
        link_grid.addWidget(link_fugro, 1, 0)

        version_grid.addWidget(lbl_version1, 0, 0)
        version_grid.addWidget(lbl_version2, 1, 0)

        main_grid.addLayout(build_grid, 1, 1)
        main_grid.addLayout(link_grid, 2, 1)
        main_grid.addLayout(version_grid, 3, 1)

        self.exec_()
class CargaFacturaProveedorView(Formulario):

    def __init__(self, *args, **kwargs):
        Formulario.__init__(self)
        self.setupUi(self)

    def setupUi(self, Form):
        self.setWindowTitle("Carga facturas de proveedor")

        self.layoutPpal = QVBoxLayout(Form)
        self.lblTitulo = EtiquetaTitulo(texto=self.windowTitle())
        self.layoutPpal.addWidget(self.lblTitulo)

        self.gridLayout = QGridLayout()
        self.lblCodigoProv = Etiqueta(texto="Proveedor")
        self.textProveedor = Proveedores.Valida()
        self.lblNombProv = Etiqueta()
        self.textProveedor.widgetNombre = self.lblNombProv
        self.gridLayout.addWidget(self.lblCodigoProv, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.textProveedor, 0, 1, 1, 1)
        self.gridLayout.addWidget(self.lblNombProv, 0, 2, 1, 1)

        self.lblCodTipoComp = Etiqueta(texto="Tipo comprobante")
        self.textTipoComp = Tipocomprobantes.Valida()
        self.lblNomTipoComp = Etiqueta()
        self.textTipoComp.widgetNombre = self.lblNomTipoComp
        self.gridLayout.addWidget(self.lblCodTipoComp, 1, 0, 1, 1)
        self.gridLayout.addWidget(self.textTipoComp, 1, 1, 1, 1)
        self.gridLayout.addWidget(self.lblNomTipoComp, 1, 2, 1, 1)

        self.lblFactura = Etiqueta(texto='Numero')
        self.textFactura = Factura()
        self.gridLayout.addWidget(self.lblFactura, 1, 3, 1, 1)
        self.gridLayout.addLayout(self.textFactura, 1, 4, 1, 1)

        self.lblFechaCarga = Etiqueta(texto="Fecha Carga")
        self.fechaCarga = Fecha()
        self.fechaCarga.setFecha()
        self.gridLayout.addWidget(self.lblFechaCarga, 2, 0, 1, 1)
        self.gridLayout.addWidget(self.fechaCarga, 2, 1, 1, 1)

        self.lblFechaEm = Etiqueta(texto="Fecha Emision")
        self.fechaEmision = Fecha()
        self.fechaEmision.setFecha()
        self.gridLayout.addWidget(self.lblFechaEm, 2, 3, 1, 1)
        self.gridLayout.addWidget(self.fechaEmision, 2, 4, 1, 1)

        self.lblPeriodo = Etiqueta(texto="Periodo")
        self.periodo = Periodo()
        self.gridLayout.addWidget(self.lblPeriodo, 2, 5, 1, 1)
        self.gridLayout.addLayout(self.periodo, 2, 6, 1, 1)

        self.lblModoCpte = Etiqueta(texto="Modo comprobante")
        self.cboModoCpte = ComboConstComp()
        self.gridLayout.addWidget(self.lblModoCpte, 3, 0, 1, 1)
        self.gridLayout.addWidget(self.cboModoCpte, 3, 1, 1, 1)

        self.lblCAE = Etiqueta(texto='CAE/CAI')
        self.textCAE = EntradaTexto(placeholderText='CAE/CAI')
        self.gridLayout.addWidget(self.lblCAE, 3, 2, 1, 1)
        self.gridLayout.addWidget(self.textCAE, 3, 3, 1, 1)
        self.layoutPpal.addLayout(self.gridLayout)

        self.gridDatos = GrillaFactProv()
        self.layoutPpal.addWidget(self.gridDatos)

        self.gridTotales = QGridLayout()
        self.lblExentos = Etiqueta(texto="Exentos")
        self.textExentos = EntradaTexto(placeholderText="Exentos")
        self.gridTotales.addWidget(self.lblExentos, 0, 0)
        self.gridTotales.addWidget(self.textExentos, 0, 1)
        lblInternos = Etiqueta(texto="Imp. Internos")
        self.textInternos = EntradaTexto(placeholderText="Imp. Internos")
        self.gridTotales.addWidget(lblInternos, 0, 2)
        self.gridTotales.addWidget(self.textInternos, 0, 3)
        self.lblNeto = Etiqueta(texto="Netos")
        self.textNeto = EntradaTexto(enabled=False, placeholderText="Neto")
        self.gridTotales.addWidget(self.lblNeto, 0, 4)
        self.gridTotales.addWidget(self.textNeto, 0, 5)

        self.lblNoGravado = Etiqueta(texto="No gravados")
        self.textNoGravado = EntradaTexto(placeholderText="No gravados")
        self.gridTotales.addWidget(self.lblNoGravado, 1, 0)
        self.gridTotales.addWidget(self.textNoGravado, 1, 1)
        self.lblPercepcionDGR = Etiqueta(texto="Percepcion DGR")
        self.textPercepcionDGR = EntradaTexto(placeholderText="Percepcion DGR", enabled=False)
        self.gridTotales.addWidget(self.lblPercepcionDGR, 1, 2)
        self.gridTotales.addWidget(self.textPercepcionDGR, 1, 3)
        self.lblIVA = Etiqueta(texto="IVA")
        self.textIVA = EntradaTexto(enabled=False)
        self.gridTotales.addWidget(self.lblIVA, 1, 4)
        self.gridTotales.addWidget(self.textIVA, 1, 5)

        self.lblPercepcionIVA = Etiqueta(texto="Percepcion IVA")
        self.textPercepcionIVA = EntradaTexto(placeholderText="Percepcion IVA")
        self.gridTotales.addWidget(self.lblPercepcionIVA, 2, 0)
        self.gridTotales.addWidget(self.textPercepcionIVA, 2, 1)
        self.lblTotal = Etiqueta(texto="Total")
        self.textTotal = EntradaTexto(enabled=False)
        self.gridTotales.addWidget(self.lblTotal, 2, 4)
        self.gridTotales.addWidget(self.textTotal, 2, 5)

        self.layoutPpal.addLayout(self.gridTotales)

        self.layoutBotones = QHBoxLayout()
        self.btnGrabar = Boton(texto="Grabar", imagen='imagenes/if_save.png', autodefault=False, enabled=False)
        self.btnConstatacion = Boton(texto="Constatacion", imagen="imagenes/logoafipfondoblanco.png",
                                     autodefault=False, enabled=False)
        self.btnPercepDGR = Boton(texto="Percepcion DGR", imagen='imagenes/dgr-misiones.png',
                                  enabled=False, autodefault=False)
        self.btnCerrar = BotonCerrarFormulario(autodefault=False)
        self.layoutBotones.addWidget(self.btnGrabar)
        self.layoutBotones.addWidget(self.btnPercepDGR)
        self.layoutBotones.addWidget(self.btnConstatacion)
        self.layoutBotones.addWidget(self.btnCerrar)
        self.layoutPpal.addLayout(self.layoutBotones)
Example #47
0
class init_GUI(QWidget):
    def __init__(self, parent=None):
        super(init_GUI, self).__init__(parent)
        self.font_header = QFont("Arial", 32)
        self.font_sub_header = QFont("Arial", 16)
        self.font_left_col = QFont("Arial", 16)

        self.stack = stack

        self.filepath_sfns = ""
        self.filepath_sfns_folder = ""
        self.filepath_img = ""
        self.filepath_img_folder = ""

        self.initUI()

    def initUI(self):
        # Set Layout and Geometry of Window
        self.grid_top = QGridLayout()
        self.grid_body = QGridLayout()

        #self.setFixedSize(800, 350)
        self.resize(800, 350)

        ### Grid TOP (1 row) ###
        # Static Text Field
        self.e1 = QLineEdit()
        self.e1.setValidator(QIntValidator())
        self.e1.setAlignment(Qt.AlignCenter)
        self.e1.setFont(self.font_header)
        self.e1.setReadOnly(True)
        self.e1.setText("Select File Locations")
        self.e1.setFrame(False)
        self.grid_top.addWidget(self.e1, 0, 0)
        # Static Text Field
        self.e1 = QTextEdit()
        self.e1.setFont(self.font_sub_header)
        self.e1.setReadOnly(True)
        self.e1.setText(
            "You must select your sorted filenames (.txt) file created for " +
            self.stack +
            ". This must be a text file formatted as described in the github page.\n"
            +
            "Your raw image files are expected to be in TIFF format and must all be "
            +
            "located inside the same directory. Each filename in the sorted filenames must "
            + "appear in the filename of a raw image file.")
        self.grid_top.addWidget(self.e1, 1, 0)

        ### Grid BODY (1 row) ###
        # Static Text Field
        self.e2 = QLineEdit()
        self.e2.setValidator(QIntValidator())
        self.e2.setAlignment(Qt.AlignRight)
        self.e2.setFont(self.font_left_col)
        self.e2.setReadOnly(True)
        self.e2.setText("Select sorted_filenames.txt file:")
        self.e2.setFrame(False)
        self.grid_body.addWidget(self.e2, 0, 0)
        # Static Text Field
        self.e3 = QLineEdit()
        self.e3.setValidator(QIntValidator())
        #self.e3.setMaxLength(50)
        self.e3.setAlignment(Qt.AlignRight)
        self.e3.setFont(self.font_left_col)
        self.e3.setReadOnly(True)
        self.e3.setText("Select raw jp2 or tiff files:")
        self.e3.setFrame(False)
        self.grid_body.addWidget(self.e3, 1, 0)

        # Button Text Field
        self.b2 = QPushButton("Select sorted filenames")
        self.b2.setDefault(True)
        self.b2.clicked.connect(lambda: self.buttonPress_selectSFS(self.b2))
        self.b2.setStyleSheet(
            'QPushButton {background-color: #A3C1DA; color: black;}')
        self.grid_body.addWidget(self.b2, 0, 1)
        # Button Text Field
        self.b3 = QPushButton("Select one image file")
        self.b3.setDefault(True)
        self.b3.clicked.connect(lambda: self.buttonPress_selectIMG(self.b3))
        self.b3.setStyleSheet(
            'QPushButton {background-color: #A3C1DA; color: black;}')
        self.grid_body.addWidget(self.b3, 1, 1)

        # Static Text Field
        self.e7 = QLineEdit()
        self.e7.setValidator(QIntValidator())
        self.e7.setAlignment(Qt.AlignRight)
        self.e7.setFont(self.font_left_col)
        self.e7.setReadOnly(True)
        self.e7.setText("Push `Submit` when finished")
        self.e7.setFrame(False)
        self.grid_body.addWidget(self.e7, 6, 0)
        # Button Text Field
        self.b1 = QPushButton("Submit")
        self.b1.setDefault(True)
        self.b1.clicked.connect(lambda: self.buttonPressSubmit(self.b1))
        self.grid_body.addWidget(self.b1, 6, 1)

        #self.grid_top.setColumnStretch(1, 3)
        #self.grid_top.setRowStretch(1, 3)

        ### SUPERGRID ###
        self.supergrid = QGridLayout()
        self.supergrid.addLayout(self.grid_top, 0, 0)
        self.supergrid.addLayout(self.grid_body, 1, 0)

        # Set layout and window title
        self.setLayout(self.supergrid)
        self.setWindowTitle("Select tiffs/jp2 images")

    def validateEntries(self):
        if self.filepath_sfns == "" or self.filepath_img == "":
            print('No filepath_sfns or filepath_img')
            return False

        return True

    def buttonPressSubmit(self, button):
        if button == self.b1:
            validated = self.validateEntries()
            if validated:
                # Create parent folders if necessary
                create_parent_folder_for_files(self.stack)

                # Copy over sorted filenames if it was selected
                if self.filepath_sfns == "":
                    pass
                else:
                    # Copy sorted filenames file to proper lcoation
                    copy_over_sorted_filenames(self.stack, self.filepath_sfns)

                # Copy image files to proper location
                if '.jp2' in self.filepath_img:
                    self.e1.setText(
                        "The jp2 images are being converted and copied, " +
                        "The process is expected to take 60-90 seconds per image.\n\n"
                        + "Please revisit this GUI in a few hours.")
                    self.e1.repaint()
                    copy_over_jp2_files(self.stack, self.filepath_img,
                                        self.filepath_img_folder)
                elif '.tif' in self.filepath_img:
                    self.e1.setText(
                        "The tiff images are now being copied. This will take about 30s - 1m per image."
                    )
                    self.e1.repaint()
                    copy_over_tif_files(self.stack)

                self.finished()

    def buttonPress_selectSFS(self, button):
        if button == self.b2:
            fp = get_selected_fp(
                default_filetype=[("text files", "*.txt"), ("all files",
                                                            "*.*")])
            self.filepath_sfns = fp
            self.filepath_sfns_folder = fp[0:max(loc
                                                 for loc, val in enumerate(fp)
                                                 if val == '/')]
            validated, err_msg = validate_sorted_filenames(fp)
            if validated:
                self.e2.setText(fp)
            else:
                self.e2.setText(err_msg)
                self.filepath_sfns = ""

    def buttonPress_selectIMG(self, button):
        if button == self.b3:
            if self.filepath_sfns_folder != '':
                fp = get_selected_fp(initialdir=self.filepath_sfns_folder,
                                     default_filetype=[("tiff files",
                                                        "*.tif*"),
                                                       ("jp2 files", "*.jp2"),
                                                       ("all files", "*.*")])
            else:
                fp = get_selected_fp(default_filetype=[(
                    "tiff files", "*.tif*"), ("jp2 files",
                                              "*.jp2"), ("all files", "*.*")])
            self.filepath_img = fp
            self.filepath_img_folder = fp[0:max(loc
                                                for loc, val in enumerate(fp)
                                                if val == '/')]
            #validate_chosen_images()
            self.e3.setText(self.filepath_img_folder)

    def closeEvent(self, event):
        #close_main_gui( ex )
        sys.exit(app.exec_())

    def finished(self):
        #if self.filepath_sfns != "":
        #set_step_completed_in_progress_ini( stack, '1-4_setup_sorted_filenames')

        subprocess.call([
            'python', 'utilities/a_script_preprocess_setup.py', stack,
            'unknown'
        ])

        set_step_completed_in_progress_ini(stack, '1-2_setup_images')

        close_gui()
Example #48
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.minimize_to_tray = True
        self.alarm = AlarmDaemon(self)

        # Window definitions
        self.setMinimumSize(QSize(480, 320))
        self.setWindowTitle("AthanPy")
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")

        # Layout definitions
        self.gridLayout_2 = QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")

        # Widget definitions
        #self.txt_times = QLabel(self.centralwidget)
        #sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        #sizePolicy.setHorizontalStretch(0)
        #sizePolicy.setVerticalStretch(0)
        #sizePolicy.setHeightForWidth(self.txt_times.sizePolicy().hasHeightForWidth())
        #self.txt_times.setSizePolicy(sizePolicy)
        #self.txt_times.setAlignment(Qt.AlignCenter)
        #self.txt_times.setObjectName("txt_times")
        #self.txt_times.setText(self.get_prayertime_text())
        #self.gridLayout.addWidget(self.txt_times, 1, 0, 1, 1)
        self.lbl_prayername = {}
        self.lbl_prayertime = {}
        i = 1
        for n in [
                'Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha',
                'Midnight'
        ]:
            self.lbl_prayername[n] = QLabel(self.centralwidget)
            self.lbl_prayername[n].setAlignment(Qt.AlignLeft)
            self.lbl_prayername[n].setText(n)
            self.gridLayout.addWidget(self.lbl_prayername[n], i, 0, 1, 1)

            self.lbl_prayertime[n] = QLabel(self.centralwidget)
            self.lbl_prayertime[n].setAlignment(Qt.AlignCenter)
            self.gridLayout.addWidget(self.lbl_prayertime[n], i, 1, 1, 1)
            i += 1
        self.set_prayertime()

        self.txt_date = QLabel(self.centralwidget)
        self.txt_date.setObjectName("txt_date")
        self.gridLayout.addWidget(self.txt_date, 0, 0, 1, 2)
        self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)

        # Menu bar
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 480, 20))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.setMenuBar(self.menubar)

        # Status bar
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.actionSettings = QAction(self)
        self.actionSettings.setObjectName("actionSettings")
        self.actionSettings.setText("Settings")
        self.actionSettings.triggered.connect(self.show_settings)

        self.actionQuit = QAction(self)
        self.actionQuit.setObjectName("actionQuit")
        self.actionQuit.setText("Quit")
        self.actionQuit.triggered.connect(qApp.quit)

        self.menuFile.addAction(self.actionSettings)
        self.menuFile.addAction(self.actionQuit)
        self.menuFile.setTitle("File")

        self.menubar.addAction(self.menuFile.menuAction())

        # QSystemTrayIcon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.style().standardIcon(
            QStyle.SP_ComputerIcon))

        show_action = QAction("Show", self)
        hide_action = QAction("Hide", self)
        mute_action = QAction("Mute sound", self)
        stopsound_action = QAction("Stop sound", self)
        quit_action = QAction("Quit", self)

        show_action.triggered.connect(self.show)
        hide_action.triggered.connect(self.hide)
        mute_action.setCheckable(True)
        mute_action.changed.connect(
            lambda: self.alarm.set_mute(mute_action.isChecked()))
        stopsound_action.triggered.connect(self.alarm.stop_sound)
        quit_action.triggered.connect(QCoreApplication.quit)

        tray_menu = QMenu()
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addSeparator()
        tray_menu.addAction(stopsound_action)
        tray_menu.addAction(mute_action)
        tray_menu.addSeparator()
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()

        # Settings window
        self.settingswindow = SettingsWindow(self)

    def closeEvent(self, event):
        if self.minimize_to_tray:
            print('triggered 1')
            event.ignore()
            self.hide()
            self.tray_icon.showMessage("Tray Program",
                                       "Application was minimized to tray",
                                       QSystemTrayIcon.Information, 2000)

    def set_prayertime(self):
        SettingsManager.refreshVariables(self.show_settings)
        SettingsManager.calcTimes()

        times = SettingsManager.times
        # For testing purposes, comment/delete when not in use
        #times['dhuhr'] = '08:02'
        #times['asr'] = '08:03'
        #        times['isha'] = '16:20'
        for n in [
                'Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha',
                'Midnight'
        ]:
            self.lbl_prayertime[n].setText(times[n.lower()])

        self.alarm.stop_alarm()
        self.alarm.schedule_alarm(times)
        self.alarm.start()
        #return output

    def show_settings(self):
        self.settingswindow.show()
Example #49
0
class QUnFrameWindow(QWidget):
    def __init__(self):
        global apptitle
        super(QUnFrameWindow,
              self).__init__(None, Qt.FramelessWindowHint)  # 设置为顶级窗口,无边框
        self._padding = 5  # 设置边界宽度为5
        #self.setAttribute(Qt.WA_TranslucentBackground)
        self.SHADOW_WIDTH = 8
        self.setWindowTitle(apptitle)
        self.initLayout()  # 设置框架布局
        #self.setMinimumSize(900,700)
        self.setMouseTracking(True)  # 设置widget鼠标跟踪
        self.initDrag()  # 设置鼠标跟踪判断默认值
        self.file = QtCore.QFile(qssfile)
        self.file.open(QtCore.QFile.ReadOnly)
        self.styleSheet = self.file.readAll()
        self.styleSheet = unicode(self.styleSheet, encoding='utf8')
        self.setStyleSheet(self.styleSheet)
        # self.setStyleSheet(open(qssfile).read())

        self.setMinimumSize(windowminW, windowminH)
        self.setContentsMargins(8, 8, 8, 8)
        self.setCloseButton(True)
        self.setMinMaxButtons(True)
        self.center()

    #------------------------------------绘制边框阴影
    def drawShadow(self, painter):
        #print('ddddddddddddddddddd')
        #绘制左上角、左下角、右上角、右下角、上、下、左、右边框
        #print(self._tomax_drag)
        self.pixmaps = []
        if imax == 0:
            if self._tomax_drag == False:
                self.pixmaps = [
                    ':/shadow/shadow_left_top.png',
                    ':/shadow/shadow_left_bottom.png',
                    ':/shadow/shadow_right_top.png',
                    ':/shadow/shadow_right_bottom.png',
                    ':/shadow/shadow_top.png', ':/shadow/shadow_bottom.png',
                    ':/shadow/shadow_left.png', ':/shadow/shadow_right.png'
                ]
            else:
                # print('yyyy')
                self.pixmaps = [
                    ':/shadow/shadow_left_top_m.png',
                    ':/shadow/shadow_left_bottom_m.png',
                    ':/shadow/shadow_right_top_m.png',
                    ':/shadow/shadow_right_bottom_m.png',
                    ':/shadow/shadow_top_m.png',
                    ':/shadow/shadow_bottom_m.png',
                    ':/shadow/shadow_left_m.png', ':/shadow/shadow_right_m.png'
                ]

            painter.drawPixmap(0, 0, self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[0]))  #左上角
            # print(self.pixmaps,self._tomax_drag,'P')
            painter.drawPixmap(self.width() - self.SHADOW_WIDTH, 0,
                               self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[2]))  #右上角
            painter.drawPixmap(0,
                               self.height() - self.SHADOW_WIDTH,
                               self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[1]))  #左下角
            painter.drawPixmap(self.width() - self.SHADOW_WIDTH,
                               self.height() - self.SHADOW_WIDTH,
                               self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[3]))  #右下角
            painter.drawPixmap(0, self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                               self.height() - 2 * self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[6]).scaled(
                                   self.SHADOW_WIDTH,
                                   self.height() - 2 * self.SHADOW_WIDTH))  #左
            painter.drawPixmap(self.width() - self.SHADOW_WIDTH,
                               self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                               self.height() - 2 * self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[7]).scaled(
                                   self.SHADOW_WIDTH,
                                   self.height() - 2 * self.SHADOW_WIDTH))  #右
            painter.drawPixmap(self.SHADOW_WIDTH, 0,
                               self.width() - 2 * self.SHADOW_WIDTH,
                               self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[4]).scaled(
                                   self.width() - 2 * self.SHADOW_WIDTH,
                                   self.SHADOW_WIDTH))  #上
            painter.drawPixmap(self.SHADOW_WIDTH,
                               self.height() - self.SHADOW_WIDTH,
                               self.width() - 2 * self.SHADOW_WIDTH,
                               self.SHADOW_WIDTH,
                               QPixmap(self.pixmaps[5]).scaled(
                                   self.width() - 2 * self.SHADOW_WIDTH,
                                   self.SHADOW_WIDTH))  #下

    #------------------------------------绘制边框阴影
    def paintEvent(self, event):
        global movenum, infobgimgwidth, infobgimgheight, infobgimg
        # if imax == 0:
        painter = QPainter(self)
        # print('rrrrrrrrrrrrr')
        self.drawShadow(painter)
        # print('444444444')
        painter.setPen(Qt.NoPen)
        painter.setBrush(Qt.white)
        painter.drawRect(
            QRect(self.SHADOW_WIDTH, self.SHADOW_WIDTH,
                  self.width() - 2 * self.SHADOW_WIDTH,
                  self.height() - 2 * self.SHADOW_WIDTH))
        painter.end()

        if imax == 0:
            movenum = 8
        elif imax == 1:
            movenum = 0
        painter1 = QPainter(self)
        # painter1.begin(self)
        painter1.setRenderHint(QPainter.Antialiasing)
        painter1.setPen(Qt.NoPen)
        painter1.drawPixmap(movenum, movenum, infobgimgwidth, titleheight,
                            QPixmap(infobgimg))
        painter1.end()

    # 设置鼠标跟踪判断扳机默认值
    def initDrag(self):
        #为FALSE时代表未有相关动作状态
        self._move_drag = False  #针对是否是在最大化状态时拖动状态的标记,为True时代表正在按压拖动中,用来一次性重新定位窗体在恢复窗口后鼠标拖拽的位置(宽度居中,标题图片一般高度,move方法中)
        self._corner_drag = False
        self._bottom_drag = False
        self._right_drag = False
        self._maxmove_drag = False
        self._tomax_drag = False

    # def initTitleLabel(self):
    # #     # 安放标题栏标签
    #     self._TileLabel = QTitleLabel(self)
    #     #self._TitleLabel.setMouseTracking(True) # 设置标题栏标签鼠标跟踪(如不设,则标题栏内在widget上层,无法实现跟踪)
    #     self._TitleLabel.setIndent(10) # 设置标题栏文本缩进
    #     #self._TitleLabel.move(0, 0) # 标题栏安放到左上角

    def initLayout(self):
        # 设置框架布局
        global numbinfo, titleheight, infobgimgwidth, infotopwidth, infoIndent, infofont, appicon, titleimg, webkiturl

        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setWindowIcon(QIcon(appicon))
        #添加整体窗体大布局框架
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName("gridLayout")

        #在整体框架里添加竖排layout
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 0, 0)

        #在竖排框架里上方生成一个横排放用户信息和标题栏
        self.horizontalLayout_1 = QHBoxLayout()
        self.horizontalLayout_1.setContentsMargins(0, 0, 0, 0)  #浏览器右下方留出拖拽空间
        self.horizontalLayout_1.setObjectName("horizontalLayout1")
        self.verticalLayout.addLayout(self.horizontalLayout_1)

        if numbinfo == 1:  #如果允许显示用户信息区
            # ---------用户信息区框架及里面所有内容
            # 在上方横排里添加竖排layout,放用户信息
            self.verticalLayout_1 = QVBoxLayout()
            self.verticalLayout_1.setContentsMargins(0, 0, 0, 0)

            self.verticalLayout_1.setObjectName("verticalLayout_1")
            # 把竖向框架嵌入到顶部横向框架里
            self.horizontalLayout_1.addLayout(self.verticalLayout_1)

            #添加一个固定宽的label,用于把信息区的宽度撑开
            self.wlab = QTitleLabel()
            self.wlab.setScaledContents(False)
            self.wlab.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self.wlab.setStyleSheet(
                "QTitleLabel{font-size:20px;background-color:rgba(255, 255, 255, 0);}"
            )
            self.wlab.setMinimumWidth(infobgimgwidth)
            self.wlab.setMaximumHeight(infotopwidth)
            #在信息区的竖向框架里添加Wlab,用户名密级横排框架,下面就是账号、部门等label
            self.verticalLayout_1.addWidget(self.wlab)  #用wlab撑开信息区的宽度

            # 在用户信息区放置一个横排框架,横向放置用户名和密级信息
            self.horizontalLayout_2 = QHBoxLayout()
            self.horizontalLayout_2.setContentsMargins(0, 0, 0,
                                                       0)  # 浏览器右下方留出拖拽空间
            self.horizontalLayout_2.setObjectName("horizontalLayout2")
            self.verticalLayout_1.addLayout(self.horizontalLayout_2)

            #信息区的横向框架里放置姓名和密级
            self.namelab = QTitleLabel()
            sizePolicy = QSizePolicy(QSizePolicy.Preferred,
                                     QSizePolicy.Preferred)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                self.namelab.sizePolicy().hasHeightForWidth())
            self.namelab.setSizePolicy(sizePolicy)
            self.namelab.setMinimumSize(QSize(0, 0))
            self.namelab.setObjectName("namelab")
            self.namelab.setScaledContents(False)
            self.namelab.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self.namelab.setStyleSheet(
                "QTitleLabel{ font-size:22px;background-color: rgba(255,255,255,0);}"
            )
            self.namelab.setIndent(infoIndent)
            self.namelab.setFont(QFont(infofont))
            self.namelab.setFixedHeight(24)
            # self.namelab.setAlignment(Qt.AlignTop)
            self.namelab.setText('')
            self.horizontalLayout_2.addWidget(self.namelab, 0, Qt.AlignBottom)

            #姓名后面放个空label间隔姓名和密级
            self.konglab1 = QTitleLabel()
            self.konglab1.setFixedWidth(5)
            self.konglab1.setObjectName("konglab1")

            self.konglab1.setText("")
            self.konglab1.setStyleSheet(
                "QTitleLabel{font-size:18px;background-color:rgba(255,255,255,0);}"
            )
            self.horizontalLayout_2.addWidget(self.konglab1)

            #后面跟着密级标签
            self.mijilab = QTitleLabel()
            self.mijilab.setScaledContents(False)
            self.mijilab.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                self.mijilab.sizePolicy().hasHeightForWidth())
            self.mijilab.setSizePolicy(sizePolicy)
            self.mijilab.setObjectName("mijilab")
            self.mijilab.setText('')
            self.mijilab.setAlignment(Qt.AlignTop)
            self.mijilab.setFont(QFont(infofont))
            self.mijilab.setStyleSheet(
                "QTitleLabel{border-width: 0px 0px 0px 0px;border-radius:3px;border-color:#b90101; font-size:12px;border-style: solid;background-color: #b90101;}"
            )
            self.mijilab.setFixedHeight(17)
            self.horizontalLayout_2.addWidget(self.mijilab, 0, Qt.AlignBottom)

            #后面跟着空label,让姓名和密级标签的宽度已最小化方式呈现
            self.konglab2 = QTitleLabel()
            sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                self.konglab2.sizePolicy().hasHeightForWidth())
            self.konglab2.setSizePolicy(sizePolicy)
            self.konglab2.setMinimumSize(QSize(0, 0))
            self.konglab2.setStyleSheet(
                "QTitleLabel{background-color: rgba(255,255,255,0);}")
            #self.konglab2.setFixedSize(self.wlab.width()-self.namelab.width()-self.konglab1.width()-self.mijilab.width(),10)
            self.konglab2.setText("")

            self.konglab2.setObjectName("konglab2")
            self.horizontalLayout_2.addWidget(self.konglab2)

            #在用户名和密级下添加竖排的账号信息
            self.numblab = QTitleLabel()
            sizePolicy = QSizePolicy(QSizePolicy.Preferred,
                                     QSizePolicy.Preferred)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                self.numblab.sizePolicy().hasHeightForWidth())
            self.numblab.setSizePolicy(sizePolicy)
            self.numblab.setMinimumSize(QSize(0, 0))
            self.numblab.setObjectName("namelab")
            self.numblab.setScaledContents(False)
            self.numblab.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self.numblab.setStyleSheet(
                "QTitleLabel{ font-size:11px;background-color: rgba(255,255,255,0);}"
            )
            self.numblab.setIndent(infoIndent)
            #self.numblab.setAlignment(Qt.AlignBottom)
            self.numblab.setFont(QFont(infofont))
            self.numblab.setText('')
            self.numblab.setFixedSize(infobgimgwidth, 19)
            self.verticalLayout_1.addWidget(self.numblab, 0, Qt.AlignBottom)

            #在用户名和密级下添加竖排的部门信息
            self.bumenlab = QTitleLabel()
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Minimum)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                self.bumenlab.sizePolicy().hasHeightForWidth())
            self.bumenlab.setSizePolicy(sizePolicy)
            self.bumenlab.setMinimumSize(QSize(0, 0))
            self.bumenlab.setObjectName("bumenlab")
            self.bumenlab.setScaledContents(False)
            self.bumenlab.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self.bumenlab.setStyleSheet(
                "QTitleLabel{ font-size:4px;background-color: rgba(255,255,255,0);}"
            )
            self.bumenlab.setIndent(infoIndent)
            #self.bumenlab.setAlignment(Qt.AlignTop)
            self.bumenlab.setFont(QFont(infofont))
            self.bumenlab.setText('')
            self.bumenlab.setFixedWidth(infobgimgwidth)
            self.verticalLayout_1.addWidget(self.bumenlab)


#-----------------------------添加标题栏图片标签
        self.label = QTitleLabel()
        self.label.setScaledContents(False)
        self.label.setPixmap(QPixmap(titleimg))
        # 设置title标签在布局中是自适应宽度的
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        # 设置title标签高度,无间隙
        self.label.setFixedHeight(titleheight)
        self.label.setContentsMargins(0, 0, 0, 0)
        self.label.setMouseTracking(True)
        #接着把title标签嵌入到顶部横向框架里
        self.horizontalLayout_1.addWidget(self.label)

        #---------------在上方整体的横排之下再排生成一个横排放浏览器
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)  #浏览器右下方留出拖拽空间
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout.addLayout(self.horizontalLayout)

        #生成一个浏览器组件,添加到下方的横排layout
        self.webEngineView = QWebView()
        self.webEngineView.load(QUrl(webkiturl))
        self.webEngineView.setObjectName('webEngineView')
        self.webEngineView.setContentsMargins(0, 0, 0, 0)
        self.webEngineView.setMaximumSize(QSize(10000, 10000))
        self.webEngineView.setMouseTracking(True)
        self.horizontalLayout.addWidget(self.webEngineView)

    def closeEvent(self, event):
        try:
            reply = QMessageBox.question(self, '提示', "确认退出?", QMessageBox.Yes,
                                         QMessageBox.No)
            #print(reply == QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                event.accept()
                # self.close()
            else:
                event.ignore()
        except:
            pass

    def changeinfo(self, nametxt, juese, numb):
        global numbinfo
        if numbinfo == 1:
            self.namelab.setText(nametxt[0:4])
            self.mijilab.setText(' ' + juese[0:6] + ' ')
            self.numblab.setText(numb[0:50])
            # self.bumenlab.setText(bumen[0:20])

    def setCloseButton(self, bool):
        # 给widget定义一个setCloseButton函数,为True时设置一个关闭按钮
        if bool == True:
            self._CloseButton = QTitleButton(b'\xef\x81\xb2'.decode("utf-8"),
                                             self)
            self._CloseButton.setObjectName(
                "CloseButton")  # 设置按钮的ObjectName以在qss样式表内定义不同的按钮样式
            self._CloseButton.setToolTip("关闭窗口")
            self._CloseButton.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self._CloseButton.setFixedHeight(40)

            #self._CloseButton.setFixedHeight(self._TitleLabel.height()) # 设置按钮高度为标题栏高度
            self._CloseButton.clicked.connect(self.close)  # 按钮信号连接到关闭窗口的槽函数

    def setMinMaxButtons(self, bool):
        # 给widget定义一个setMinMaxButtons函数,为True时设置一组最小化最大化按钮
        if bool == True:
            self._MinimumButton = QTitleButton(b'\xef\x80\xb0'.decode("utf-8"),
                                               self)
            self._MinimumButton.setObjectName(
                "MinMaxButton")  # 设置按钮的ObjectName以在qss样式表内定义不同的按钮样式
            self._MinimumButton.setToolTip("最小化")
            self._MinimumButton.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self._MinimumButton.setFixedHeight(40)  # 设置按钮高度为标题栏高度
            #self._MinimumButton.setFixedHeight(self._TitleLabel.height()) # 设置按钮高度为标题栏高度
            self._MinimumButton.clicked.connect(
                self.showMinimized)  # 按钮信号连接到最小化窗口的槽函数
            self._MaximumButton = QTitleButton(b'\xef\x80\xb1'.decode("utf-8"),
                                               self)
            self._MaximumButton.setObjectName(
                "MinMaxButton")  # 设置按钮的ObjectName以在qss样式表内定义不同的按钮样式
            self._MaximumButton.setToolTip("最大化")
            self._MaximumButton.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self._MaximumButton.setFixedHeight(40)
            #self._MaximumButton.setFixedHeight(self._TitleLabel.height()) # 设置按钮高度为标题栏高度
            self._MaximumButton.clicked.connect(
                self._changeNormalButton)  # 按钮信号连接切换到恢复窗口大小按钮函数

    def _changeNormalButton(self):
        global imax
        imax = 1  #已经最大化了
        # 切换到恢复窗口大小按钮
        # self.changeinfo('王骅', '核心商密', '3333333333224561354')
        try:
            self.setContentsMargins(0, 0, 0, 0)

            self.showMaximized()  # 先实现窗口最大化
            self._MaximumButton.setText(
                b'\xef\x80\xb2'.decode("utf-8"))  # 更改按钮文本
            self._MaximumButton.setToolTip("恢复")  # 更改按钮提示
            self._move_drag = False  #针对按住拖到顶端最大化后,就不再相应鼠标拖拽事件
            self._tomax_drag = False
            # self.window().resize(self.width(), self.height() + 1)
            # self.window().resize(self.width(), self.height() - 1)
            self._MaximumButton.disconnect()  # 断开原本的信号槽连接

            #self.toplabel.move(0,0)
            #self.toplabel.setFixedWidth(self.width())
            self._MaximumButton.clicked.connect(
                self._changeMaxButton)  # 重新连接信号和槽
        except:
            pass

    def _changeMaxButton(self):
        global imax

        imax = 0
        # 切换到最大化按钮
        try:
            self.setContentsMargins(8, 8, 8, 8)
            self.showNormal()
            self._MaximumButton.setText(b'\xef\x80\xb1'.decode("utf-8"))
            self._MaximumButton.setToolTip("最大化")
            self._tomax_drag = False
            self.window().resize(self.width(), self.height() + 1)
            self.window().resize(self.width(), self.height() - 1)
            self._MaximumButton.disconnect()

            # self.changeinfo('李振飞','机密', '210199292929292212')
            self._MaximumButton.clicked.connect(self._changeNormalButton)
        except:
            pass

    def resizeEvent(self, QResizeEvent):
        global imax
        global movenum

        # 自定义窗口调整大小事件
        if imax == 0:
            movenum = 8
        elif imax == 1:
            movenum = 0
            try:
                self.setContentsMargins(0, 0, 0, 0)
            except:
                pass
        # 分别移动三个按钮到正确的位置
        try:
            self._CloseButton.move(
                self.width() - self._CloseButton.width() - movenum, movenum)
        except:
            pass
        try:
            self._MinimumButton.move(
                self.width() - (self._CloseButton.width() + 1) * 3 + 1 -
                movenum, 0 + movenum)
        except:
            pass
        try:
            self._MaximumButton.move(
                self.width() - (self._CloseButton.width() + 1) * 2 + 1 -
                movenum, 0 + movenum)
        except:
            pass
        # 重新调整边界范围以备实现鼠标拖放缩放窗口大小,采用三个列表生成式生成三个列表
        self._right_rect = [
            QPoint(x, y) for x in range(self.width() - self._padding,
                                        self.width() + 1)
            for y in range(1,
                           self.height() - self._padding)
        ]
        self._bottom_rect = [
            QPoint(x, y) for x in range(1,
                                        self.width() - self._padding)
            for y in range(self.height() - self._padding,
                           self.height() + 1)
        ]
        self._corner_rect = [
            QPoint(x, y) for x in range(self.width() - self._padding,
                                        self.width() + 1)
            for y in range(self.height() - self._padding,
                           self.height() + 1)
        ]

    def mousePressEvent(self, event):
        global imax, allowresize
        # 重写鼠标点击的事件
        #如果允许调整窗体大小,根据鼠标按下位置定义调整大小的部位
        if allowresize == 1:
            if (event.button() == Qt.LeftButton) and (event.pos()
                                                      in self._corner_rect):
                # 鼠标左键点击右下角边界区域
                self._corner_drag = True
                event.accept()
            elif (event.button() == Qt.LeftButton) and (event.pos()
                                                        in self._right_rect):
                # 鼠标左键点击右侧边界区域
                self._right_drag = True
                event.accept()
            elif (event.button() == Qt.LeftButton) and (event.pos()
                                                        in self._bottom_rect):
                # 鼠标左键点击下侧边界区域
                self._bottom_drag = True
                event.accept()
            #最大化时,也允许进入拖动状态,和move互动,发现move就恢复窗口大小模式
            # 最大化时,也允许进入拖动状态,和move互动,发现move就恢复窗口大小模式,这个条件要先执行,不然就执行不到了
            elif (event.button()
                  == Qt.LeftButton) and (event.y() <
                                         (self.label.height())) and imax == 1:
                self._maxmove_drag = True
                self._move_drag = True
                event.accept()
            elif (event.button()
                  == Qt.LeftButton) and (event.y() <
                                         (self.label.height() + 8)):
                # 鼠标左键点击标题栏区域
                self._move_drag = True
                self.move_DragPosition = event.globalPos() - self.pos()
                event.accept()
        # 最大化时,也允许进入拖动状态,和move互动,发现move就恢复窗口大小模式,这个条件要先执行,不然就执行不到了
        elif (event.button()
              == Qt.LeftButton) and (event.y() <
                                     (self.label.height())) and imax == 1:
            self._maxmove_drag = True
            self._move_drag = True
            event.accept()
        elif (event.button() == Qt.LeftButton) and (event.y() <
                                                    (self.label.height() + 8)):
            # 鼠标左键点击标题栏区域
            self._move_drag = True
            self.move_DragPosition = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        global imax, allowresize
        if allowresize == 1:  #如果允许在边角调整大小
            # 判断鼠标位置切换鼠标手势
            if (QMouseEvent.pos() in self._corner_rect and imax == 0
                    and self._move_drag == False):
                self.setCursor(Qt.SizeFDiagCursor)
            elif (QMouseEvent.pos() in self._bottom_rect and imax == 0
                  and self._move_drag == False):
                self.setCursor(Qt.SizeVerCursor)
            elif (QMouseEvent.pos() in self._right_rect and imax == 0
                  and self._move_drag == False):
                self.setCursor(Qt.SizeHorCursor)
            elif (self._corner_drag == True or self._bottom_drag == True
                  or self._right_drag == True):
                pass
            else:
                self.setCursor(Qt.ArrowCursor)
            # 当鼠标左键点击不放及满足点击区域的要求后,分别实现不同的窗口调整
            # 没有定义左方和上方相关的5个方向,主要是因为实现起来不难,但是效果很差,拖放的时候窗口闪烁,再研究研究是否有更好的实现
            if (Qt.LeftButton and self._right_drag and imax == 0):
                # 右侧调整窗口宽度
                self.resize(QMouseEvent.pos().x(), self.height())
                QMouseEvent.accept()
            elif (Qt.LeftButton and self._bottom_drag and imax == 0):
                # 下侧调整窗口高度
                self.resize(self.width(), QMouseEvent.pos().y())
                QMouseEvent.accept()
            elif (Qt.LeftButton and self._corner_drag and imax == 0):
                # 右下角同时调整高度和宽度
                self.resize(QMouseEvent.pos().x(), QMouseEvent.pos().y())
                QMouseEvent.accept()

            # 目前是在拖动标题栏时,直接根据鼠标移动位置调整窗体位置,以下两条elif和外面的两条一样
            elif (Qt.LeftButton and self._move_drag and imax == 0):
                # print(self._tomax_drag)
                # 在最大化拖小后重新定位鼠标在窗体按压的位置,居中
                if self._maxmove_drag:
                    self.move_DragPosition = QPoint(self.width() / 2,
                                                    titleheight / 2)
                    self._maxmove_drag = False
                # 正常拖拽就是鼠标按住哪里就在哪里
                if ((QMouseEvent.globalPos().y() == 0
                     or QMouseEvent.globalPos().x() == 0
                     or QMouseEvent.globalPos().x()
                     == QDesktopWidget().availableGeometry().right())
                        and self._tomax_drag == False):
                    # self.setCursor(Qt.SplitHCursor)
                    self._tomax_drag = True
                    #QUnFrameWindow.paintEvent(self, QMouseEvent)
                    self.window().resize(self.width(), self.height() + 1)
                    self.window().resize(self.width(), self.height() - 1)
                elif (QMouseEvent.globalPos().y() == 0
                      or QMouseEvent.globalPos().x() == 0
                      or QMouseEvent.globalPos().x()
                      == QDesktopWidget().availableGeometry().right()):
                    # self.setCursor(Qt.SplitHCursor)
                    self._tomax_drag = True
                elif ((QMouseEvent.globalPos().y() == 0
                       or QMouseEvent.globalPos().x() == 0
                       or QMouseEvent.globalPos().x()
                       == QDesktopWidget().availableGeometry().right())
                      and self._tomax_drag == False):
                    # self.setCursor(Qt.SplitHCursor)
                    self._tomax_drag = True
                    #QUnFrameWindow.paintEvent(self, QMouseEvent)
                    self.window().resize(self.width(), self.height() + 1)
                    self.window().resize(self.width(), self.height() - 1)
                #以上执行完都不符合if条件,代表开始离开边界了
                elif (self._tomax_drag == True):
                    self._tomax_drag = False
                    self.setCursor(Qt.ArrowCursor)
                    #进行调整窗体动作,重绘窗体
                    self.window().resize(self.width(), self.height() + 1)
                    self.window().resize(self.width(), self.height() - 1)
                self.move(QMouseEvent.globalPos() - self.move_DragPosition)

                QMouseEvent.accept()
            elif (Qt.LeftButton and self._move_drag
                  and imax == 1):  # 针对最大化时拖动标题栏后,窗口恢复正常窗口大小
                self.setCursor(Qt.SizeAllCursor)
                QUnFrameWindow._changeMaxButton(self)
                self.setCursor(Qt.ArrowCursor)
                QMouseEvent.accept()

        # 目前是在拖动标题栏时,直接根据鼠标移动位置调整窗体位置,以下两条和里面的两条一样
        elif (Qt.LeftButton and self._move_drag and imax == 0):
            # 在最大化状态下拖动,拖小后重新定位鼠标在窗体press的位置,居中
            if self._maxmove_drag:
                self.move_DragPosition = QPoint(self.width() / 2,
                                                titleheight / 2)
                #关闭最大化拖动开关,已经不再是最大化拖动状态了
                self._maxmove_drag = False

            #此if下都是和鼠标在边界附近时的处理
            # 刚开始拖到边界的时候边界的时候,打开到边界的开关
            if ((QMouseEvent.globalPos().y() == 0
                 or QMouseEvent.globalPos().x() == 0
                 or QMouseEvent.globalPos().x()
                 == QDesktopWidget().availableGeometry().right())
                    and self._tomax_drag == False):
                self._tomax_drag = True
                # 在拖到边界时,调整窗体大小重绘窗体
                self.window().resize(self.width(), self.height() + 1)
                self.window().resize(self.width(), self.height() - 1)
            #已经在边界状态,只要保持边界状态开关一直打开
            elif (QMouseEvent.globalPos().y() == 0
                  or QMouseEvent.globalPos().x() == 0
                  or QMouseEvent.globalPos().x()
                  == QDesktopWidget().availableGeometry().right()):
                self._tomax_drag = True
            # 刚开始拖到边界的时候边界的时候,打开到边界的开关
            elif ((QMouseEvent.globalPos().y() == 0
                   or QMouseEvent.globalPos().x() == 0
                   or QMouseEvent.globalPos().x()
                   == QDesktopWidget().availableGeometry().right())
                  and self._tomax_drag == False):
                self._tomax_drag = True
                self.window().resize(self.width(), self.height() + 1)
                self.window().resize(self.width(), self.height() - 1)
            #以上和边界有关的条件都不符合,只有一种情况,是刚开始离开边界,关闭边界开关,重绘窗体阴影
            elif (self._tomax_drag == True):
                self._tomax_drag = False
                self.setCursor(Qt.ArrowCursor)
                self.window().resize(self.width(), self.height() + 1)
                self.window().resize(self.width(), self.height() - 1)
            #正常拖动,在边界状态也是需要拖动的
            self.move(QMouseEvent.globalPos() - self.move_DragPosition)
            QMouseEvent.accept()
        elif (Qt.LeftButton and self._move_drag
              and imax == 1):  # 针对最大化时拖动标题栏后,窗口恢复正常窗口大小
            self.setCursor(Qt.SizeAllCursor)
            QUnFrameWindow._changeMaxButton(self)
            self.setCursor(Qt.ArrowCursor)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):

        #拖到上、左、右边界就最大化
        if ((QMouseEvent.globalPos().y() == 0 or QMouseEvent.globalPos().x()
             == 0 or QMouseEvent.globalPos().x()
             == QDesktopWidget().availableGeometry().right())
                and self._move_drag == True and imax == 0):

            QUnFrameWindow._changeNormalButton(self)

        # 鼠标释放后,各扳机复位,鼠标样式复位
        self._maxmove_drag = False
        self._tomax_drag = False
        self._move_drag = False
        self._corner_drag = False
        self._bottom_drag = False
        self._right_drag = False
        self.setCursor(Qt.ArrowCursor)

    #窗口居中
    def center(self):
        qr = self.frameGeometry()  # 获得主窗口的一个矩形特定几何图形。这包含了窗口的框架。
        cp = QDesktopWidget().availableGeometry().center()  # 算出相对于显示器的绝对值。
        # 并且从这个绝对值中,我们获得了屏幕中心点。
        qr.moveCenter(cp)  # 矩形已经设置好了它的宽和高。现在我们把矩形的中心设置到屏幕的中间去。
        # 矩形的大小并不会改变。
        self.move(qr.topLeft())  # 移动了应用窗口的左上方的点到qr矩形的左上方的点,因此居中显示在我们的屏幕
Example #50
0
    def __init__(self):
        super(Window, self).__init__()

        rectPath = QPainterPath()
        rectPath.moveTo(20.0, 30.0)
        rectPath.lineTo(80.0, 30.0)
        rectPath.lineTo(80.0, 70.0)
        rectPath.lineTo(20.0, 70.0)
        rectPath.closeSubpath()

        roundRectPath = QPainterPath()
        roundRectPath.moveTo(80.0, 35.0)
        roundRectPath.arcTo(70.0, 30.0, 10.0, 10.0, 0.0, 90.0)
        roundRectPath.lineTo(25.0, 30.0)
        roundRectPath.arcTo(20.0, 30.0, 10.0, 10.0, 90.0, 90.0)
        roundRectPath.lineTo(20.0, 65.0)
        roundRectPath.arcTo(20.0, 60.0, 10.0, 10.0, 180.0, 90.0)
        roundRectPath.lineTo(75.0, 70.0)
        roundRectPath.arcTo(70.0, 60.0, 10.0, 10.0, 270.0, 90.0)
        roundRectPath.closeSubpath()

        ellipsePath = QPainterPath()
        ellipsePath.moveTo(80.0, 50.0)
        ellipsePath.arcTo(20.0, 30.0, 60.0, 40.0, 0.0, 360.0)

        piePath = QPainterPath()
        piePath.moveTo(50.0, 50.0)
        piePath.lineTo(65.0, 32.6795)
        piePath.arcTo(20.0, 30.0, 60.0, 40.0, 60.0, 240.0)
        piePath.closeSubpath()

        polygonPath = QPainterPath()
        polygonPath.moveTo(10.0, 80.0)
        polygonPath.lineTo(20.0, 10.0)
        polygonPath.lineTo(80.0, 30.0)
        polygonPath.lineTo(90.0, 70.0)
        polygonPath.closeSubpath()

        groupPath = QPainterPath()
        groupPath.moveTo(60.0, 40.0)
        groupPath.arcTo(20.0, 20.0, 40.0, 40.0, 0.0, 360.0)
        groupPath.moveTo(40.0, 40.0)
        groupPath.lineTo(40.0, 80.0)
        groupPath.lineTo(80.0, 80.0)
        groupPath.lineTo(80.0, 40.0)
        groupPath.closeSubpath()

        textPath = QPainterPath()
        timesFont = QFont('Times', 50)
        timesFont.setStyleStrategy(QFont.ForceOutline)
        textPath.addText(10, 70, timesFont, "Qt")

        bezierPath = QPainterPath()
        bezierPath.moveTo(20, 30)
        bezierPath.cubicTo(80, 0, 50, 50, 80, 80)

        starPath = QPainterPath()
        starPath.moveTo(90, 50)
        for i in range(1, 5):
            starPath.lineTo(50 + 40 * cos(0.8 * i * pi),
                    50 + 40 * sin(0.8 * i * pi))
        starPath.closeSubpath()

        self.renderAreas = [RenderArea(rectPath), RenderArea(roundRectPath),
                RenderArea(ellipsePath), RenderArea(piePath),
                RenderArea(polygonPath), RenderArea(groupPath),
                RenderArea(textPath), RenderArea(bezierPath),
                RenderArea(starPath)]
        assert len(self.renderAreas) == 9

        self.fillRuleComboBox = QComboBox()
        self.fillRuleComboBox.addItem("Odd Even", Qt.OddEvenFill)
        self.fillRuleComboBox.addItem("Winding", Qt.WindingFill)

        fillRuleLabel = QLabel("Fill &Rule:")
        fillRuleLabel.setBuddy(self.fillRuleComboBox)

        self.fillColor1ComboBox = QComboBox()
        self.populateWithColors(self.fillColor1ComboBox)
        self.fillColor1ComboBox.setCurrentIndex(
                self.fillColor1ComboBox.findText("mediumslateblue"))

        self.fillColor2ComboBox = QComboBox()
        self.populateWithColors(self.fillColor2ComboBox)
        self.fillColor2ComboBox.setCurrentIndex(
                self.fillColor2ComboBox.findText("cornsilk"))

        fillGradientLabel = QLabel("&Fill Gradient:")
        fillGradientLabel.setBuddy(self.fillColor1ComboBox)

        fillToLabel = QLabel("to")
        fillToLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.penWidthSpinBox = QSpinBox()
        self.penWidthSpinBox.setRange(0, 20)

        penWidthLabel = QLabel("&Pen Width:")
        penWidthLabel.setBuddy(self.penWidthSpinBox)

        self.penColorComboBox = QComboBox()
        self.populateWithColors(self.penColorComboBox)
        self.penColorComboBox.setCurrentIndex(
                self.penColorComboBox.findText('darkslateblue'))

        penColorLabel = QLabel("Pen &Color:")
        penColorLabel.setBuddy(self.penColorComboBox)

        self.rotationAngleSpinBox = QSpinBox()
        self.rotationAngleSpinBox.setRange(0, 359)
        self.rotationAngleSpinBox.setWrapping(True)
        self.rotationAngleSpinBox.setSuffix(u'\N{DEGREE SIGN}')

        rotationAngleLabel = QLabel("&Rotation Angle:")
        rotationAngleLabel.setBuddy(self.rotationAngleSpinBox)

        self.fillRuleComboBox.activated.connect(self.fillRuleChanged)
        self.fillColor1ComboBox.activated.connect(self.fillGradientChanged)
        self.fillColor2ComboBox.activated.connect(self.fillGradientChanged)
        self.penColorComboBox.activated.connect(self.penColorChanged)

        for i in range(Window.NumRenderAreas):
            self.penWidthSpinBox.valueChanged.connect(self.renderAreas[i].setPenWidth)
            self.rotationAngleSpinBox.valueChanged.connect(self.renderAreas[i].setRotationAngle)

        topLayout = QGridLayout()
        for i in range(Window.NumRenderAreas):
            topLayout.addWidget(self.renderAreas[i], i / 3, i % 3)

        mainLayout = QGridLayout()
        mainLayout.addLayout(topLayout, 0, 0, 1, 4)
        mainLayout.addWidget(fillRuleLabel, 1, 0)
        mainLayout.addWidget(self.fillRuleComboBox, 1, 1, 1, 3)
        mainLayout.addWidget(fillGradientLabel, 2, 0)
        mainLayout.addWidget(self.fillColor1ComboBox, 2, 1)
        mainLayout.addWidget(fillToLabel, 2, 2)
        mainLayout.addWidget(self.fillColor2ComboBox, 2, 3)
        mainLayout.addWidget(penWidthLabel, 3, 0)
        mainLayout.addWidget(self.penWidthSpinBox, 3, 1, 1, 3)
        mainLayout.addWidget(penColorLabel, 4, 0)
        mainLayout.addWidget(self.penColorComboBox, 4, 1, 1, 3)
        mainLayout.addWidget(rotationAngleLabel, 5, 0)
        mainLayout.addWidget(self.rotationAngleSpinBox, 5, 1, 1, 3)
        self.setLayout(mainLayout)

        self.fillRuleChanged()
        self.fillGradientChanged()
        self.penColorChanged()
        self.penWidthSpinBox.setValue(2)

        self.setWindowTitle("Painter Paths")
Example #51
0
class UI(QDialog):
    def __init__(self, parent=None):
        super(UI, self).__init__(parent)

        self.confidence_label = QLabel("Confidence interval")
        self.confidence_value = QComboBox()
        self.confidence_value.addItems(
            ["0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9"])
        self.reset = QPushButton("Reset")
        self.run = QPushButton("Execute")
        self.useStylePaletteCheckBox = QCheckBox("Light")
        self.i_label = QLabel('i')
        self.i = QSpinBox()
        self.j_label = QLabel('j')
        self.j = QSpinBox()
        self.tab1hbox = QHBoxLayout()
        self.Btab1 = QWidget()
        self.Btable = QTableWidget(self.Btab1)
        self.middleBox = QTabWidget()

        self.Mlabel4 = QLabel("For S4:")
        self.Mlabel3 = QLabel("For S3:")
        self.Mlabel2 = QLabel("For S2:")
        self.Mlabel1 = QLabel("For S1:")
        self.MspinBox4 = QLineEdit("")
        self.MspinBox3 = QLineEdit("")
        self.MspinBox2 = QLineEdit("")
        self.MspinBox1 = QLineEdit("")
        self.bottomBox = QGroupBox("Results")

        self.outputs = []
        self.results = QLabel()
        self.originalPalette = QApplication.palette()
        self.topBox = QHBoxLayout()
        self.setWindowIcon(QIcon('icon.jpg'))
        self.setWindowTitle("Solver")
        self.setWindowIconText('Solver')

        self.create_top_box()
        self.create_middle_box()
        self.create_bottom_box()

        self.canvas1 = Graph(self, width=6, height=3, dpi=100, title='I_t')
        self.canvas2 = Graph(self, width=6, height=3, dpi=100, title='I_p')
        self.canvas3 = Graph(self, width=6, height=3, dpi=100, title='I_d')
        self.canvas4 = Graph(self, width=6, height=3, dpi=100, title='I')

        self.mainLayout = QGridLayout()
        self.mainLayout.addLayout(self.topBox, 0, 0, 1, 6)
        self.mainLayout.addWidget(self.middleBox, 1, 2, 1, 2)
        self.mainLayout.addWidget(self.bottomBox, 2, 2, 2, 2)
        self.mainLayout.addWidget(self.canvas1, 1, 0)
        self.mainLayout.addWidget(self.canvas2, 2, 0)
        self.mainLayout.addWidget(self.canvas3, 1, 4)
        self.mainLayout.addWidget(self.canvas4, 2, 4)

        self.setLayout(self.mainLayout)
        self.resize(1360, 600)
        self.change_palette()

    def change_palette(self):
        dark_palette = QPalette()

        QApplication.setStyle(QStyleFactory.create("Fusion"))

        dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.WindowText, Qt.white)
        dark_palette.setColor(QPalette.Disabled, QPalette.WindowText,
                              QColor(127, 127, 127))
        dark_palette.setColor(QPalette.Base, QColor(42, 42, 42))
        dark_palette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
        dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
        dark_palette.setColor(QPalette.ToolTipText, Qt.white)
        dark_palette.setColor(QPalette.Text, Qt.white)
        dark_palette.setColor(QPalette.Disabled, QPalette.Text,
                              QColor(127, 127, 127))
        dark_palette.setColor(QPalette.Dark, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.Shadow, QColor(20, 20, 20))
        dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.ButtonText, Qt.white)
        dark_palette.setColor(QPalette.Disabled, QPalette.ButtonText,
                              QColor(127, 127, 127))
        dark_palette.setColor(QPalette.BrightText, Qt.red)
        dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.Disabled, QPalette.Highlight,
                              QColor(80, 80, 80))
        dark_palette.setColor(QPalette.HighlightedText, Qt.white)
        dark_palette.setColor(QPalette.Disabled, QPalette.HighlightedText,
                              QColor(127, 127, 127))

        if self.useStylePaletteCheckBox.isChecked():
            QApplication.setPalette(QApplication.style().standardPalette())
        else:
            QApplication.setPalette(dark_palette)

    def create_top_box(self):
        self.useStylePaletteCheckBox.setChecked(True)
        self.reset.setFlat(True)
        self.run.setFlat(True)
        self.topBox.addWidget(self.confidence_label)
        self.topBox.addWidget(self.confidence_value)
        self.topBox.addStretch(1)
        self.topBox.addWidget(self.i_label)
        self.topBox.addWidget(self.i)
        self.topBox.addWidget(self.j_label)
        self.topBox.addWidget(self.j)
        self.topBox.addStretch(1)
        self.topBox.addWidget(self.useStylePaletteCheckBox)
        self.topBox.addWidget(self.run)
        self.topBox.addWidget(self.reset)

    def create_middle_box(self):
        self.Btable.setColumnCount(7)
        self.Btable.setRowCount(0)
        self.Btable.setHorizontalHeaderLabels([
            "       1        ", "       2        ", "       3        ",
            "       4        ", "       5        ", "       6        ",
            "       7        "
        ])
        for j in range(4):
            self.Btable.insertRow(j)
            for i in range(7):
                self.Btable.setColumnWidth(i, 622 / 7)

                self.Btable.setItem(j, i, QTableWidgetItem(''))
        self.Btable.setFixedHeight(144)

        self.tab1hbox.setContentsMargins(5, 5, 5, 5)
        self.tab1hbox.addWidget(self.Btable)

        self.Btab1.setLayout(self.tab1hbox)

        self.middleBox.addTab(self.Btab1, "S[ i ] / Ф[ j ]")

    def create_bottom_box(self):

        self.outputs.append(self.MspinBox1)
        self.outputs.append(self.MspinBox2)
        self.outputs.append(self.MspinBox3)
        self.outputs.append(self.MspinBox4)

        layout = QGridLayout()

        layout.addWidget(self.MspinBox1, 0, 1, 1, 4)
        layout.addWidget(self.MspinBox2, 1, 1, 1, 4)
        layout.addWidget(self.MspinBox3, 2, 1, 1, 4)
        layout.addWidget(self.MspinBox4, 3, 1, 1, 4)
        layout.addWidget(self.Mlabel1, 0, 0, 1, 1)
        layout.addWidget(self.Mlabel2, 1, 0)
        layout.addWidget(self.Mlabel3, 2, 0)
        layout.addWidget(self.Mlabel4, 3, 0)

        self.bottomBox.setFixedWidth(645)
        self.bottomBox.setLayout(layout)

    def clr(self):
        self.Btable.clear()
        for i in range(4):
            self.outputs[i].clear()

    def view(self, solver):
        for i in range(4):
            for j in range(7):
                if solver.intervals_right[i][j] != 0:
                    self.Btable.setItem(
                        i, j,
                        QTableWidgetItem(
                            '[' +
                            str(np.round(solver.intervals_left[i][j], 2)) +
                            ' ; ' +
                            str(np.round(solver.intervals_right[i][j], 2)) +
                            ']'))
                elif solver.mask.to_numpy()[i, j]:
                    self.Btable.setItem(i, j, QTableWidgetItem('Empty'))
                else:
                    self.Btable.setItem(i, j, QTableWidgetItem('-'))

    def plot(self, solver):
        i_p1 = np.vectorize(lambda t, I_p_hat: min(
            t / np.sqrt(1 + (1 - 1e-4**2) /
                        (1 - I_p_hat - 1e-4)**2 - 1 * t**2) + I_p_hat, 1))

        i_d1 = np.vectorize(lambda t, I_d_hat: min(
            np.log(1 + np.exp(np.log(2 * np.exp(1 - I_d_hat) - 1) * t)) - np.
            log(2) + I_d_hat, 1))

        i_t1 = np.vectorize(lambda t, I_t_hat: max(I_t_hat * (1 - t**2), 0))

        i_t = i_t1(np.linspace(0, 1, 1001),
                   solver.tables['I_t_hat'][self.i.value()][self.j.value()])
        i_p = i_p1(np.linspace(0, 1, 1001),
                   solver.tables['I_p_hat'][self.i.value()][self.j.value()])
        i_d = i_d1(np.linspace(0, 1, 1001),
                   solver.tables['I_d_hat'][self.i.value()][self.j.value()])
        i = i_t * i_d * i_p

        self.canvas1.axes.clear()
        self.canvas2.axes.clear()
        self.canvas3.axes.clear()
        self.canvas4.axes.clear()
        self.canvas1.axes.set_title('I_t')
        self.canvas2.axes.set_title('I_p')
        self.canvas3.axes.set_title('I_d')
        self.canvas4.axes.set_title('I')
        self.canvas1.axes.plot(np.linspace(0, 1, 1001),
                               i_t,
                               lw=1,
                               color='blue')
        self.canvas2.axes.plot(np.linspace(0, 1, 1001),
                               i_p,
                               lw=1,
                               color='green')
        self.canvas3.axes.plot(np.linspace(0, 1, 1001), i_d, lw=1, color='red')
        self.canvas4.axes.plot(np.linspace(0, 1, 1001), i, lw=1, color='brown')
        self.canvas1.draw()
        self.canvas2.draw()
        self.canvas3.draw()
        self.canvas4.draw()

    def execute(self):
        self.useStylePaletteCheckBox.setEnabled(False)
        solver = Solver(float(self.confidence_value.currentText()))
        solver.solve()
        self.view(solver)
        self.plot(solver)
        for i in range(4):
            self.outputs[i].clear()
            self.outputs[i].setText(solver.classificator()[i])
Example #52
0
class GuiBuildNovel(QDialog):

    FMT_PDF = 1  # Print to PDF

    FMT_ODT = 2  # Open Document file
    FMT_FODT = 3  # Flat Open Document file
    FMT_HTM = 4  # HTML5
    FMT_NWD = 5  # nW Markdown
    FMT_MD = 6  # Standard Markdown
    FMT_GH = 7  # GitHub Markdown

    FMT_JSON_H = 8  # HTML5 wrapped in JSON
    FMT_JSON_M = 9  # nW Markdown wrapped in JSON

    def __init__(self, theParent, theProject):
        QDialog.__init__(self, theParent)

        logger.debug("Initialising GuiBuildNovel ...")
        self.setObjectName("GuiBuildNovel")

        self.mainConf = nw.CONFIG
        self.theProject = theProject
        self.theParent = theParent
        self.theTheme = theParent.theTheme
        self.optState = self.theProject.optState

        self.htmlText = []  # List of html documents
        self.htmlStyle = []  # List of html styles
        self.htmlSize = 0  # Size of the html document
        self.buildTime = 0  # The timestamp of the last build

        self.setWindowTitle(self.tr("Build Novel Project"))
        self.setMinimumWidth(self.mainConf.pxInt(700))
        self.setMinimumHeight(self.mainConf.pxInt(600))

        self.resize(
            self.mainConf.pxInt(
                self.optState.getInt("GuiBuildNovel", "winWidth", 900)),
            self.mainConf.pxInt(
                self.optState.getInt("GuiBuildNovel", "winHeight", 800)))

        self.docView = GuiBuildNovelDocView(self, self.theProject)

        hS = self.theTheme.fontPixelSize
        wS = 2 * hS

        # Title Formats
        # =============

        self.titleGroup = QGroupBox(self.tr("Title Formats for Novel Files"),
                                    self)
        self.titleForm = QGridLayout(self)
        self.titleGroup.setLayout(self.titleForm)

        fmtHelp = "<br>".join([
            "<b>%s</b>" % self.tr("Formatting Codes:"),
            self.tr("{0} for the title as set in the document").format(
                r"%title%"),
            self.tr("{0} for chapter number (1, 2, 3)").format(r"%ch%"),
            self.tr("{0} for chapter number as a word (one, two)").format(
                r"%chw%"),
            self.tr("{0} for chapter number in upper case Roman").format(
                r"%chI%"),
            self.tr("{0} for chapter number in lower case Roman").format(
                r"%chi%"),
            self.tr("{0} for scene number within chapter").format(r"%sc%"),
            self.tr("{0} for scene number within novel").format(r"%sca%"),
        ])
        fmtScHelp = "<br><br>%s" % self.tr(
            "Leave blank to skip this heading, or set to a static text, like "
            "for instance '{0}', to make a separator. The separator will "
            "be centred automatically and only appear between sections of "
            "the same type.").format("* * *")
        xFmt = self.mainConf.pxInt(100)

        self.fmtTitle = QLineEdit()
        self.fmtTitle.setMaxLength(200)
        self.fmtTitle.setMinimumWidth(xFmt)
        self.fmtTitle.setToolTip(fmtHelp)
        self.fmtTitle.setText(
            self._reFmtCodes(self.theProject.titleFormat["title"]))

        self.fmtChapter = QLineEdit()
        self.fmtChapter.setMaxLength(200)
        self.fmtChapter.setMinimumWidth(xFmt)
        self.fmtChapter.setToolTip(fmtHelp)
        self.fmtChapter.setText(
            self._reFmtCodes(self.theProject.titleFormat["chapter"]))

        self.fmtUnnumbered = QLineEdit()
        self.fmtUnnumbered.setMaxLength(200)
        self.fmtUnnumbered.setMinimumWidth(xFmt)
        self.fmtUnnumbered.setToolTip(fmtHelp)
        self.fmtUnnumbered.setText(
            self._reFmtCodes(self.theProject.titleFormat["unnumbered"]))

        self.fmtScene = QLineEdit()
        self.fmtScene.setMaxLength(200)
        self.fmtScene.setMinimumWidth(xFmt)
        self.fmtScene.setToolTip(fmtHelp + fmtScHelp)
        self.fmtScene.setText(
            self._reFmtCodes(self.theProject.titleFormat["scene"]))

        self.fmtSection = QLineEdit()
        self.fmtSection.setMaxLength(200)
        self.fmtSection.setMinimumWidth(xFmt)
        self.fmtSection.setToolTip(fmtHelp + fmtScHelp)
        self.fmtSection.setText(
            self._reFmtCodes(self.theProject.titleFormat["section"]))

        self.buildLang = QComboBox()
        self.buildLang.setMinimumWidth(xFmt)
        theLangs = self.mainConf.listLanguages(self.mainConf.LANG_PROJ)
        self.buildLang.addItem("[%s]" % self.tr("Not Set"), "None")
        for langID, langName in theLangs:
            self.buildLang.addItem(langName, langID)

        langIdx = self.buildLang.findData(self.theProject.projLang)
        if langIdx != -1:
            self.buildLang.setCurrentIndex(langIdx)

        # Dummy boxes due to QGridView and QLineEdit expand bug
        self.boxTitle = QHBoxLayout()
        self.boxTitle.addWidget(self.fmtTitle)
        self.boxChapter = QHBoxLayout()
        self.boxChapter.addWidget(self.fmtChapter)
        self.boxUnnumb = QHBoxLayout()
        self.boxUnnumb.addWidget(self.fmtUnnumbered)
        self.boxScene = QHBoxLayout()
        self.boxScene.addWidget(self.fmtScene)
        self.boxSection = QHBoxLayout()
        self.boxSection.addWidget(self.fmtSection)

        titleLabel = QLabel(self.tr("Title"))
        chapterLabel = QLabel(self.tr("Chapter"))
        unnumbLabel = QLabel(self.tr("Unnumbered"))
        sceneLabel = QLabel(self.tr("Scene"))
        sectionLabel = QLabel(self.tr("Section"))
        langLabel = QLabel(self.tr("Language"))

        self.titleForm.addWidget(titleLabel, 0, 0, 1, 1, Qt.AlignLeft)
        self.titleForm.addLayout(self.boxTitle, 0, 1, 1, 1, Qt.AlignRight)
        self.titleForm.addWidget(chapterLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.titleForm.addLayout(self.boxChapter, 1, 1, 1, 1, Qt.AlignRight)
        self.titleForm.addWidget(unnumbLabel, 2, 0, 1, 1, Qt.AlignLeft)
        self.titleForm.addLayout(self.boxUnnumb, 2, 1, 1, 1, Qt.AlignRight)
        self.titleForm.addWidget(sceneLabel, 3, 0, 1, 1, Qt.AlignLeft)
        self.titleForm.addLayout(self.boxScene, 3, 1, 1, 1, Qt.AlignRight)
        self.titleForm.addWidget(sectionLabel, 4, 0, 1, 1, Qt.AlignLeft)
        self.titleForm.addLayout(self.boxSection, 4, 1, 1, 1, Qt.AlignRight)
        self.titleForm.addWidget(langLabel, 5, 0, 1, 1, Qt.AlignLeft)
        self.titleForm.addWidget(self.buildLang, 5, 1, 1, 1, Qt.AlignRight)

        self.titleForm.setColumnStretch(0, 0)
        self.titleForm.setColumnStretch(1, 1)

        # Font Options
        # ============

        self.fontGroup = QGroupBox(self.tr("Font Options"), self)
        self.fontForm = QGridLayout(self)
        self.fontGroup.setLayout(self.fontForm)

        ## Font Family
        self.textFont = QLineEdit()
        self.textFont.setReadOnly(True)
        self.textFont.setMinimumWidth(xFmt)
        self.textFont.setText(
            self.optState.getString("GuiBuildNovel", "textFont",
                                    self.mainConf.textFont))
        self.fontButton = QPushButton("...")
        self.fontButton.setMaximumWidth(
            int(2.5 * self.theTheme.getTextWidth("...")))
        self.fontButton.clicked.connect(self._selectFont)

        self.textSize = QSpinBox(self)
        self.textSize.setFixedWidth(6 * self.theTheme.textNWidth)
        self.textSize.setMinimum(6)
        self.textSize.setMaximum(72)
        self.textSize.setSingleStep(1)
        self.textSize.setValue(
            self.optState.getInt("GuiBuildNovel", "textSize",
                                 self.mainConf.textSize))

        self.lineHeight = QDoubleSpinBox(self)
        self.lineHeight.setFixedWidth(6 * self.theTheme.textNWidth)
        self.lineHeight.setMinimum(0.8)
        self.lineHeight.setMaximum(3.0)
        self.lineHeight.setSingleStep(0.05)
        self.lineHeight.setDecimals(2)
        self.lineHeight.setValue(
            self.optState.getFloat("GuiBuildNovel", "lineHeight", 1.15))

        # Dummy box due to QGridView and QLineEdit expand bug
        self.boxFont = QHBoxLayout()
        self.boxFont.addWidget(self.textFont)

        fontFamilyLabel = QLabel(self.tr("Font family"))
        fontSizeLabel = QLabel(self.tr("Font size"))
        lineHeightLabel = QLabel(self.tr("Line height"))
        justifyLabel = QLabel(self.tr("Justify text"))
        stylingLabel = QLabel(self.tr("Disable styling"))

        self.fontForm.addWidget(fontFamilyLabel, 0, 0, 1, 1, Qt.AlignLeft)
        self.fontForm.addLayout(self.boxFont, 0, 1, 1, 1, Qt.AlignRight)
        self.fontForm.addWidget(self.fontButton, 0, 2, 1, 1, Qt.AlignRight)
        self.fontForm.addWidget(fontSizeLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.fontForm.addWidget(self.textSize, 1, 1, 1, 2, Qt.AlignRight)
        self.fontForm.addWidget(lineHeightLabel, 2, 0, 1, 1, Qt.AlignLeft)
        self.fontForm.addWidget(self.lineHeight, 2, 1, 1, 2, Qt.AlignRight)

        self.fontForm.setColumnStretch(0, 0)
        self.fontForm.setColumnStretch(1, 1)
        self.fontForm.setColumnStretch(2, 0)

        # Styling Options
        # ===============

        self.styleGroup = QGroupBox(self.tr("Styling Options"), self)
        self.styleForm = QGridLayout(self)
        self.styleGroup.setLayout(self.styleForm)

        self.justifyText = QSwitch(width=wS, height=hS)
        self.justifyText.setChecked(
            self.optState.getBool("GuiBuildNovel", "justifyText", False))

        self.noStyling = QSwitch(width=wS, height=hS)
        self.noStyling.setChecked(
            self.optState.getBool("GuiBuildNovel", "noStyling", False))

        self.styleForm.addWidget(justifyLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.styleForm.addWidget(self.justifyText, 1, 1, 1, 2, Qt.AlignRight)
        self.styleForm.addWidget(stylingLabel, 2, 0, 1, 1, Qt.AlignLeft)
        self.styleForm.addWidget(self.noStyling, 2, 1, 1, 2, Qt.AlignRight)

        self.styleForm.setColumnStretch(0, 0)
        self.styleForm.setColumnStretch(1, 1)

        # Include Options
        # ===============

        self.textGroup = QGroupBox(self.tr("Include Options"), self)
        self.textForm = QGridLayout(self)
        self.textGroup.setLayout(self.textForm)

        self.includeSynopsis = QSwitch(width=wS, height=hS)
        self.includeSynopsis.setChecked(
            self.optState.getBool("GuiBuildNovel", "incSynopsis", False))

        self.includeComments = QSwitch(width=wS, height=hS)
        self.includeComments.setChecked(
            self.optState.getBool("GuiBuildNovel", "incComments", False))

        self.includeKeywords = QSwitch(width=wS, height=hS)
        self.includeKeywords.setChecked(
            self.optState.getBool("GuiBuildNovel", "incKeywords", False))

        self.includeBody = QSwitch(width=wS, height=hS)
        self.includeBody.setChecked(
            self.optState.getBool("GuiBuildNovel", "incBodyText", True))

        synopsisLabel = QLabel(self.tr("Include synopsis"))
        commentsLabel = QLabel(self.tr("Include comments"))
        keywordsLabel = QLabel(self.tr("Include keywords"))
        bodyLabel = QLabel(self.tr("Include body text"))

        self.textForm.addWidget(synopsisLabel, 0, 0, 1, 1, Qt.AlignLeft)
        self.textForm.addWidget(self.includeSynopsis, 0, 1, 1, 1,
                                Qt.AlignRight)
        self.textForm.addWidget(commentsLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.textForm.addWidget(self.includeComments, 1, 1, 1, 1,
                                Qt.AlignRight)
        self.textForm.addWidget(keywordsLabel, 2, 0, 1, 1, Qt.AlignLeft)
        self.textForm.addWidget(self.includeKeywords, 2, 1, 1, 1,
                                Qt.AlignRight)
        self.textForm.addWidget(bodyLabel, 3, 0, 1, 1, Qt.AlignLeft)
        self.textForm.addWidget(self.includeBody, 3, 1, 1, 1, Qt.AlignRight)

        self.textForm.setColumnStretch(0, 1)
        self.textForm.setColumnStretch(1, 0)

        # File Filter Options
        # ===================

        self.fileGroup = QGroupBox(self.tr("File Filter Options"), self)
        self.fileForm = QGridLayout(self)
        self.fileGroup.setLayout(self.fileForm)

        self.novelFiles = QSwitch(width=wS, height=hS)
        self.novelFiles.setToolTip(
            self.tr("Include files with layouts other than 'Note'."))
        self.novelFiles.setChecked(
            self.optState.getBool("GuiBuildNovel", "addNovel", True))

        self.noteFiles = QSwitch(width=wS, height=hS)
        self.noteFiles.setToolTip(self.tr("Include files with layout 'Note'."))
        self.noteFiles.setChecked(
            self.optState.getBool("GuiBuildNovel", "addNotes", False))

        self.ignoreFlag = QSwitch(width=wS, height=hS)
        self.ignoreFlag.setToolTip(
            self.
            tr("Ignore the 'Include when building project' setting and include "
               "all files in the output."))
        self.ignoreFlag.setChecked(
            self.optState.getBool("GuiBuildNovel", "ignoreFlag", False))

        novelLabel = QLabel(self.tr("Include novel files"))
        notesLabel = QLabel(self.tr("Include note files"))
        exportLabel = QLabel(self.tr("Ignore export flag"))

        self.fileForm.addWidget(novelLabel, 0, 0, 1, 1, Qt.AlignLeft)
        self.fileForm.addWidget(self.novelFiles, 0, 1, 1, 1, Qt.AlignRight)
        self.fileForm.addWidget(notesLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.fileForm.addWidget(self.noteFiles, 1, 1, 1, 1, Qt.AlignRight)
        self.fileForm.addWidget(exportLabel, 2, 0, 1, 1, Qt.AlignLeft)
        self.fileForm.addWidget(self.ignoreFlag, 2, 1, 1, 1, Qt.AlignRight)

        self.fileForm.setColumnStretch(0, 1)
        self.fileForm.setColumnStretch(1, 0)

        # Export Options
        # ==============

        self.exportGroup = QGroupBox(self.tr("Export Options"), self)
        self.exportForm = QGridLayout(self)
        self.exportGroup.setLayout(self.exportForm)

        self.replaceTabs = QSwitch(width=wS, height=hS)
        self.replaceTabs.setChecked(
            self.optState.getBool("GuiBuildNovel", "replaceTabs", False))

        self.replaceUCode = QSwitch(width=wS, height=hS)
        self.replaceUCode.setChecked(
            self.optState.getBool("GuiBuildNovel", "replaceUCode", False))

        tabsLabel = QLabel(self.tr("Replace tabs with spaces"))
        uCodeLabel = QLabel(self.tr("Replace Unicode in HTML"))

        self.exportForm.addWidget(tabsLabel, 0, 0, 1, 1, Qt.AlignLeft)
        self.exportForm.addWidget(self.replaceTabs, 0, 1, 1, 1, Qt.AlignRight)
        self.exportForm.addWidget(uCodeLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.exportForm.addWidget(self.replaceUCode, 1, 1, 1, 1, Qt.AlignRight)

        self.exportForm.setColumnStretch(0, 1)
        self.exportForm.setColumnStretch(1, 0)

        # Build Button
        # ============

        self.buildProgress = QProgressBar()

        self.buildNovel = QPushButton(self.tr("Build Preview"))
        self.buildNovel.clicked.connect(self._buildPreview)

        # Action Buttons
        # ==============

        self.buttonBox = QHBoxLayout()

        # Printing

        self.printMenu = QMenu(self)
        self.btnPrint = QPushButton(self.tr("Print"))
        self.btnPrint.setMenu(self.printMenu)

        self.printSend = QAction(self.tr("Print Preview"), self)
        self.printSend.triggered.connect(self._printDocument)
        self.printMenu.addAction(self.printSend)

        self.printFile = QAction(self.tr("Print to PDF"), self)
        self.printFile.triggered.connect(
            lambda: self._saveDocument(self.FMT_PDF))
        self.printMenu.addAction(self.printFile)

        # Saving to File

        self.saveMenu = QMenu(self)
        self.btnSave = QPushButton(self.tr("Save As"))
        self.btnSave.setMenu(self.saveMenu)

        self.saveODT = QAction(self.tr("Open Document (.odt)"), self)
        self.saveODT.triggered.connect(
            lambda: self._saveDocument(self.FMT_ODT))
        self.saveMenu.addAction(self.saveODT)

        self.saveFODT = QAction(self.tr("Flat Open Document (.fodt)"), self)
        self.saveFODT.triggered.connect(
            lambda: self._saveDocument(self.FMT_FODT))
        self.saveMenu.addAction(self.saveFODT)

        self.saveHTM = QAction(self.tr("novelWriter HTML (.htm)"), self)
        self.saveHTM.triggered.connect(
            lambda: self._saveDocument(self.FMT_HTM))
        self.saveMenu.addAction(self.saveHTM)

        self.saveNWD = QAction(self.tr("novelWriter Markdown (.nwd)"), self)
        self.saveNWD.triggered.connect(
            lambda: self._saveDocument(self.FMT_NWD))
        self.saveMenu.addAction(self.saveNWD)

        self.saveMD = QAction(self.tr("Standard Markdown (.md)"), self)
        self.saveMD.triggered.connect(lambda: self._saveDocument(self.FMT_MD))
        self.saveMenu.addAction(self.saveMD)

        self.saveGH = QAction(self.tr("GitHub Markdown (.md)"), self)
        self.saveGH.triggered.connect(lambda: self._saveDocument(self.FMT_GH))
        self.saveMenu.addAction(self.saveGH)

        self.saveJsonH = QAction(self.tr("JSON + novelWriter HTML (.json)"),
                                 self)
        self.saveJsonH.triggered.connect(
            lambda: self._saveDocument(self.FMT_JSON_H))
        self.saveMenu.addAction(self.saveJsonH)

        self.saveJsonM = QAction(
            self.tr("JSON + novelWriter Markdown (.json)"), self)
        self.saveJsonM.triggered.connect(
            lambda: self._saveDocument(self.FMT_JSON_M))
        self.saveMenu.addAction(self.saveJsonM)

        self.btnClose = QPushButton(self.tr("Close"))
        self.btnClose.clicked.connect(self._doClose)

        self.buttonBox.addWidget(self.btnSave)
        self.buttonBox.addWidget(self.btnPrint)
        self.buttonBox.addWidget(self.btnClose)
        self.buttonBox.setSpacing(self.mainConf.pxInt(4))

        # Assemble GUI
        # ============

        # Splitter Position
        boxWidth = self.mainConf.pxInt(350)
        boxWidth = self.optState.getInt("GuiBuildNovel", "boxWidth", boxWidth)
        docWidth = max(self.width() - boxWidth, 100)
        docWidth = self.optState.getInt("GuiBuildNovel", "docWidth", docWidth)

        # The Tool Box
        self.toolsBox = QVBoxLayout()
        self.toolsBox.addWidget(self.titleGroup)
        self.toolsBox.addWidget(self.fontGroup)
        self.toolsBox.addWidget(self.styleGroup)
        self.toolsBox.addWidget(self.textGroup)
        self.toolsBox.addWidget(self.fileGroup)
        self.toolsBox.addWidget(self.exportGroup)
        self.toolsBox.addStretch(1)

        # Tool Box Wrapper Widget
        self.toolsWidget = QWidget()
        self.toolsWidget.setSizePolicy(QSizePolicy.MinimumExpanding,
                                       QSizePolicy.Minimum)
        self.toolsWidget.setLayout(self.toolsBox)

        # Tool Box Scroll Area
        self.toolsArea = QScrollArea()
        self.toolsArea.setMinimumWidth(self.mainConf.pxInt(250))
        self.toolsArea.setWidgetResizable(True)
        self.toolsArea.setWidget(self.toolsWidget)

        if self.mainConf.hideVScroll:
            self.toolsArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        else:
            self.toolsArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        if self.mainConf.hideHScroll:
            self.toolsArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        else:
            self.toolsArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        # Tools and Buttons Layout
        tSp = self.mainConf.pxInt(8)
        self.innerBox = QVBoxLayout()
        self.innerBox.addWidget(self.toolsArea)
        self.innerBox.addSpacing(tSp)
        self.innerBox.addWidget(self.buildProgress)
        self.innerBox.addWidget(self.buildNovel)
        self.innerBox.addSpacing(tSp)
        self.innerBox.addLayout(self.buttonBox)

        # Tools and Buttons Wrapper Widget
        self.innerWidget = QWidget()
        self.innerWidget.setLayout(self.innerBox)

        # Main Dialog Splitter
        self.mainSplit = QSplitter(Qt.Horizontal)
        self.mainSplit.addWidget(self.innerWidget)
        self.mainSplit.addWidget(self.docView)
        self.mainSplit.setSizes([boxWidth, docWidth])

        self.idxSettings = self.mainSplit.indexOf(self.innerWidget)
        self.idxDocument = self.mainSplit.indexOf(self.docView)

        self.mainSplit.setCollapsible(self.idxSettings, False)
        self.mainSplit.setCollapsible(self.idxDocument, False)

        # Outer Layout
        self.outerBox = QHBoxLayout()
        self.outerBox.addWidget(self.mainSplit)

        self.setLayout(self.outerBox)
        self.buildNovel.setFocus()

        logger.debug("GuiBuildNovel initialisation complete")

        return

    def viewCachedDoc(self):
        """Load the previously generated document from cache.
        """
        if self._loadCache():
            textFont = self.textFont.text()
            textSize = self.textSize.value()
            justifyText = self.justifyText.isChecked()
            self.docView.setTextFont(textFont, textSize)
            self.docView.setJustify(justifyText)
            if self.noStyling.isChecked():
                self.docView.clearStyleSheet()
            else:
                self.docView.setStyleSheet(self.htmlStyle)

            htmlSize = sum([len(x) for x in self.htmlText])
            if htmlSize < nwConst.MAX_BUILDSIZE:
                qApp.processEvents()
                self.docView.setContent(self.htmlText, self.buildTime)
            else:
                self.docView.setText(
                    self.tr(
                        "Failed to generate preview. The result is too big."))

        else:
            self.htmlText = []
            self.htmlStyle = []
            self.buildTime = 0
            return False

        return True

    ##
    #  Slots and Related
    ##

    def _buildPreview(self):
        """Build a preview of the project in the document viewer.
        """
        # Get Settings
        justifyText = self.justifyText.isChecked()
        noStyling = self.noStyling.isChecked()
        textFont = self.textFont.text()
        textSize = self.textSize.value()
        replaceTabs = self.replaceTabs.isChecked()

        self.htmlText = []
        self.htmlStyle = []
        self.htmlSize = 0

        # Build Preview
        # =============

        makeHtml = ToHtml(self.theProject, self.theParent)
        self._doBuild(makeHtml, isPreview=True)
        if replaceTabs:
            makeHtml.replaceTabs()

        self.htmlText = makeHtml.fullHTML
        self.htmlStyle = makeHtml.getStyleSheet()
        self.htmlSize = makeHtml.getFullResultSize()
        self.buildTime = int(time())

        # Load Preview
        # ============

        self.docView.setTextFont(textFont, textSize)
        self.docView.setJustify(justifyText)
        if noStyling:
            self.docView.clearStyleSheet()
        else:
            self.docView.setStyleSheet(self.htmlStyle)

        if self.htmlSize < nwConst.MAX_BUILDSIZE:
            self.docView.setContent(self.htmlText, self.buildTime)
        else:
            self.docView.setText(
                "Failed to generate preview. The result is too big.")

        self._saveCache()

        return

    def _doBuild(self, bldObj, isPreview=False, doConvert=True):
        """Rund the build with a specific build object.
        """
        tStart = int(time())

        # Get Settings
        fmtTitle = self.fmtTitle.text().strip()
        fmtChapter = self.fmtChapter.text().strip()
        fmtUnnumbered = self.fmtUnnumbered.text().strip()
        fmtScene = self.fmtScene.text().strip()
        fmtSection = self.fmtSection.text().strip()
        textFont = self.textFont.text()
        textSize = self.textSize.value()
        lineHeight = self.lineHeight.value()
        justifyText = self.justifyText.isChecked()
        noStyling = self.noStyling.isChecked()
        incSynopsis = self.includeSynopsis.isChecked()
        incComments = self.includeComments.isChecked()
        incKeywords = self.includeKeywords.isChecked()
        novelFiles = self.novelFiles.isChecked()
        noteFiles = self.noteFiles.isChecked()
        ignoreFlag = self.ignoreFlag.isChecked()
        includeBody = self.includeBody.isChecked()
        replaceUCode = self.replaceUCode.isChecked()

        # The language lookup dict is reloaded if needed
        self.theProject.setProjectLang(self.buildLang.currentData())

        # Get font information
        fontInfo = QFontInfo(QFont(textFont, textSize))
        textFixed = fontInfo.fixedPitch()

        isHtml = isinstance(bldObj, ToHtml)
        isOdt = isinstance(bldObj, ToOdt)

        bldObj.setTitleFormat(fmtTitle)
        bldObj.setChapterFormat(fmtChapter)
        bldObj.setUnNumberedFormat(fmtUnnumbered)
        bldObj.setSceneFormat(fmtScene, fmtScene == "")
        bldObj.setSectionFormat(fmtSection, fmtSection == "")

        bldObj.setFont(textFont, textSize, textFixed)
        bldObj.setJustify(justifyText)
        bldObj.setLineHeight(lineHeight)

        bldObj.setSynopsis(incSynopsis)
        bldObj.setComments(incComments)
        bldObj.setKeywords(incKeywords)
        bldObj.setBodyText(includeBody)

        if isHtml:
            bldObj.setStyles(not noStyling)
            bldObj.setReplaceUnicode(replaceUCode)

        if isOdt:
            bldObj.setColourHeaders(not noStyling)
            bldObj.initDocument()

        # Make sure the project and document is up to date
        self.theParent.treeView.flushTreeOrder()
        self.theParent.saveDocument()

        self.buildProgress.setMaximum(len(self.theProject.projTree))
        self.buildProgress.setValue(0)

        for nItt, tItem in enumerate(self.theProject.projTree):

            noteRoot = noteFiles
            noteRoot &= tItem.itemType == nwItemType.ROOT
            noteRoot &= tItem.itemClass != nwItemClass.NOVEL
            noteRoot &= tItem.itemClass != nwItemClass.ARCHIVE

            try:
                if noteRoot:
                    # Add headers for root folders of notes
                    bldObj.addRootHeading(tItem.itemHandle)
                    if doConvert:
                        bldObj.doConvert()

                elif self._checkInclude(tItem, noteFiles, novelFiles,
                                        ignoreFlag):
                    bldObj.setText(tItem.itemHandle)
                    bldObj.doPreProcessing()
                    bldObj.tokenizeText()
                    bldObj.doHeaders()
                    if doConvert:
                        bldObj.doConvert()
                    bldObj.doPostProcessing()

            except Exception:
                logger.error("Failed to build document '%s'" %
                             tItem.itemHandle)
                nw.logException()
                if isPreview:
                    self.docView.setText(
                        ("Failed to generate preview. "
                         "Document with title '%s' could not be parsed.") %
                        tItem.itemName)

                return False

            # Update progress bar, also for skipped items
            self.buildProgress.setValue(nItt + 1)

        if isOdt:
            bldObj.closeDocument()

        tEnd = int(time())
        logger.debug("Built project in %.3f ms" % (1000 * (tEnd - tStart)))

        if bldObj.errData:
            self.theParent.makeAlert(
                "%s:<br>-&nbsp;%s" %
                (self.tr("There were problems when building the project"),
                 "<br>-&nbsp;".join(bldObj.errData)), nwAlert.ERROR)

        return

    def _checkInclude(self, theItem, noteFiles, novelFiles, ignoreFlag):
        """This function checks whether a file should be included in the
        export or not. For standard note and novel files, this is
        controlled by the options selected by the user. For other files
        classified as non-exportable, a few checks must be made, and the
        following are not:
        * Items that are not actual files.
        * Items that have been orphaned which are tagged as NO_LAYOUT
          and NO_CLASS.
        * Items that appear in the TRASH folder or have parent set to
          None (orphaned files).
        """
        if theItem is None:
            return False

        if not theItem.isExported and not ignoreFlag:
            return False

        isNone = theItem.itemType != nwItemType.FILE
        isNone |= theItem.itemLayout == nwItemLayout.NO_LAYOUT
        isNone |= theItem.itemClass == nwItemClass.NO_CLASS
        isNone |= theItem.itemClass == nwItemClass.TRASH
        isNone |= theItem.itemParent == self.theProject.projTree.trashRoot()
        isNone |= theItem.itemParent is None
        isNote = theItem.itemLayout == nwItemLayout.NOTE
        isNovel = not isNone and not isNote

        if isNone:
            return False
        if isNote and not noteFiles:
            return False
        if isNovel and not novelFiles:
            return False

        rootItem = self.theProject.projTree.getRootItem(theItem.itemHandle)
        if rootItem.itemClass == nwItemClass.ARCHIVE:
            return False

        return True

    def _saveDocument(self, theFmt):
        """Save the document to various formats.
        """
        replaceTabs = self.replaceTabs.isChecked()

        fileExt = ""
        textFmt = ""

        # Settings
        # ========

        if theFmt == self.FMT_ODT:
            fileExt = "odt"
            textFmt = self.tr("Open Document")

        elif theFmt == self.FMT_FODT:
            fileExt = "fodt"
            textFmt = self.tr("Flat Open Document")

        elif theFmt == self.FMT_HTM:
            fileExt = "htm"
            textFmt = self.tr("Plain HTML")

        elif theFmt == self.FMT_NWD:
            fileExt = "nwd"
            textFmt = self.tr("novelWriter Markdown")

        elif theFmt == self.FMT_MD:
            fileExt = "md"
            textFmt = self.tr("Standard Markdown")

        elif theFmt == self.FMT_GH:
            fileExt = "md"
            textFmt = self.tr("GitHub Markdown")

        elif theFmt == self.FMT_JSON_H:
            fileExt = "json"
            textFmt = self.tr("JSON + novelWriter HTML")

        elif theFmt == self.FMT_JSON_M:
            fileExt = "json"
            textFmt = self.tr("JSON + novelWriter Markdown")

        elif theFmt == self.FMT_PDF:
            fileExt = "pdf"
            textFmt = self.tr("PDF")

        else:
            return False

        # Generate File Name
        # ==================

        if fileExt:

            cleanName = makeFileNameSafe(self.theProject.projName)
            fileName = "%s.%s" % (cleanName, fileExt)
            saveDir = self.mainConf.lastPath
            savePath = os.path.join(saveDir, fileName)
            if not os.path.isdir(saveDir):
                saveDir = self.mainConf.homePath

            savePath, _ = QFileDialog.getSaveFileName(
                self, self.tr("Save Document As"), savePath)
            if not savePath:
                return False

            self.mainConf.setLastPath(savePath)

        else:
            return False

        # Build and Write
        # ===============

        errMsg = ""
        wSuccess = False

        if theFmt == self.FMT_ODT:
            makeOdt = ToOdt(self.theProject, self.theParent, isFlat=False)
            self._doBuild(makeOdt)
            try:
                makeOdt.saveOpenDocText(savePath)
                wSuccess = True
            except Exception as e:
                errMsg = str(e)

        elif theFmt == self.FMT_FODT:
            makeOdt = ToOdt(self.theProject, self.theParent, isFlat=True)
            self._doBuild(makeOdt)
            try:
                makeOdt.saveFlatXML(savePath)
                wSuccess = True
            except Exception as e:
                errMsg = str(e)

        elif theFmt == self.FMT_HTM:
            makeHtml = ToHtml(self.theProject, self.theParent)
            self._doBuild(makeHtml)
            if replaceTabs:
                makeHtml.replaceTabs()

            try:
                makeHtml.saveHTML5(savePath)
                wSuccess = True
            except Exception as e:
                errMsg = str(e)

        elif theFmt == self.FMT_NWD:
            makeNwd = ToMarkdown(self.theProject, self.theParent)
            makeNwd.setKeepMarkdown(True)
            self._doBuild(makeNwd, doConvert=False)
            if replaceTabs:
                makeNwd.replaceTabs(spaceChar=" ")

            try:
                makeNwd.saveRawMarkdown(savePath)
                wSuccess = True
            except Exception as e:
                errMsg = str(e)

        elif theFmt in (self.FMT_MD, self.FMT_GH):
            makeMd = ToMarkdown(self.theProject, self.theParent)
            if theFmt == self.FMT_GH:
                makeMd.setGitHubMarkdown()
            else:
                makeMd.setStandardMarkdown()

            self._doBuild(makeMd)
            if replaceTabs:
                makeMd.replaceTabs(nSpaces=4, spaceChar=" ")

            try:
                makeMd.saveMarkdown(savePath)
                wSuccess = True
            except Exception as e:
                errMsg = str(e)

        elif theFmt == self.FMT_JSON_H or theFmt == self.FMT_JSON_M:
            jsonData = {
                "meta": {
                    "workingTitle": self.theProject.projName,
                    "novelTitle": self.theProject.bookTitle,
                    "authors": self.theProject.bookAuthors,
                    "buildTime": self.buildTime,
                }
            }

            if theFmt == self.FMT_JSON_H:
                makeHtml = ToHtml(self.theProject, self.theParent)
                self._doBuild(makeHtml)
                if replaceTabs:
                    makeHtml.replaceTabs()

                theBody = []
                for htmlPage in makeHtml.fullHTML:
                    theBody.append(htmlPage.rstrip("\n").split("\n"))
                jsonData["text"] = {
                    "css": self.htmlStyle,
                    "html": theBody,
                }

            elif theFmt == self.FMT_JSON_M:
                makeMd = ToHtml(self.theProject, self.theParent)
                makeMd.setKeepMarkdown(True)
                self._doBuild(makeMd, doConvert=False)
                if replaceTabs:
                    makeMd.replaceTabs(spaceChar=" ")

                theBody = []
                for nwdPage in makeMd.theMarkdown:
                    theBody.append(nwdPage.split("\n"))
                jsonData["text"] = {
                    "nwd": theBody,
                }

            try:
                with open(savePath, mode="w", encoding="utf8") as outFile:
                    outFile.write(json.dumps(jsonData, indent=2))
                    wSuccess = True
            except Exception as e:
                errMsg = str(e)

        elif theFmt == self.FMT_PDF:
            try:
                thePrinter = QPrinter()
                thePrinter.setOutputFormat(QPrinter.PdfFormat)
                thePrinter.setOrientation(QPrinter.Portrait)
                thePrinter.setDuplex(QPrinter.DuplexLongSide)
                thePrinter.setFontEmbeddingEnabled(True)
                thePrinter.setColorMode(QPrinter.Color)
                thePrinter.setOutputFileName(savePath)
                self.docView.qDocument.print(thePrinter)
                wSuccess = True

            except Exception as e:
                errMsg - str(e)

        else:
            errMsg = self.tr("Unknown format")

        # Report to user
        if wSuccess:
            self.theParent.makeAlert(
                "%s<br>%s" %
                (self.tr("{0} file successfully written to:").format(textFmt),
                 savePath), nwAlert.INFO)
        else:
            self.theParent.makeAlert(
                self.tr("Failed to write {0} file. {1}").format(
                    textFmt, errMsg), nwAlert.ERROR)

        return wSuccess

    def _printDocument(self):
        """Open the print preview dialog.
        """
        thePreview = QPrintPreviewDialog(self)
        thePreview.paintRequested.connect(self._doPrintPreview)
        thePreview.exec_()
        return

    def _doPrintPreview(self, thePrinter):
        """Connect the print preview painter to the document viewer.
        """
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
        thePrinter.setOrientation(QPrinter.Portrait)
        self.docView.qDocument.print(thePrinter)
        qApp.restoreOverrideCursor()
        return

    def _selectFont(self):
        """Open the QFontDialog and set a font for the font style.
        """
        currFont = QFont()
        currFont.setFamily(self.textFont.text())
        currFont.setPointSize(self.textSize.value())
        theFont, theStatus = QFontDialog.getFont(currFont, self)
        if theStatus:
            self.textFont.setText(theFont.family())
            self.textSize.setValue(theFont.pointSize())

        self.raise_()  # Move the dialog to front (fixes a bug on macOS)

        return

    def _loadCache(self):
        """Save the current data to cache.
        """
        buildCache = os.path.join(self.theProject.projCache,
                                  nwFiles.BUILD_CACHE)
        dataCount = 0
        if os.path.isfile(buildCache):

            logger.debug("Loading build cache")
            try:
                with open(buildCache, mode="r", encoding="utf8") as inFile:
                    theJson = inFile.read()
                theData = json.loads(theJson)
            except Exception:
                logger.error("Failed to load build cache")
                nw.logException()
                return False

            if "buildTime" in theData.keys():
                self.buildTime = theData["buildTime"]
            if "htmlStyle" in theData.keys():
                self.htmlStyle = theData["htmlStyle"]
                dataCount += 1
            if "htmlText" in theData.keys():
                self.htmlText = theData["htmlText"]
                dataCount += 1

        return dataCount == 2

    def _saveCache(self):
        """Save the current data to cache.
        """
        buildCache = os.path.join(self.theProject.projCache,
                                  nwFiles.BUILD_CACHE)

        logger.debug("Saving build cache")
        try:
            with open(buildCache, mode="w+", encoding="utf8") as outFile:
                outFile.write(
                    json.dumps(
                        {
                            "buildTime": self.buildTime,
                            "htmlStyle": self.htmlStyle,
                            "htmlText": self.htmlText,
                        },
                        indent=2))
        except Exception:
            logger.error("Failed to save build cache")
            nw.logException()
            return False

        return True

    def _doClose(self):
        """Close button was clicked.
        """
        self.close()
        return

    ##
    #  Events
    ##

    def closeEvent(self, theEvent):
        """Capture the user closing the window so we can save settings.
        """
        self._saveSettings()
        self.docView.clear()
        theEvent.accept()
        return

    ##
    #  Internal Functions
    ##

    def _saveSettings(self):
        """Save the various user settings.
        """
        logger.debug("Saving GuiBuildNovel settings")

        # Formatting
        self.theProject.setTitleFormat({
            "title":
            self.fmtTitle.text().strip(),
            "chapter":
            self.fmtChapter.text().strip(),
            "unnumbered":
            self.fmtUnnumbered.text().strip(),
            "scene":
            self.fmtScene.text().strip(),
            "section":
            self.fmtSection.text().strip(),
        })

        buildLang = self.buildLang.currentData()
        winWidth = self.mainConf.rpxInt(self.width())
        winHeight = self.mainConf.rpxInt(self.height())
        justifyText = self.justifyText.isChecked()
        noStyling = self.noStyling.isChecked()
        textFont = self.textFont.text()
        textSize = self.textSize.value()
        lineHeight = self.lineHeight.value()
        novelFiles = self.novelFiles.isChecked()
        noteFiles = self.noteFiles.isChecked()
        ignoreFlag = self.ignoreFlag.isChecked()
        incSynopsis = self.includeSynopsis.isChecked()
        incComments = self.includeComments.isChecked()
        incKeywords = self.includeKeywords.isChecked()
        incBodyText = self.includeBody.isChecked()
        replaceTabs = self.replaceTabs.isChecked()
        replaceUCode = self.replaceUCode.isChecked()

        mainSplit = self.mainSplit.sizes()
        boxWidth = self.mainConf.rpxInt(mainSplit[0])
        docWidth = self.mainConf.rpxInt(mainSplit[1])

        self.theProject.setProjectLang(buildLang)

        # GUI Settings
        self.optState.setValue("GuiBuildNovel", "winWidth", winWidth)
        self.optState.setValue("GuiBuildNovel", "winHeight", winHeight)
        self.optState.setValue("GuiBuildNovel", "boxWidth", boxWidth)
        self.optState.setValue("GuiBuildNovel", "docWidth", docWidth)
        self.optState.setValue("GuiBuildNovel", "justifyText", justifyText)
        self.optState.setValue("GuiBuildNovel", "noStyling", noStyling)
        self.optState.setValue("GuiBuildNovel", "textFont", textFont)
        self.optState.setValue("GuiBuildNovel", "textSize", textSize)
        self.optState.setValue("GuiBuildNovel", "lineHeight", lineHeight)
        self.optState.setValue("GuiBuildNovel", "addNovel", novelFiles)
        self.optState.setValue("GuiBuildNovel", "addNotes", noteFiles)
        self.optState.setValue("GuiBuildNovel", "ignoreFlag", ignoreFlag)
        self.optState.setValue("GuiBuildNovel", "incSynopsis", incSynopsis)
        self.optState.setValue("GuiBuildNovel", "incComments", incComments)
        self.optState.setValue("GuiBuildNovel", "incKeywords", incKeywords)
        self.optState.setValue("GuiBuildNovel", "incBodyText", incBodyText)
        self.optState.setValue("GuiBuildNovel", "replaceTabs", replaceTabs)
        self.optState.setValue("GuiBuildNovel", "replaceUCode", replaceUCode)

        self.optState.saveSettings()

        return

    def _reFmtCodes(self, theFormat):
        """Translates old formatting codes to new ones.
        """
        theFormat = theFormat.replace(r"%chnum%", r"%ch%")
        theFormat = theFormat.replace(r"%scnum%", r"%sc%")
        theFormat = theFormat.replace(r"%scabsnum%", r"%sca%")
        theFormat = theFormat.replace(r"%chnumword%", r"%chw%")
        return theFormat
Example #53
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.graph =PlotCanvas3d(self, width=1, height=1)
        self.graph_2 = PlotCanvas(self, width=1, height=1)
        f = open('style.css', 'r')

        self.setStyleSheet(f.read())
        f.close()
        login = LoginWindow(self)
        self.createGui()

    def createGui(self):
        self.setGeometry(10, 30, 600, 300)
        self.setWindowTitle("Test")
        self.tabs = QTabWidget()
        self.tab = QWidget()
        self.tab_result = QWidget()
        self.tabs.addTab(self.tab, "Главное")
        self.tabs.addTab(self.tab_result, "Таблица значений")
        # self.tab = QTabWidget()
        # self.tab.addTab(self, "Главное окно")
        self.tools_panel = QVBoxLayout()
        self.lab_method = QLabel("Метод оптимизации")
        self.lab_method.setAlignment(Qt.AlignCenter)
        self.select_method = QComboBox()
        self.select_method.addItem("Полный перебор")
        self.select_method.addItem("Сканнирование с переменным шагом")
        self.lab_var = QLabel("Вариант")
        self.lab_var.setAlignment(Qt.AlignCenter)
        self.select_var = QComboBox()
        self.select_var.addItem("11")
        self.lab_select_temterature = QLabel("Ограничения температуры")
        self.temp_layout = QHBoxLayout()
        self.temp_layout_2 = QHBoxLayout()
        self.lab_T1min = QLabel("Tmin")
        self.lab_T1max = QLabel("Tmax")
        self.lab_T2min = QLabel("T2min")
        self.lab_T2max = QLabel("T2max")
        self.T2min = QLineEdit()
        self.T2min.setText("-0.5")
        self.T2max = QLineEdit()
        self.T2max.setText("3")
        self.value_T1 = QLineEdit()
        self.value_T1.setText("-3")
        self.value_T2 = QLineEdit()
        self.value_T2.setText("0.5")
        self.temp_layout.addWidget(self.lab_T1min)
        self.temp_layout.addWidget(self.value_T1)
        self.temp_layout.addWidget(self.lab_T1max)
        self.temp_layout.addWidget(self.value_T2)
        self.temp_layout_2.addWidget(self.lab_T2min)
        self.temp_layout_2.addWidget(self.T2min)
        self.temp_layout_2.addWidget(self.lab_T2max)
        self.temp_layout_2.addWidget(self.T2max)

        self.lim_layout = QHBoxLayout()
        self.lim_layout_2 = QHBoxLayout()
        self.lab_lim = QLabel("Ограничения 2-го рода:")
        self.lim_value = QLineEdit()
        self.lab_count = QLabel("Кол-во устройств:")
        self.count = QLineEdit()
        self.lim_value.setText("T2-T1 <= 3")
        self.lim_value.setEnabled(False)
        self.count.setText("2")
        self.count.setEnabled(False)
        self.lim_layout.addWidget(self.lim_value)
        self.lim_layout.addWidget(self.count)
        self.lim_layout_2.addWidget(self.lab_lim)
        self.lim_layout_2.addWidget(self.lab_count)


        self.lab_accuracy = QLabel("Точность нахождения решения:")
        self.accuracy = QLineEdit()
        self.accuracy.setText("0.01")


        self.lab_mult = QLabel("Нормирующие множители:")
        self.mult_layout_1 = QHBoxLayout()
        self.lab_alfa = QLabel("\u03B1")
        self.alfa = QLineEdit()
        self.alfa.setText("1")
        self.lab_beta = QLabel("\u03B2")
        self.beta = QLineEdit()
        self.beta.setText("1")
        self.lab_y = QLabel("y")
        self.y = QLineEdit()
        self.y.setText("3.14")
        self.mult_layout_1.addWidget(self.lab_alfa)
        self.mult_layout_1.addWidget(self.alfa)
        self.mult_layout_1.addWidget(self.lab_beta)
        self.mult_layout_1.addWidget(self.beta)
        self.mult_layout_1.addWidget(self.lab_y)
        self.mult_layout_1.addWidget(self.y)


        self.lab_volume = QLabel("Величина перепада давлений Кпа:")
        self.lab_P1 = QLabel("\u0394 P1")
        self.lab_P2 = QLabel("\u0394 P2")
        self.P1 = QLineEdit()
        self.P1.setText("1")
        self.P2 = QLineEdit()
        self.P2.setText("1")
        self.volume_layout = QHBoxLayout()
        self.volume_layout.addWidget(self.lab_P1)
        self.volume_layout.addWidget(self.P1)
        self.volume_layout.addWidget(self.lab_P2)
        self.volume_layout.addWidget(self.P2)

        self.tools_panel.contentsMargins().top()
        self.tools_panel.addWidget(self.lab_method)
        self.tools_panel.addWidget(self.select_method)
        self.tools_panel.addWidget(self.lab_var)
        self.tools_panel.addWidget(self.select_var)
        self.tools_panel.addWidget(self.lab_select_temterature)
        self.tools_panel.addLayout(self.temp_layout)
        self.tools_panel.addLayout(self.temp_layout_2)
        self.tools_panel.addLayout(self.lim_layout_2)
        self.tools_panel.addLayout(self.lim_layout)
        self.tools_panel.addWidget(self.lab_accuracy)
        self.tools_panel.addWidget(self.accuracy)
        self.tools_panel.addWidget(self.lab_mult)
        self.tools_panel.addLayout(self.mult_layout_1)

        self.tools_panel.addWidget(self.lab_volume)
        self.tools_panel.addLayout(self.volume_layout)
        self.tools_panel.addStretch(1)

        self.result_layout = QHBoxLayout()
        self.result_line = QLineEdit()
        self.result_line.setEnabled(False)
        self.result_line.setMinimumSize(200, 30)
        self.result_lab = QLabel("Результат: ")
        self.result_lab.setFont(QFont('', 10))
        self.result_layout.addWidget(self.result_lab)
        self.result_layout.addWidget(self.result_line)

        self.layout = QGridLayout()
        self.layout.addLayout(self.tools_panel, 0, 1)

        self.buttons_panel = QHBoxLayout()
        self.start_button = QPushButton('Решить задачу')
        self.start_button.clicked.connect(self.plotGraph)
        self.buttons_panel.addWidget(self.start_button)

        self.name_graph = QLabel("3-D График критерия качества оптимизации")
        self.name_graph.setAlignment(Qt.AlignCenter)
        self.graph_layout = QVBoxLayout()

        self.graph_layout.addWidget(self.name_graph)
        self.graph_layout.addWidget(self.graph)

        self.third_graph_lay = QVBoxLayout()
        self.lab_tihrd_graph = QLabel("Контурный график критерия качества оптимизации")
        self.lab_tihrd_graph.setAlignment(Qt.AlignCenter)
        self.third_graph = gl.GLViewWidget()
        self.third_graph.setGeometry(0, 110, 1920, 500)
        self.third_graph_lay.addWidget(self.lab_tihrd_graph)
        self.third_graph_lay.addWidget(self.graph_2)

        self.graph_layout.addLayout(self.third_graph_lay)
        self.layout.addLayout(self.graph_layout, 2, 1)
        self.layout.addLayout(self.result_layout, 1, 1)
        self.layout.addLayout(self.buttons_panel, 3, 1)

        # self.layout.addLayout(self.buttons_panel, 1,1)
        # self.tab.addTab(self, "Tab")
        self.table = QTableWidget()
        self.table.setColumnCount(2000)
        self.table.setRowCount(2000)
        self.table_layout = QVBoxLayout()
        self.table_layout.addWidget(self.table)
        self.tab_result.setLayout(self.table_layout)

        self.tab.setLayout(self.layout)
        self.lay_tab_1 = QVBoxLayout()
        self.lay_tab_1.addWidget(self.tabs)
        self.setLayout(self.lay_tab_1)
        # self.setLayout(self.layout)
        self.setAcceptDrops(True)
        #self.show()

    def dragEnterEvent(self, e):
        e.accept()

    def dropEvent(self, e):
        position = e.pos()
        self.button.move(position)
        e.setDropAction(Qt.MoveAction)
        e.accept()
    def plotGraph(self):
        print("plot")
        T_min = float(self.value_T1.text())
        T_max = float(self.value_T2.text())
        print("qwe")
        accuracy =float(self.accuracy.text())
        a = float(self.alfa.text())
        b = float(self.beta.text())
        y = float(self.y.text())
        print("asd")
        P1 = float(self.P1.text())
        P2 = float(self.P2.text())
        print(a, b, y, P1, P2)
        h = Handler(a, b, y, P1, P2)
        self.result_line.setText(h.full(T_min, T_max, T_min, T_max, accuracy))
        self.graph.plot(h.xgrid, h.ygrid, h.zgrid)
        self.graph_2.plot(h.xgrid, h.ygrid, h.zgrid)
        self.update_table(h.xgrid, h.ygrid, h.arr_d)
    def update_table(self, arr1, arr2, arr3):
        for x in range(len(arr1)):
            for y in range(len(arr2)):
                self.table.setItem(x, y, QTableWidgetItem(str(arr3[x][y])))
    def out_frame_func(int_lng, prj_path, mesh_name_txt, patches_visible):
        patches_1_obj = None

        #----------------Если файл patches_1.pkl существует, получаем данные из него для вывода в форму---------------#

        if patches_visible == True:
            patches_1_path_file = prj_path + '/' + mesh_name_txt + '/' + 'patches_1.pkl'
            if os.path.exists(patches_1_path_file):

                input = open(patches_1_path_file, 'rb')
                patches_1_obj = pickle.load(input)
                input.close()

        main_lbl = QLabel()
        if int_lng == 'Russian':
            main_lbl.setText("Список патчей")
        elif int_lng == 'English':
            main_lbl.setText("List of patches")

        #-------------Формируем внешний вид формы для файла patches_1.pkl на основе данных файла initial.pkl----------#

        initial_path_file = prj_path + '/' + mesh_name_txt + '/' + 'initial.pkl'
        if os.path.exists(initial_path_file):

            input = open(initial_path_file, 'rb')
            obj = pickle.load(input)
            input.close()

            i = 0
            n = 1

            prs_vbox = QVBoxLayout()
            pne_list = []
            pte_list = []
            cnl_list = []
            cne_list = []
            fne_list = []
            patch_def_list = []
            while n <= obj['nop']:
                patch_def = QLabel()
                patch_def.setStyleSheet("color: darkBlue;")
                patch_def_list.append(patch_def)

                p_lbl = QLabel()

                regexp = QtCore.QRegExp('[a-zA-Z]+')
                validator = QtGui.QRegExpValidator(regexp)

                patch_name_lbl = QLabel()
                patch_name_edit = QLineEdit()
                if patches_1_obj != None:
                    patch_name_edit.setText(patches_1_obj[i]['patch_' +
                                                             str(n)])
                patch_name_edit.setFixedSize(110, 21)
                patch_name_edit.setValidator(validator)
                pne_list.append(patch_name_edit)

                patch_type_lbl = QLabel("Тип: ")
                patch_type_edit = QComboBox()
                if patches_1_obj != None:
                    patch_type_edit_mas = patch_type_edit.count()
                    for bvc in range(patch_type_edit_mas):
                        if patch_type_edit.itemText(bvc) == patches_1_obj[i][
                                'type_' + str(n)]:
                            patch_type_edit.setCurrentIndex(bvc)
                patch_type_edit.setFixedSize(120, 21)
                patch_list = [
                    "patch", "symmetryPlane", "empty", "wedge", "cyclic",
                    "wall", "processor"
                ]
                patch_type_edit.addItems(patch_list)
                pte_list.append(patch_type_edit)

                cycl_name_lbl = QLabel()
                cycl_name_lbl.setVisible(False)
                cycl_name_edit = QLineEdit()
                if patches_1_obj != None and patches_1_obj[i][
                        'type_' + str(n)] == "cyclic":
                    cycl_name_edit.setVisible(True)
                    cycl_name_edit.setText(patches_1_obj[i]['neighb_' +
                                                            str(n)])
                cycl_name_edit.setFixedSize(90, 21)
                cycl_name_edit.setVisible(False)
                cycl_name_edit.setValidator(validator)
                cnl_list.append(cycl_name_lbl)
                cne_list.append(cycl_name_edit)

                faces_numb_lbl = QLabel()
                faces_numb_edit = QSpinBox()
                if patches_1_obj != None:
                    faces_numb_edit.setValue(patches_1_obj[i]['faces_' +
                                                              str(n)])
                faces_numb_edit.setRange(1, 100)
                faces_numb_edit.setFixedSize(50, 22)
                fne_list.append(faces_numb_edit)

                prs_grid = QGridLayout()
                prs_grid.addWidget(patch_name_lbl, i, 0)
                prs_grid.addWidget(patch_name_edit, i, 1)
                prs_grid.addWidget(patch_type_lbl, i, 2)
                prs_grid.addWidget(patch_type_edit, i, 3)
                prs_grid.addWidget(cycl_name_lbl, i, 4)
                prs_grid.addWidget(cycl_name_edit, i, 5)
                prs_grid.addWidget(faces_numb_lbl, i, 6)
                prs_grid.addWidget(faces_numb_edit, i, 7)
                prs_grid.addWidget(p_lbl, i, 8)

                prs_vbox.addWidget(patch_def, alignment=QtCore.Qt.AlignCenter)
                prs_vbox.addLayout(prs_grid)

                if int_lng == 'Russian':
                    patch_def.setText("Универсальный патч")
                    p_lbl.setText("// " + "Патч_" + str(n))

                    patch_name_lbl.setText("Название: ")
                    patch_name_edit.setToolTip("Имя патча " + str(n) +
                                               ", формирующего границу сетки")
                    patch_type_edit.setToolTip("Тип патча " + str(n) +
                                               ", формирующего границу сетки")

                    cycl_name_lbl.setText("Сосед: ")
                    cycl_name_edit.setToolTip("Имя циклического патча")

                    faces_numb_lbl.setText("Количество граней: ")
                    faces_numb_edit.setToolTip(
                        "Количество граней блока, составляющих патч")

                elif int_lng == 'English':
                    patch_def.setText("Universal patch")
                    p_lbl.setText("// " + "Patch_" + str(n))

                    patch_name_lbl.setText("Name: ")
                    patch_name_edit.setToolTip("Patch name " + str(n) +
                                               ", forming the mesh boundary")
                    patch_type_edit.setToolTip("Patch type " + str(n) +
                                               ", forming the mesh boundary")

                    cycl_name_lbl.setText("Neighbour: ")
                    cycl_name_edit.setToolTip("Name of the cyclic patch")

                    faces_numb_lbl.setText("Number of faces: ")
                    faces_numb_edit.setToolTip(
                        "Number of block edges making up the patch")

                i = i + 1
                n = n + 1

            prs_frame = QFrame()
            prs_frame.setLayout(prs_vbox)

            # -----------------------Кнопка сохранения------------------------#

            patches_1_btnSave = QPushButton()
            patches_1_btnSave.setFixedSize(80, 25)
            buttons_hbox = QHBoxLayout()
            buttons_hbox.addWidget(patches_1_btnSave)
            if int_lng == 'Russian':
                patches_1_btnSave.setText("Записать")
            elif int_lng == 'English':
                patches_1_btnSave.setText("Write")

            # ---------------------Групповой элемент формы--------------------#

            patches_1_grid = QGridLayout()
            patches_1_grid.addWidget(main_lbl,
                                     0,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
            patches_1_grid.addWidget(prs_frame,
                                     1,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
            patches_1_grid.addLayout(buttons_hbox,
                                     2,
                                     0,
                                     alignment=QtCore.Qt.AlignCenter)
            patches_1_grid.setRowStretch(3, 6)
            patches_1_group = QGroupBox()
            patches_1_group.setLayout(patches_1_grid)

            return patches_1_group, patches_1_btnSave, pne_list, pte_list, cnl_list, cne_list, fne_list, patch_def_list
Example #55
0
class GuiWritingStats(QDialog):

    C_TIME = 0
    C_LENGTH = 1
    C_IDLE = 2
    C_COUNT = 3
    C_BAR = 4

    FMT_JSON = 0
    FMT_CSV = 1

    def __init__(self, theParent, theProject):
        QDialog.__init__(self, theParent)

        logger.debug("Initialising GuiWritingStats ...")
        self.setObjectName("GuiWritingStats")

        self.mainConf = nw.CONFIG
        self.theParent = theParent
        self.theProject = theProject
        self.theTheme = theParent.theTheme
        self.optState = theProject.optState

        self.logData = []
        self.filterData = []
        self.timeFilter = 0.0
        self.wordOffset = 0

        self.setWindowTitle(self.tr("Writing Statistics"))
        self.setMinimumWidth(self.mainConf.pxInt(420))
        self.setMinimumHeight(self.mainConf.pxInt(400))
        self.resize(
            self.mainConf.pxInt(
                self.optState.getInt("GuiWritingStats", "winWidth", 550)),
            self.mainConf.pxInt(
                self.optState.getInt("GuiWritingStats", "winHeight", 500)))

        # List Box
        wCol0 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol0", 180))
        wCol1 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol1", 80))
        wCol2 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol2", 80))
        wCol3 = self.mainConf.pxInt(
            self.optState.getInt("GuiWritingStats", "widthCol3", 80))

        self.listBox = QTreeWidget()
        self.listBox.setHeaderLabels([
            self.tr("Session Start"),
            self.tr("Length"),
            self.tr("Idle"),
            self.tr("Words"),
            self.tr("Histogram"),
        ])
        self.listBox.setIndentation(0)
        self.listBox.setColumnWidth(self.C_TIME, wCol0)
        self.listBox.setColumnWidth(self.C_LENGTH, wCol1)
        self.listBox.setColumnWidth(self.C_IDLE, wCol2)
        self.listBox.setColumnWidth(self.C_COUNT, wCol3)

        hHeader = self.listBox.headerItem()
        hHeader.setTextAlignment(self.C_LENGTH, Qt.AlignRight)
        hHeader.setTextAlignment(self.C_IDLE, Qt.AlignRight)
        hHeader.setTextAlignment(self.C_COUNT, Qt.AlignRight)

        sortValid = (Qt.AscendingOrder, Qt.DescendingOrder)
        sortCol = self.optState.validIntRange(
            self.optState.getInt("GuiWritingStats", "sortCol", 0), 0, 2, 0)
        sortOrder = self.optState.validIntTuple(
            self.optState.getInt("GuiWritingStats", "sortOrder",
                                 Qt.DescendingOrder), sortValid,
            Qt.DescendingOrder)
        self.listBox.sortByColumn(sortCol, sortOrder)
        self.listBox.setSortingEnabled(True)

        # Word Bar
        self.barHeight = int(round(0.5 * self.theTheme.fontPixelSize))
        self.barWidth = self.mainConf.pxInt(200)
        self.barImage = QPixmap(self.barHeight, self.barHeight)
        self.barImage.fill(self.palette().highlight().color())

        # Session Info
        self.infoBox = QGroupBox(self.tr("Sum Totals"), self)
        self.infoForm = QGridLayout(self)
        self.infoBox.setLayout(self.infoForm)

        self.labelTotal = QLabel(formatTime(0))
        self.labelTotal.setFont(self.theTheme.guiFontFixed)
        self.labelTotal.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.labelIdleT = QLabel(formatTime(0))
        self.labelIdleT.setFont(self.theTheme.guiFontFixed)
        self.labelIdleT.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.labelFilter = QLabel(formatTime(0))
        self.labelFilter.setFont(self.theTheme.guiFontFixed)
        self.labelFilter.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.novelWords = QLabel("0")
        self.novelWords.setFont(self.theTheme.guiFontFixed)
        self.novelWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.notesWords = QLabel("0")
        self.notesWords.setFont(self.theTheme.guiFontFixed)
        self.notesWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        self.totalWords = QLabel("0")
        self.totalWords.setFont(self.theTheme.guiFontFixed)
        self.totalWords.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

        lblTTime = QLabel(self.tr("Total Time:"))
        lblITime = QLabel(self.tr("Idle Time:"))
        lblFTime = QLabel(self.tr("Filtered Time:"))
        lblNvCount = QLabel(self.tr("Novel Word Count:"))
        lblNtCount = QLabel(self.tr("Notes Word Count:"))
        lblTtCount = QLabel(self.tr("Total Word Count:"))

        self.infoForm.addWidget(lblTTime, 0, 0)
        self.infoForm.addWidget(lblITime, 1, 0)
        self.infoForm.addWidget(lblFTime, 2, 0)
        self.infoForm.addWidget(lblNvCount, 3, 0)
        self.infoForm.addWidget(lblNtCount, 4, 0)
        self.infoForm.addWidget(lblTtCount, 5, 0)

        self.infoForm.addWidget(self.labelTotal, 0, 1)
        self.infoForm.addWidget(self.labelIdleT, 1, 1)
        self.infoForm.addWidget(self.labelFilter, 2, 1)
        self.infoForm.addWidget(self.novelWords, 3, 1)
        self.infoForm.addWidget(self.notesWords, 4, 1)
        self.infoForm.addWidget(self.totalWords, 5, 1)

        self.infoForm.setRowStretch(6, 1)

        # Filter Options
        sPx = self.theTheme.baseIconSize

        self.filterBox = QGroupBox(self.tr("Filters"), self)
        self.filterForm = QGridLayout(self)
        self.filterBox.setLayout(self.filterForm)

        self.incNovel = QSwitch(width=2 * sPx, height=sPx)
        self.incNovel.setChecked(
            self.optState.getBool("GuiWritingStats", "incNovel", True))
        self.incNovel.clicked.connect(self._updateListBox)

        self.incNotes = QSwitch(width=2 * sPx, height=sPx)
        self.incNotes.setChecked(
            self.optState.getBool("GuiWritingStats", "incNotes", True))
        self.incNotes.clicked.connect(self._updateListBox)

        self.hideZeros = QSwitch(width=2 * sPx, height=sPx)
        self.hideZeros.setChecked(
            self.optState.getBool("GuiWritingStats", "hideZeros", True))
        self.hideZeros.clicked.connect(self._updateListBox)

        self.hideNegative = QSwitch(width=2 * sPx, height=sPx)
        self.hideNegative.setChecked(
            self.optState.getBool("GuiWritingStats", "hideNegative", False))
        self.hideNegative.clicked.connect(self._updateListBox)

        self.groupByDay = QSwitch(width=2 * sPx, height=sPx)
        self.groupByDay.setChecked(
            self.optState.getBool("GuiWritingStats", "groupByDay", False))
        self.groupByDay.clicked.connect(self._updateListBox)

        self.showIdleTime = QSwitch(width=2 * sPx, height=sPx)
        self.showIdleTime.setChecked(
            self.optState.getBool("GuiWritingStats", "showIdleTime", False))
        self.showIdleTime.clicked.connect(self._updateListBox)

        self.filterForm.addWidget(QLabel(self.tr("Count novel files")), 0, 0)
        self.filterForm.addWidget(QLabel(self.tr("Count note files")), 1, 0)
        self.filterForm.addWidget(QLabel(self.tr("Hide zero word count")), 2,
                                  0)
        self.filterForm.addWidget(QLabel(self.tr("Hide negative word count")),
                                  3, 0)
        self.filterForm.addWidget(QLabel(self.tr("Group entries by day")), 4,
                                  0)
        self.filterForm.addWidget(QLabel(self.tr("Show idle time")), 5, 0)
        self.filterForm.addWidget(self.incNovel, 0, 1)
        self.filterForm.addWidget(self.incNotes, 1, 1)
        self.filterForm.addWidget(self.hideZeros, 2, 1)
        self.filterForm.addWidget(self.hideNegative, 3, 1)
        self.filterForm.addWidget(self.groupByDay, 4, 1)
        self.filterForm.addWidget(self.showIdleTime, 5, 1)
        self.filterForm.setRowStretch(6, 1)

        # Settings
        self.histMax = QSpinBox(self)
        self.histMax.setMinimum(100)
        self.histMax.setMaximum(100000)
        self.histMax.setSingleStep(100)
        self.histMax.setValue(
            self.optState.getInt("GuiWritingStats", "histMax", 2000))
        self.histMax.valueChanged.connect(self._updateListBox)

        self.optsBox = QHBoxLayout()
        self.optsBox.addStretch(1)
        self.optsBox.addWidget(
            QLabel(self.tr("Word count cap for the histogram")), 0)
        self.optsBox.addWidget(self.histMax, 0)

        # Buttons
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.rejected.connect(self._doClose)

        self.btnClose = self.buttonBox.addButton(QDialogButtonBox.Close)
        self.btnClose.setAutoDefault(False)

        self.btnSave = self.buttonBox.addButton(self.tr("Save As"),
                                                QDialogButtonBox.ActionRole)
        self.btnSave.setAutoDefault(False)

        self.saveMenu = QMenu(self)
        self.btnSave.setMenu(self.saveMenu)

        self.saveJSON = QAction(self.tr("JSON Data File (.json)"), self)
        self.saveJSON.triggered.connect(lambda: self._saveData(self.FMT_JSON))
        self.saveMenu.addAction(self.saveJSON)

        self.saveCSV = QAction(self.tr("CSV Data File (.csv)"), self)
        self.saveCSV.triggered.connect(lambda: self._saveData(self.FMT_CSV))
        self.saveMenu.addAction(self.saveCSV)

        # Assemble
        self.outerBox = QGridLayout()
        self.outerBox.addWidget(self.listBox, 0, 0, 1, 2)
        self.outerBox.addLayout(self.optsBox, 1, 0, 1, 2)
        self.outerBox.addWidget(self.infoBox, 2, 0)
        self.outerBox.addWidget(self.filterBox, 2, 1)
        self.outerBox.addWidget(self.buttonBox, 3, 0, 1, 2)
        self.outerBox.setRowStretch(0, 1)

        self.setLayout(self.outerBox)

        logger.debug("GuiWritingStats initialisation complete")

        return

    def populateGUI(self):
        """Populate list box with data from the log file.
        """
        qApp.setOverrideCursor(QCursor(Qt.WaitCursor))
        self._loadLogFile()
        self._updateListBox()
        qApp.restoreOverrideCursor()
        return

    ##
    #  Slots
    ##

    def _doClose(self):
        """Save the state of the window, clear cache, end close.
        """
        self.logData = []

        winWidth = self.mainConf.rpxInt(self.width())
        winHeight = self.mainConf.rpxInt(self.height())
        widthCol0 = self.mainConf.rpxInt(self.listBox.columnWidth(0))
        widthCol1 = self.mainConf.rpxInt(self.listBox.columnWidth(1))
        widthCol2 = self.mainConf.rpxInt(self.listBox.columnWidth(2))
        widthCol3 = self.mainConf.rpxInt(self.listBox.columnWidth(3))
        sortCol = self.listBox.sortColumn()
        sortOrder = self.listBox.header().sortIndicatorOrder()
        incNovel = self.incNovel.isChecked()
        incNotes = self.incNotes.isChecked()
        hideZeros = self.hideZeros.isChecked()
        hideNegative = self.hideNegative.isChecked()
        groupByDay = self.groupByDay.isChecked()
        showIdleTime = self.showIdleTime.isChecked()
        histMax = self.histMax.value()

        self.optState.setValue("GuiWritingStats", "winWidth", winWidth)
        self.optState.setValue("GuiWritingStats", "winHeight", winHeight)
        self.optState.setValue("GuiWritingStats", "widthCol0", widthCol0)
        self.optState.setValue("GuiWritingStats", "widthCol1", widthCol1)
        self.optState.setValue("GuiWritingStats", "widthCol2", widthCol2)
        self.optState.setValue("GuiWritingStats", "widthCol3", widthCol3)
        self.optState.setValue("GuiWritingStats", "sortCol", sortCol)
        self.optState.setValue("GuiWritingStats", "sortOrder", sortOrder)
        self.optState.setValue("GuiWritingStats", "incNovel", incNovel)
        self.optState.setValue("GuiWritingStats", "incNotes", incNotes)
        self.optState.setValue("GuiWritingStats", "hideZeros", hideZeros)
        self.optState.setValue("GuiWritingStats", "hideNegative", hideNegative)
        self.optState.setValue("GuiWritingStats", "groupByDay", groupByDay)
        self.optState.setValue("GuiWritingStats", "showIdleTime", showIdleTime)
        self.optState.setValue("GuiWritingStats", "histMax", histMax)

        self.optState.saveSettings()
        self.close()

        return

    def _saveData(self, dataFmt):
        """Save the content of the list box to a file.
        """
        fileExt = ""
        textFmt = ""

        if dataFmt == self.FMT_JSON:
            fileExt = "json"
            textFmt = self.tr("JSON Data File")
        elif dataFmt == self.FMT_CSV:
            fileExt = "csv"
            textFmt = self.tr("CSV Data File")
        else:
            return False

        # Generate the file name
        saveDir = self.mainConf.lastPath
        if not os.path.isdir(saveDir):
            saveDir = os.path.expanduser("~")

        fileName = "sessionStats.%s" % fileExt
        savePath = os.path.join(saveDir, fileName)

        savePath, _ = QFileDialog.getSaveFileName(
            self, self.tr("Save Data As"), savePath,
            "%s (*.%s)" % (textFmt, fileExt))
        if not savePath:
            return False

        self.mainConf.setLastPath(savePath)

        # Do the actual writing
        wSuccess = False
        errMsg = ""

        try:
            with open(savePath, mode="w", encoding="utf8") as outFile:
                if dataFmt == self.FMT_JSON:
                    jsonData = []
                    for _, sD, tT, wD, wA, wB, tI in self.filterData:
                        jsonData.append({
                            "date": sD,
                            "length": tT,
                            "newWords": wD,
                            "novelWords": wA,
                            "noteWords": wB,
                            "idleTime": tI,
                        })
                    json.dump(jsonData, outFile, indent=2)
                    wSuccess = True

                if dataFmt == self.FMT_CSV:
                    outFile.write(
                        '"Date","Length (sec)","Words Changed",'
                        '"Novel Words","Note Words","Idle Time (sec)"\n')
                    for _, sD, tT, wD, wA, wB, tI in self.filterData:
                        outFile.write(f'"{sD}",{tT:.0f},{wD},{wA},{wB},{tI}\n')
                    wSuccess = True

        except Exception as e:
            errMsg = str(e)
            wSuccess = False

        # Report to user
        if wSuccess:
            self.theParent.makeAlert(
                "%s file successfully written to:<br>%s" % (textFmt, savePath),
                nwAlert.INFO)
        else:
            self.theParent.makeAlert(
                "Failed to write %s file.<br>%s" % (textFmt, errMsg),
                nwAlert.ERROR)

        return wSuccess

    ##
    #  Internal Functions
    ##

    def _loadLogFile(self):
        """Load the content of the log file into a buffer.
        """
        logger.debug("Loading session log file")

        self.logData = []
        self.wordOffset = 0

        ttNovel = 0
        ttNotes = 0
        ttTime = 0
        ttIdle = 0

        logFile = os.path.join(self.theProject.projMeta, nwFiles.SESS_STATS)
        if not os.path.isfile(logFile):
            logger.info("This project has no writing stats logfile")
            return False

        try:
            with open(logFile, mode="r", encoding="utf8") as inFile:
                for inLine in inFile:
                    if inLine.startswith("#"):
                        if inLine.startswith("# Offset"):
                            self.wordOffset = checkInt(inLine[9:].strip(), 0)
                            logger.verbose(
                                "Initial word count when log was started is %d"
                                % self.wordOffset)
                        continue

                    inData = inLine.split()
                    if len(inData) < 6:
                        continue

                    dStart = datetime.strptime(
                        "%s %s" % (inData[0], inData[1]), nwConst.FMT_TSTAMP)
                    dEnd = datetime.strptime("%s %s" % (inData[2], inData[3]),
                                             nwConst.FMT_TSTAMP)

                    sIdle = 0
                    if len(inData) > 6:
                        sIdle = checkInt(inData[6], 0)

                    tDiff = dEnd - dStart
                    sDiff = tDiff.total_seconds()
                    ttTime += sDiff
                    ttIdle += sIdle

                    wcNovel = int(inData[4])
                    wcNotes = int(inData[5])
                    ttNovel = wcNovel
                    ttNotes = wcNotes

                    self.logData.append(
                        (dStart, sDiff, wcNovel, wcNotes, sIdle))

        except Exception as e:
            self.theParent.makeAlert(
                [self.tr("Failed to read session log file."),
                 str(e)], nwAlert.ERROR)
            return False

        ttWords = ttNovel + ttNotes
        self.labelTotal.setText(formatTime(round(ttTime)))
        self.labelIdleT.setText(formatTime(round(ttIdle)))
        self.novelWords.setText(f"{ttNovel:n}")
        self.notesWords.setText(f"{ttNotes:n}")
        self.totalWords.setText(f"{ttWords:n}")

        return True

    ##
    #  Slots
    ##

    def _updateListBox(self, dummyVar=None):
        """Load/reload the content of the list box. The dummyVar
        variable captures the variable sent from the widgets connecting
        to it and discards it.
        """
        self.listBox.clear()
        self.timeFilter = 0.0

        incNovel = self.incNovel.isChecked()
        incNotes = self.incNotes.isChecked()
        hideZeros = self.hideZeros.isChecked()
        hideNegative = self.hideNegative.isChecked()
        groupByDay = self.groupByDay.isChecked()
        histMax = self.histMax.value()

        # Group the data
        if groupByDay:
            tempData = []
            sessDate = None
            sessTime = 0
            sessIdle = 0
            lstNovel = 0
            lstNotes = 0

            for n, (dStart, sDiff, wcNovel, wcNotes,
                    sIdle) in enumerate(self.logData):
                if n == 0:
                    sessDate = dStart.date()
                if sessDate != dStart.date():
                    tempData.append(
                        (sessDate, sessTime, lstNovel, lstNotes, sessIdle))
                    sessDate = dStart.date()
                    sessTime = sDiff
                    sessIdle = sIdle
                    lstNovel = wcNovel
                    lstNotes = wcNotes
                else:
                    sessTime += sDiff
                    sessIdle += sIdle
                    lstNovel = wcNovel
                    lstNotes = wcNotes

            if sessDate is not None:
                tempData.append(
                    (sessDate, sessTime, lstNovel, lstNotes, sessIdle))

        else:
            tempData = self.logData

        # Calculate Word Diff
        self.filterData = []
        pcTotal = 0
        listMax = 0
        isFirst = True
        for dStart, sDiff, wcNovel, wcNotes, sIdle in tempData:

            wcTotal = 0
            if incNovel:
                wcTotal += wcNovel
            if incNotes:
                wcTotal += wcNotes

            dwTotal = wcTotal - pcTotal
            if hideZeros and dwTotal == 0:
                continue
            if hideNegative and dwTotal < 0:
                pcTotal = wcTotal
                continue

            if isFirst:
                # Subtract the offset from the first list entry
                dwTotal -= self.wordOffset
                dwTotal = max(dwTotal, 1)  # Don't go zero or negative
                isFirst = False

            if groupByDay:
                sStart = dStart.strftime(nwConst.FMT_DSTAMP)
            else:
                sStart = dStart.strftime(nwConst.FMT_TSTAMP)

            self.filterData.append(
                (dStart, sStart, sDiff, dwTotal, wcNovel, wcNotes, sIdle))
            listMax = min(max(listMax, dwTotal), histMax)
            pcTotal = wcTotal

        # Populate the list
        showIdleTime = self.showIdleTime.isChecked()
        for _, sStart, sDiff, nWords, _, _, sIdle in self.filterData:

            if showIdleTime:
                idleEntry = formatTime(sIdle)
            else:
                sRatio = sIdle / sDiff if sDiff > 0.0 else 0.0
                idleEntry = "%d %%" % round(100.0 * sRatio)

            newItem = QTreeWidgetItem()
            newItem.setText(self.C_TIME, sStart)
            newItem.setText(self.C_LENGTH, formatTime(round(sDiff)))
            newItem.setText(self.C_IDLE, idleEntry)
            newItem.setText(self.C_COUNT, f"{nWords:n}")

            if nWords > 0 and listMax > 0:
                theBar = self.barImage.scaled(
                    int(200 * min(nWords, histMax) / listMax), self.barHeight,
                    Qt.IgnoreAspectRatio, Qt.FastTransformation)
                newItem.setData(self.C_BAR, Qt.DecorationRole, theBar)

            newItem.setTextAlignment(self.C_LENGTH, Qt.AlignRight)
            newItem.setTextAlignment(self.C_IDLE, Qt.AlignRight)
            newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight)
            newItem.setTextAlignment(self.C_BAR,
                                     Qt.AlignLeft | Qt.AlignVCenter)

            newItem.setFont(self.C_TIME, self.theTheme.guiFontFixed)
            newItem.setFont(self.C_LENGTH, self.theTheme.guiFontFixed)
            newItem.setFont(self.C_COUNT, self.theTheme.guiFontFixed)
            if showIdleTime:
                newItem.setFont(self.C_IDLE, self.theTheme.guiFontFixed)
            else:
                newItem.setFont(self.C_IDLE, self.theTheme.guiFont)

            self.listBox.addTopLevelItem(newItem)
            self.timeFilter += sDiff

        self.labelFilter.setText(formatTime(round(self.timeFilter)))

        return True
Example #56
0
class RSADemoChatApp(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'RSA Message Encyption & Decryption demo app'
        self.left = 0
        self.top = 0
        self.width = 720
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)

        self.setGeometry(self.left, self.top, self.width, self.height)

        self.createGridLayout()

        self.windowLayout = QVBoxLayout()
        self.windowLayout.addWidget(self.horizontalGroupBox)
        self.setLayout(self.windowLayout)

        self.show()

    def createGridLayout(self):
        self.horizontalGroupBox = QGroupBox()
        self.layout = QGridLayout()
        """
        Add UI elements below
        """
        # Create a separate layout to group the private/public key UI elements
        keyLayout = QGridLayout()

        # Add the public key display field
        publicKeyLabel = QLabel("Public Key: ")
        self.publicKeyField = QLineEdit(self)
        keyLayout.addWidget(publicKeyLabel, 0, 0)
        keyLayout.addWidget(self.publicKeyField, 0, 1)

        # Add the private key display field
        privateKeyLabel = QLabel("Private Key: ")
        self.privateKeyField = QLineEdit(self)
        keyLayout.addWidget(privateKeyLabel, 0, 2)
        keyLayout.addWidget(self.privateKeyField, 0, 3)

        # Add a text field for specifiying the key size
        keySizeLabel = QLabel("Keysize: ")
        self.keySizeField = QLineEdit(self)
        self.keySizeField.setText(str(32))
        keyLayout.addWidget(keySizeLabel, 1, 0)
        keyLayout.addWidget(self.keySizeField, 1, 1)

        # Add the generate key button
        generateKeysButton = QPushButton('Generate Keys', self)
        generateKeysButton.clicked.connect(self.generate_keypair_ev)
        generateKeysButton.setToolTip('Generates a Public/Private RSA Keypair')
        keyLayout.addWidget(generateKeysButton, 0, 4)

        # Add the input text field
        self.messageInputField = QPlainTextEdit(self)
        self.messageInputField.insertPlainText(
            "Write message to encrypt/decrypt here....")

        # Add the output text field
        self.messageOutputField = QPlainTextEdit(self)
        self.messageOutputField.setReadOnly(True)

        # Add encrypt button
        encryptButton = QPushButton('Encrypt', self)
        encryptButton.clicked.connect(self.encrypt_ev)
        encryptButton.setToolTip('Encrypts a message using the RSA algorithm')

        # Add decrypt button
        decryptButton = QPushButton('Decrypt', self)
        decryptButton.clicked.connect(self.decrypt_ev)
        decryptButton.setToolTip(
            'Decrypts a message encrypted by the RSA algorithm')

        # Add everything to the grid layout (so the items display)
        self.layout.addLayout(keyLayout, 0, 0)
        self.layout.addWidget(self.messageInputField, 1, 0)
        self.layout.addWidget(encryptButton, 1, 1)
        self.layout.addWidget(self.messageOutputField, 2, 0)
        self.layout.addWidget(decryptButton, 2, 1)

        self.horizontalGroupBox.setLayout(self.layout)

    @pyqtSlot()
    def encrypt_ev(self):
        privateKey = [
            int(i) for i in self.privateKeyField.text().strip("()").split(",")
        ]
        encrypted_msg = encrypt(privateKey,
                                self.messageInputField.toPlainText())
        self.messageOutputField.setPlainText(" ".join(
            map(lambda x: str(x), encrypted_msg)))

    @pyqtSlot()
    def decrypt_ev(self):
        publicKey = [
            int(i) for i in self.publicKeyField.text().strip("()").split(",")
        ]
        decrypted_msg = decrypt(
            publicKey,
            [int(i) for i in self.messageInputField.toPlainText().split(" ")])
        self.messageOutputField.setPlainText(str(decrypted_msg))

    @pyqtSlot()
    def generate_keypair_ev(self):
        print("Generating your public/private keypairs now . . .")
        publicKey, privateKey = generate_keypair(int(self.keySizeField.text()))
        # Index 1 should be the public key text field
        self.publicKeyField.setText(str(publicKey))
        # Index 3 should be the private key text field
        self.privateKeyField.setText(str(privateKey))
Example #57
0
 def __initUI(self):
     layout =  QGridLayout()
     layout.addLayout(self.__leftPanelBuilder(), 0, 0, 1, 5)
     layout.addLayout(self.__rightPanelBuilder(), 0, 5, 1, 10)
     self.setLayout(layout)
Example #58
0
class window_qc(QMainWindow):
    def __init__(self, parent, lan=0):
        super(window_qc, self).__init__(parent)
        self.temp = parent
        self.setGeometry(303, 304, 500, 350)  # 设置子窗口的尺寸
        self.setMinimumSize(200, 130)  # 设置子窗口的最小尺寸
        self.lan = lan
        self.path_cbf = ""
        self.path_gm = ""
        self.path_wm = ""
        self.path_noise = ""
        self.path_local = os.path.realpath(__file__)

        self.initUI()

    def initUI(self):
        if self.lan == 0:
            self.label_dir = QLabel("Directory:", self)
            self.label_cbf = QLabel("Whole Brain", self)
            self.label_gm = QLabel("Gray Matter(Optional)", self)
            self.label_wm = QLabel("White Matter(Optional)", self)
            self.label_noise = QLabel("Noise(Optional)", self)
            self.label_mode = QLabel("Mode:", self)
            self.rb_mode_quick = QRadioButton("Quick", self)
            self.rb_mode_detail = QRadioButton("Detail", self)
            # self.label_snr = QLabel("SNR:", self)
            # self.cb_snr_full = QCheckBox("Whole Image", self)
            # self.cb_snr_gm = QCheckBox("Grey Matter", self)
            # self.cb_snr_wm = QCheckBox("White Matter", self)
            # self.cb_cnr = QCheckBox("CNR", self)
            # self.cb_fber = QCheckBox("FBER", self)
            # self.cb_cjv = QCheckBox("CJV", self)
            # self.cb_efc = QCheckBox("EFC", self)
            # self.cb_wm2max = QCheckBox("WM/Max", self)
        elif self.lan == 1:
            self.label_dir = QLabel("路径:", self)
            self.label_cbf = QLabel("全脑", self)
            self.label_gm = QLabel("灰质(可选)", self)
            self.label_wm = QLabel("白质(可选)", self)
            self.label_noise = QLabel("噪声(可选)", self)
            self.label_mode = QLabel("模式:", self)
            self.rb_mode_quick = QRadioButton("快速", self)
            self.rb_mode_detail = QRadioButton("全面", self)
            # self.label_snr = QLabel("信噪比:", self)
            # self.cb_snr_full = QCheckBox("完整图像", self)
            # self.cb_snr_gm = QCheckBox("灰质", self)
            # self.cb_snr_wm = QCheckBox("白质", self)
            # self.cb_cnr = QCheckBox("对比噪声比", self)
            # self.cb_fber = QCheckBox("频带能量比", self)
            # self.cb_cjv = QCheckBox("联合变异系数", self)
            # self.cb_efc = QCheckBox("熵集聚系数", self)
            # self.cb_wm2max = QCheckBox("白质/最大值比", self)
        self.value_dir_cbf = QLineEdit(self)
        self.value_dir_gm = QLineEdit(self)
        self.value_dir_wm = QLineEdit(self)
        self.bt_dir_cbf = QPushButton("...", self)
        self.bt_dir_gm = QPushButton("...", self)
        self.bt_dir_wm = QPushButton("...", self)
        self.bt_operate = QPushButton("OK", self)

        self.group_mode = QButtonGroup(self)
        self.group_mode.addButton(self.rb_mode_quick, 1)
        self.group_mode.addButton(self.rb_mode_detail, 2)

        self.grid_full = QGridLayout()
        self.grid_dir = QGridLayout()
        self.grid_opt = QGridLayout()
        self.rb_mode_detail.setChecked(True)

        self.grid_opt.addWidget(self.label_mode, 0, 0)
        self.grid_opt.addWidget(self.rb_mode_quick, 1, 0)
        self.grid_opt.addWidget(self.rb_mode_detail, 1, 1)

        self.grid_dir.addWidget(self.label_dir, 0, 0)
        self.grid_dir.addWidget(self.label_cbf, 0, 1)
        self.grid_dir.addWidget(self.value_dir_cbf, 0, 2)
        self.grid_dir.addWidget(self.bt_dir_cbf, 0, 3)
        self.grid_dir.addWidget(self.label_gm, 1, 1)
        self.grid_dir.addWidget(self.value_dir_gm, 1, 2)
        self.grid_dir.addWidget(self.bt_dir_gm, 1, 3)
        self.grid_dir.addWidget(self.label_wm, 2, 1)
        self.grid_dir.addWidget(self.value_dir_wm, 2, 2)
        self.grid_dir.addWidget(self.bt_dir_wm, 2, 3)

        self.grid_full.addLayout(self.grid_dir, 0, 0)
        self.grid_full.addLayout(self.grid_opt, 1, 0)
        self.grid_full.addWidget(self.bt_operate, 2, 0)

        self.resizeEvent = self.adjustSize

        self.bt_dir_cbf.clicked.connect(self.select_dir_cbf)
        self.bt_dir_gm.clicked.connect(self.select_dir_gm)
        self.bt_dir_wm.clicked.connect(self.select_dir_wm)
        self.bt_operate.clicked.connect(self.pipeline)

    def adjustSize(self, event):
        self.grid_full.setGeometry(
            QRect(50, 50, (self.width() - 100), (self.height() - 100)))

    def select_dir_cbf(self):
        if self.lan == 0:
            if platform.system == "Windows":
                self.path_cbf = QFileDialog.getOpenFileNames(
                    self, 'Select File', './',
                    "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
            elif platform.system == "Linux":
                self.path_cbf = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
            else:
                self.path_cbf = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
        elif self.lan == 1:
            if platform.system == "Windows":
                self.path_cbf = QFileDialog.getOpenFileNames(
                    self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
            elif platform.system == "Linux":
                self.path_cbf = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
            else:
                self.path_cbf = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
        if self.path_cbf == []:
            self.path_cbf = ""
        self.value_dir_cbf.setText(str(self.path_cbf))

    def select_dir_gm(self):
        if self.lan == 0:
            if platform.system == "Windows":
                self.path_gm = QFileDialog.getOpenFileNames(
                    self, 'Select File', './',
                    "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
            elif platform.system == "Linux":
                self.path_gm = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
            else:
                self.path_gm = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
        elif self.lan == 1:
            if platform.system == "Windows":
                self.path_gm = QFileDialog.getOpenFileNames(
                    self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
            elif platform.system == "Linux":
                self.path_gm = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
            else:
                self.path_gm = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
        if self.path_gm == []:
            self.path_gm = ""
        self.value_dir_gm.setText(str(self.path_gm))

    def select_dir_wm(self):
        if self.lan == 0:
            if platform.system == "Windows":
                self.path_wm = QFileDialog.getOpenFileNames(
                    self, 'Select File', './',
                    "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
            elif platform.system == "Linux":
                self.path_wm = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
            else:
                self.path_wm = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
        elif self.lan == 1:
            if platform.system == "Windows":
                self.path_wm = QFileDialog.getOpenFileNames(
                    self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
            elif platform.system == "Linux":
                self.path_wm = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
            else:
                self.path_wm = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
        if self.path_wm == []:
            self.path_wm = ""
        self.value_dir_wm.setText(str(self.path_wm))

    def select_dir_noise(self):
        if self.lan == 0:
            if platform.system == "Windows":
                self.path_noise = QFileDialog.getOpenFileNames(
                    self, 'Select File', './',
                    "Nii Files (*.nii;*.nii.gz);;All Files (*)")[0]
            elif platform.system == "Linux":
                self.path_noise = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
            else:
                self.path_noise = QFileDialog.getOpenFileNames(
                    self, 'Select File', './')[0]
        elif self.lan == 1:
            if platform.system == "Windows":
                self.path_noise = QFileDialog.getOpenFileNames(
                    self, '选择文件', './', "Nii文件(*.nii;*.nii.gz);;所有文件(*)")[0]
            elif platform.system == "Linux":
                self.path_noise = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
            else:
                self.path_noise = QFileDialog.getOpenFileNames(
                    self, '选择文件', './')[0]
        if self.path_noise == []:
            self.path_noise = ""
        self.value_dir_noise.setText(str(self.path_noise))

    def reg_gw(self):
        self.thread_qc = RegThread(self, self.lan)
        self.thread_qc.start()
        if self.lan == 0:
            self.statusBar().showMessage("Working...")
        elif self.lan == 1:
            self.statusBar().showMessage("正忙...")
        self.thread_qc.process.connect(self.update_process)
        self.thread_qc.trigger.connect(self.definition)
        self.thread_qc.file.connect(self.updata_path)

    def definition(self):
        if self.path_noise == "":
            if self.path_cbf != "":
                for item in self.path_cbf:
                    self.thread_mask = MaskThread(self, item, self.lan)
                    self.thread_mask.result.connect(self.calculate)

    def calculate(self):
        self.qc = Qualityratio(data_wb,
                               data_gm,
                               data_wm,
                               data_noise,
                               threshold=0.7)

    def update_process(self, int_process):
        if self.lan == 0:
            self.statusBar().showMessage("File: " + str(int_process) + "/" +
                                         str(len(self.path_cbf)))
        elif self.lan == 1:
            self.statusBar().showMessage("文件: " + str(int_process) + "/" +
                                         str(len(self.path_cbf)))

    def updata_path(self, list_path):
        self.path_gm = list_path

    def pipeline(self):
        if self.rb_mode_detail.isChecked():
            if self.path_gm == "" or self.path_wm == "":
                self.reg_gw()
                data_gm = [
                    ni.load(item.replace(".nii",
                                         "_seg.nii")).get_fdata()[:, :, :, 0]
                    for item in self.path_gm
                ]
                data_wm = [
                    ni.load(item.replace(".nii",
                                         "_seg.nii")).get_fdata()[:, :, :, 1]
                    for item in self.path_wm
                ]

            else:
                self.definition()
Example #59
0
    def personal_details(self):
        group_box = QGroupBox()
        grid = QGridLayout()
        group_box.setLayout(grid)

        group_box.setTitle("Personal Details")

        # for views containing school detail of student
        sd_view = QHBoxLayout()
        sd_detail_view = QGridLayout()

        grid.addLayout(sd_view, 0, 0, 1, 0)

        sd_view.addLayout(sd_detail_view)
        sd_view.addWidget(self.comp.profile_pic)

        r = requests.get(url=self.profile["pic"], stream=True)

        pic = QImage()
        pic.loadFromData(r.content)

        self.comp.profile_pic.setPixmap(QPixmap.fromImage(pic))

        sd_detail_view.addWidget(self.comp.m_num, 0, 0)
        m_num_text = QLabel()
        sd_detail_view.addWidget(m_num_text, 0, 1)
        m_num_text.setText(self.profile["matric_number"])

        sd_detail_view.addWidget(self.comp.j_num, 1, 0)
        j_num_text = QLabel()
        sd_detail_view.addWidget(j_num_text, 1, 1)
        j_num_text.setText(self.profile["jamb_number"])

        sd_detail_view.addWidget(self.comp.college, 2, 0)
        college_text = QLabel()
        sd_detail_view.addWidget(college_text, 2, 1)
        college_text.setText(self.profile["college"])

        sd_detail_view.addWidget(self.comp.dept, 3, 0)
        dept_text = QLabel()
        sd_detail_view.addWidget(dept_text, 3, 1)
        dept_text.setText(self.profile["department"])

        sd_detail_view.addWidget(self.comp.level, 4, 0)
        level_text = QLabel()
        sd_detail_view.addWidget(level_text, 4, 1)
        level_text.setText(self.profile["level"])

        pd_detail_view = QGridLayout()
        name = QLabel("Name:")

        grid.addWidget(name, 1, 0)

        pd_detail_view.addWidget(self.comp.l_name, 0, 0)
        l_name_text = QLabel()
        pd_detail_view.addWidget(l_name_text, 0, 1)
        l_name_text.setText(self.profile["last_name"])

        pd_detail_view.addWidget(self.comp.m_name, 1, 0)
        m_name_text = QLabel()
        pd_detail_view.addWidget(m_name_text, 1, 1)
        m_name_text.setText(self.profile["middle_name"])

        pd_detail_view.addWidget(self.comp.f_name, 2, 0)
        f_name_text = QLabel()
        pd_detail_view.addWidget(f_name_text, 2, 1)
        f_name_text.setText(self.profile["first_name"])

        grid.addLayout(pd_detail_view, 1, 1)

        grid.addWidget(self.comp.age, 2, 0)
        age_text = QLabel()
        grid.addWidget(age_text, 2, 1)
        age_text.setText(str(self.profile["age"]))

        grid.addWidget(self.comp.gender, 3, 0)
        gender_text = QLabel()
        grid.addWidget(gender_text, 3, 1)
        gender_text.setText(self.profile["gender"])

        grid.addWidget(self.comp.dob_label, 4, 0)
        dob_text = QLabel()
        grid.addWidget(dob_text, 4, 1)
        dob_text.setText(str(self.profile["date_of_birth"]))

        grid.addWidget(self.comp.nationality, 5, 0)
        nationality_text = QLabel()
        grid.addWidget(nationality_text, 5, 1)
        nationality_text.setText(self.profile["nationality"])

        grid.addWidget(self.comp.state_origin, 6, 0)
        state_origin_text = QLabel()
        grid.addWidget(state_origin_text, 6, 1)
        state_origin_text.setText(self.profile["state_of_origin"])

        grid.addWidget(self.comp.lga_origin, 7, 0)
        lga_origin_text = QLabel()
        grid.addWidget(lga_origin_text, 7, 1)
        lga_origin_text.setText(self.profile["lga_origin"])

        grid.addWidget(self.comp.marital, 8, 0)
        marital_text = QLabel()
        grid.addWidget(marital_text, 8, 1)
        marital_text.setText(self.profile["marital_status"])

        self.vbox.addWidget(group_box)
Example #60
0
    def createproxyTestPanel(self):
        self.buttonCheckProxy = QPushButton(
            self.translate("proxyTestPanel", "Check..."), self)
        labelproxyhostName = QLabel(
            self.translate("proxyTestPanel", "Proxy Host Name: "), self)
        self.lineEditproxyHostName = QLineEdit(self.proxyhostName)
        labelPort = QLabel(self.translate("proxyTestPanel", "Port: "), self)
        self.spinBoxPort = QSpinBox(self)
        self.spinBoxPort.setRange(0, 65535)
        self.spinBoxPort.setValue(1080)

        hboxPort = QHBoxLayout()
        hboxPort.addWidget(labelPort)
        hboxPort.addWidget(self.spinBoxPort)
        hboxPort.addStretch()

        labelTargethostUrl = QLabel(
            self.translate("proxyTestPanel", "Target Host Url: "), self)
        self.lineEdittargethostUrl = QLineEdit(self.url, self)

        labelProxyProtocol = QLabel(
            self.translate("proxyTestPanel", "Proxy Protocol: "), self)
        radioButtonSocks5 = QRadioButton("Socks5", self)
        radioButtonSocks5.setChecked(True)
        radioButtonHttp = QRadioButton("Http", self)

        self.groupRadioButton = QButtonGroup()
        self.groupRadioButton.addButton(radioButtonSocks5)
        self.groupRadioButton.addButton(radioButtonHttp)

        hboxRadioButtonProxyProtocol = QHBoxLayout()
        hboxRadioButtonProxyProtocol.addWidget(radioButtonSocks5)
        hboxRadioButtonProxyProtocol.addWidget(radioButtonHttp)
        hboxRadioButtonProxyProtocol.addStretch()

        labelProxyStatus = QLabel(
            self.translate("proxyTestPanel", "Proxy Status: "), self)
        labelProxyTimeLag = QLabel(
            self.translate("proxyTestPanel", "Proxy Time Lag: "), self)

        self.labelproxyStatus = QLabel()
        self.labelproxyTimeLag = QLabel()
        labelFont = QFont()
        labelFont.setPointSize(16)
        labelFont.setBold(True)
        self.labelproxyStatus.setFont(labelFont)
        self.labelproxyTimeLag.setFont(labelFont)

        self.palettelabelProxyStatusOK = QPalette()
        self.palettelabelProxyStatusOK.setColor(QPalette.WindowText,
                                                QColor(34, 139,
                                                       34))  # ##ForestGreen
        self.palettelabelProxyStatusFalse = QPalette()
        self.palettelabelProxyStatusFalse.setColor(QPalette.WindowText, Qt.red)

        self.palettelabelProxyTimeLagForestGreen = QPalette()
        self.palettelabelProxyTimeLagForestGreen.setColor(
            QPalette.WindowText, QColor(34, 139, 34))
        self.palettelabelProxyTimeLagDarkOrange = QPalette()
        self.palettelabelProxyTimeLagDarkOrange.setColor(
            QPalette.WindowText, QColor(255, 140, 0))
        self.palettelabelProxyTimeLagRed = QPalette()
        self.palettelabelProxyTimeLagRed.setColor(QPalette.WindowText, Qt.red)

        self.textEditProxy = QTextEdit()
        self.textEditProxy.setReadOnly(True)

        gridBoxProxy = QGridLayout()
        gridBoxProxy.addWidget(labelproxyhostName, 0, 0)
        gridBoxProxy.addWidget(self.lineEditproxyHostName, 0, 1)
        gridBoxProxy.addLayout(hboxPort, 0, 2)
        gridBoxProxy.addWidget(labelTargethostUrl, 1, 0)
        gridBoxProxy.addWidget(self.lineEdittargethostUrl, 1, 1)
        gridBoxProxy.addWidget(labelProxyProtocol, 2, 0)
        gridBoxProxy.addLayout(hboxRadioButtonProxyProtocol, 2, 1)
        gridBoxProxy.addWidget(labelProxyStatus, 3, 0)
        gridBoxProxy.addWidget(self.labelproxyStatus, 3, 1)
        gridBoxProxy.addWidget(labelProxyTimeLag, 4, 0)
        gridBoxProxy.addWidget(self.labelproxyTimeLag, 4, 1)

        hboxButtonCheckProxy = QHBoxLayout()
        hboxButtonCheckProxy.addStretch()
        hboxButtonCheckProxy.addWidget(self.buttonCheckProxy)

        vboxProxy = QVBoxLayout()
        vboxProxy.addLayout(gridBoxProxy)
        vboxProxy.addWidget(self.textEditProxy)
        # vboxProxy.addStretch()
        vboxProxy.addLayout(hboxButtonCheckProxy)

        self.buttonCheckProxy.clicked.connect(self.onButtonCheckProxy)
        self.settingProxyPanel()
        self.setLayout(vboxProxy)