class InputMode(QWidget): def __init__(self, parent=None): super(InputMode, self).__init__(parent) self.is_encrypt = False self.setup_ui() def setup_ui(self): self.btn_switch = QPushButton('Switch Mode') self.btn_execute = QPushButton('Execute') self.lbl_mode_title = QLabel('Mode') self.lbl_colon = QLabel(':') self.lbl_mode_value = QLabel('Encrypt') self.lbl_mode_title.setAlignment(Qt.AlignRight) self.lbl_colon.setAlignment(Qt.AlignCenter) self.lbl_mode_value.setAlignment(Qt.AlignLeft) self.spacer = QSpacerItem(20, 10, QSizePolicy.Fixed, QSizePolicy.Minimum) self.h_layout_1 = QHBoxLayout() self.h_layout_2 = QHBoxLayout() self.v_layout = QVBoxLayout() self.h_layout_1.addWidget(self.lbl_mode_title) self.h_layout_1.addWidget(self.lbl_colon) self.h_layout_1.addWidget(self.lbl_mode_value) self.h_layout_2.addWidget(self.btn_switch) self.h_layout_2.addWidget(self.btn_execute) self.v_layout.addLayout(self.h_layout_1) self.v_layout.addLayout(self.h_layout_2) self.setLayout(self.v_layout) self.btn_switch.clicked.connect(self.switch_mode) self.btn_execute.clicked.connect(self.execute) self.btn_switch.animateClick() def switch_mode(self): self.is_encrypt = not self.is_encrypt if self.is_encrypt: mode = ModeType.ENCRYPT else: mode = ModeType.DECRYPT EncryptionParms.get_instance().mode = mode self.lbl_mode_value.setText(mode.value) def execute(self): EncryptionParms.get_instance().print_info()
def show_popup(self): """Makes the QDialog pop up and creates its layout.""" self.temp_values = self.values dialog = QDialog(self) dialog.setMinimumWidth(300) dialog.setStyleSheet("Text-align:center") dialog.setWindowTitle("Filter " + self.accessibleName() + " by ") dialog.setModal(True) dialog.accepted.connect(self.accept_changes) scroll = QScrollArea(dialog) viewport = QWidget(dialog) scroll.setWidget(viewport) scroll.setWidgetResizable(True) select_all_button = QPushButton("Select all") deselect_all_button = QPushButton("Deselect all") show_all_button = QPushButton("Show visible") ok_button = QPushButton("Ok") cancel_button = QPushButton("Cancel") select_all_button.clicked.connect( lambda: self.set_selection(dialog, True)) deselect_all_button.clicked.connect( lambda: self.set_selection(dialog, False)) show_all_button.clicked.connect(lambda: self.show_all(dialog)) ok_button.clicked.connect(dialog.accept) cancel_button.clicked.connect(dialog.reject) layout = QGridLayout(viewport) viewport.setLayout(layout) self.draw_layout(layout, show_all=True) dialog_layout = QGridLayout(dialog) dialog.setLayout(dialog_layout) dialog.layout().addWidget(select_all_button, 0, 0) dialog.layout().addWidget(deselect_all_button, 0, 1) dialog.layout().addWidget(show_all_button, 0, 2) dialog.layout().addWidget(scroll, 1, 0, 1, -1) dialog.layout().addWidget(ok_button, 2, 1) dialog.layout().addWidget(cancel_button, 2, 2) if self.accessibleName() != "Category": show_all_button.animateClick() else: show_all_button.hide() dialog.exec()
def show_popup(self): """Makes the QDialog pop up and creates its layout.""" self.update_check_state() self.temp_checked = dict(self.checked) dialog = QDialog(self) dialog.setMinimumWidth(300) dialog.setStyleSheet("Text-align:center") dialog.setWindowTitle(self.text) dialog.setModal(True) dialog.accepted.connect(self.accept_changes) scroll = QScrollArea(dialog) viewport = QWidget(dialog) scroll.setWidget(viewport) scroll.setWidgetResizable(True) select_all_button = QPushButton("Select all") deselect_all_button = QPushButton("Deselect all") show_all_button = QPushButton("Show visible") ok_button = QPushButton("Ok") cancel_button = QPushButton("Cancel") select_all_button.clicked.connect( lambda: self.set_selection(dialog, True)) deselect_all_button.clicked.connect( lambda: self.set_selection(dialog, False)) show_all_button.clicked.connect(lambda: self.show_all(dialog)) ok_button.clicked.connect(dialog.accept) cancel_button.clicked.connect(dialog.reject) layout = QGridLayout(viewport) viewport.setLayout(layout) #self.draw_layout(layout, show_all=True) dialog_layout = QGridLayout(dialog) dialog.setLayout(dialog_layout) dialog.layout().addWidget(select_all_button, 0, 0) dialog.layout().addWidget(deselect_all_button, 0, 1) dialog.layout().addWidget(show_all_button, 0, 2) dialog.layout().addWidget(scroll, 1, 0, 1, -1) dialog.layout().addWidget(ok_button, 2, 1) dialog.layout().addWidget(cancel_button, 2, 2) # To get the right QScrollArea show_all_button.animateClick() dialog.exec()
class myReflections(QWidget): def __init__(self): super(myReflections, self).__init__() self.setGeometry(300, 500, 420, 200) self.title = "My Reflections" self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setWindowIcon(QIcon('reflections.png')) self.layout = QVBoxLayout() #self.layout.addStretch(1) self.setLayout(self.layout) self.txt = QTextEdit() self.layout.addWidget(self.txt) self.txt.setFixedSize(400, 100) self.txt.wordWrapMode self.lbl = QLabel(self) self.layout.addWidget(self.lbl) self.lbl.setText("Char: ") self.lbl.setFixedSize(100, 10) self.hbox = QHBoxLayout() #self.hbox.addWidget(QLabel("")) self.enterbtn = QPushButton('Enter') self.enterbtn.setFixedSize(70, 20) self.hbox.addWidget(self.enterbtn) self.enterbtn.animateClick() self.layout.addLayout(self.hbox) self.downbtn = QPushButton('v') self.layout.addWidget(self.downbtn) self.downbtn.resize(10, 10) self.downbtn.setFixedHeight(30) self.downbtn.setFixedWidth(30) self.downbtn.animateClick() self.downbtn.minimumSize() self.txt20 = QTextEdit() self.txt20.setReadOnly(True) self.txt.textChanged.connect(self.text_count) self.enterbtn.clicked.connect(self.enter_works) self.downbtn.clicked.connect(self.show20) self.show() def text_count(self): wordcount = len(self.txt.toPlainText()) if wordcount <= 200: self.lbl.setText("Chars: " + str(wordcount)) else: self.txt.setPlainText(self.txt.toPlainText()[0:200]) self.txt.moveCursor(QTextCursor.End) QMessageBox.information(self, 'Warning', 'Warning: no more than 200 characters', QMessageBox.Ok) def enter_works(self): reflections = self.txt.toPlainText() datestamp = str(datetime.datetime.now()) if len(reflections) > 0: conn = sqlite3.connect("myreflections.db") c = conn.cursor() c.execute( "INSERT into reflections (datestamp, reflection) VALUES (?,?)", (datestamp, reflections)) conn.commit() c.close() conn.close() self.txt.setPlainText("") self.show20() def show20(self): if self.downbtn.text() == 'v': self.downbtn.setText('^') self.setFixedSize(420, 500) conn = sqlite3.connect("myreflections.db") c = conn.cursor() c.execute("SELECT datestamp, reflection FROM reflections") data = c.fetchall() self.layout.addWidget(self.txt20) for row in data: self.txt20.setText(self.txt20.toPlainText() + str(row) + '\n') elif self.downbtn.text() == '^': self.txt20.setParent(None) #self.resize(500,300) self.setFixedSize(420, 300) self.downbtn.setText('v')
class SelectRectangleWindow(QDialog): """Simple view window for pageimages""" def __init__(self, parent, fnames): QWidget.__init__(self) self.parent = parent if type(fnames) == list: self.initUI(fnames) else: self.initUI([fnames]) self.rectangle = None self.whichFile = 0 self.tool = "zoom" def initUI(self, fnames): self.setWindowTitle("Select ID Rectangle") self.vTW = QTabWidget() self.views = {} v = 0 for fn in fnames: self.views[v] = IDView(self, [fn]) self.views[v].setRenderHint(QPainter.HighQualityAntialiasing) self.vTW.addTab(self.views[v], "{}".format(v + 1)) v += 1 # reset view button passes to the UnknownView. self.resetB = QPushButton("reset view") self.zoomB = QPushButton("zoom tool") self.rectB = QPushButton("rectangle") self.delRectB = QPushButton("delete rectangle") self.acceptB = QPushButton("&accept") self.cancelB = QPushButton("&cancel") self.maxNormB = QPushButton("&max/norm") self.cancelB.clicked.connect(self.reject) self.acceptB.clicked.connect(self.check_and_accept_rect) # self.resetB.clicked.connect(lambda: self.view.resetView()) self.maxNormB.clicked.connect(self.swapMaxNorm) self.zoomB.clicked.connect(self.zoomTool) self.rectB.clicked.connect(self.rectTool) self.delRectB.clicked.connect(self.deleteRect) self.resetB.setAutoDefault( False) # return wont click the button by default. # Layout simply grid = QGridLayout() grid.addWidget(self.vTW, 1, 1, 10, 6) grid.addWidget(self.zoomB, 6, 20) grid.addWidget(self.rectB, 5, 20) grid.addWidget(self.delRectB, 7, 20) grid.addWidget(self.resetB, 20, 1) grid.addWidget(self.cancelB, 20, 20) grid.addWidget(self.acceptB, 19, 20) grid.addWidget(self.maxNormB, 1, 20) self.setLayout(grid) self.show() self.rectB.animateClick() def check_and_accept_rect(self): """Checks and accepts only if there is a valid rectangle.""" if self.rectangle is None: # if the user has selected a valid rectangle then we accept it, otherwise do we throw this warning. ErrorMessage("Error: no rectangle selected.").exec_() pass else: self.accept() def swapMaxNorm(self): """Toggles the window size between max and normal""" if self.windowState() != Qt.WindowMaximized: self.setWindowState(Qt.WindowMaximized) else: self.setWindowState(Qt.WindowNoState) def zoomTool(self): self.zoomB.setStyleSheet( "border: 2px solid #00aaaa; " "background: qlineargradient(x1:0,y1:0,x2:0,y2:1, " "stop: 0 #00dddd, stop: 1 #00aaaa);") self.rectB.setStyleSheet("") self.tool = "zoom" def rectTool(self): self.rectB.setStyleSheet( "border: 2px solid #00aaaa; " "background: qlineargradient(x1:0,y1:0,x2:0,y2:1, " "stop: 0 #00dddd, stop: 1 #00aaaa);") self.zoomB.setStyleSheet("") self.tool = "rect" def deleteRect(self): cv = self.vTW.currentIndex() self.views[cv].deleteRect()
class FluidPropertyWidget(QWidget): UNITS_WIDTH = 55 def __init__(self, parent): super(FluidPropertyWidget, self).__init__(parent) self.parent = parent self.modified = False self.layoutMain = QVBoxLayout(self) self.layoutMain.setContentsMargins(15, 7, 15, 7) self.layoutForm = QFormLayout() self.layoutForm.setLabelAlignment(Qt.AlignLeft) self.layoutForm.setFormAlignment(Qt.AlignLeft) self.layoutForm.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow) self.layoutForm.setVerticalSpacing(5) self.lblInputs = {} self.ctlInputs = {} self.lblUnit = {} self.lblProp = {} self.ctlProp = {} for i, p in enumerate(self.inputs()): name = p['name'] unit = p['unit'] hint = p['hint'] self.lblInputs[name] = QLabel(name, self) self.lblInputs[name].setToolTip(hint) self.ctlInputs[name] = QLineEdit(self) self.ctlInputs[name].setToolTip(hint) self.ctlInputs[name].textChanged.connect(self.onModified) self.lblUnit[name] = QLabel(unit, self) self.lblUnit[name].setFixedWidth(self.UNITS_WIDTH) hbox = QHBoxLayout() hbox.addWidget(self.ctlInputs[name]) hbox.addWidget(self.lblUnit[name]) self.layoutForm.addRow(self.lblInputs[name], hbox) self.btnCalculate = QPushButton() self.btnCalculate.clicked.connect(self.computeProperties) icon_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'icons', 'calculator.svg')) icon = QIcon(icon_path) self.btnCalculate.setIcon(icon) self.btnCalculate.setToolTip( "Calculate fluid properties for given inputs") self.btnCalculate.setAutoDefault(True) self.btnCalculate.setMaximumWidth(62) self.layoutForm.addRow("", self.btnCalculate) self.CalculateShortcut = QtWidgets.QShortcut( QtGui.QKeySequence("Ctrl+Return"), self) self.CalculateShortcut.activated.connect(self.onCtrlReturn) lbl = QFrame() lbl.setMinimumHeight(2) self.layoutForm.addRow("", lbl) for p in self.outputs(): name = p['name'] unit = p['unit'] hint = p['hint'] self.lblProp[name] = QLabel(name, self) self.lblProp[name].setToolTip(hint) self.lblProp[name].setEnabled(False) self.ctlProp[name] = QLineEdit(self) self.ctlProp[name].setReadOnly(True) self.ctlProp[name].setToolTip(hint) self.lblUnit[name] = QLabel(unit, self) self.lblUnit[name].setFixedWidth(self.UNITS_WIDTH) self.lblUnit[name].setEnabled(False) hbox = QHBoxLayout() hbox.addWidget(self.ctlProp[name]) hbox.addWidget(self.lblUnit[name]) self.layoutForm.addRow(self.lblProp[name], hbox) self.layoutMain.addLayout(self.layoutForm) self.layoutMain.addStretch() self.lblError = QLabel("") self.lblError.setWordWrap(True) self.lblError.setStyleSheet("QLabel { color: red; }") self.lblError.setVisible(False) self.layoutMain.addWidget(self.lblError) self.updateWidgets() # process used to execute the binary that will compute the fluid properties self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.started.connect(self._onStarted) self.process.readyReadStandardOutput.connect(self._onReadStdOut) self.process.readyReadStandardError.connect(self._onReadStdErr) self.process.finished.connect(self._onJobFinished) self.process.error.connect(self._onError) # create a temporary file which is used to generate the input file self.fd, self.input_file_name = mkstemp() def updateWidgets(self): enable = True for input in self.inputs(): if len(self.ctlInputs[input['name']].text()) == 0: enable = False break self.btnCalculate.setEnabled(enable) self.CalculateShortcut.setEnabled(enable) title = "Fluid Property Interrogator" if self.modified: title += " *" self.parent.setWindowTitle(title) def onModified(self): self.setModified(True) self.updateWidgets() def setExecutablePath(self, exe_path): self.exe_path = exe_path def onCtrlReturn(self): self.btnCalculate.animateClick() def computeProperties(self): """ Called when the computation of properties is requested """ self.buildInputFile(self.input_file_name) args = ['-i', self.input_file_name, '--no-color'] self.process.start(self.exe_path, args) self.process.waitForStarted() self.setModified(False) self.updateWidgets() def setModified(self, modified): self.modified = modified def buildInputFile(self, file_name): """ Write the input file into a file Inputs: file_name[str]: File name which we write into """ with open(file_name, "w+") as f: f.write("[FluidPropertiesInterrogator]\n") f.write(" fp = fp\n") f.write(" json = true\n") for p in self.inputs(): name = p['name'] f.write(" {} = {}\n".format(name, self.ctlInputs[name].text())) f.write("[]\n") f.write("[Modules]\n") f.write(" [./FluidProperties]\n") f.write(" {}\n".format( self.parent.fluidPropertyInputFileBlock())) f.write(" [../]\n") f.write("[]\n") @pyqtSlot() def _onStarted(self): self.json_str = "" self.json_data_on = False self.error_str = "" self.error_data_on = False @pyqtSlot() def _onReadStdOut(self): # store only the JSON data self.process.setReadChannel(QProcess.StandardOutput) while self.process.canReadLine(): line = self.process.readLine().data().decode("utf-8").rstrip() if line == '**START JSON DATA**': self.json_data_on = True elif line == '**END JSON DATA**': self.json_data_on = False elif self.json_data_on: self.json_str += line @pyqtSlot() def _onReadStdErr(self): self.process.setReadChannel(QProcess.StandardError) while self.process.canReadLine(): line = self.process.readLine().data().decode("utf-8").rstrip() if line == '*** ERROR ***': self.error_data_on = True elif line[:13] == 'Stack frames:': self.error_data_on = False elif self.error_data_on: self.error_str += line @pyqtSlot(int, QProcess.ExitStatus) def _onJobFinished(self, code, status): if code == 0: try: j = json.loads(self.json_str) # enter the data into the controls for p in self.outputs(): name = p['name'] val = float(j[self.jsonSectionName()][name]) if abs(val) < 0.1: s = "{:.5e}".format(val) else: s = "{:.5f}".format(val) self.ctlProp[name].setText(s) except: # this would happen if people used MOOSE that does not support # printing fluid properties in JSON format pass self.lblError.setVisible(False) else: self.lblError.setText(self.error_str) self.lblError.setVisible(True) @pyqtSlot(QProcess.ProcessError) def _onError(self, err): print("error:", err)
def btn_clicked(btn: QtWidgets.QPushButton) -> None: if btn.isVisible() and btn.isEnabled(): btn.animateClick()