class AirShareWidget(QWidget): def __init__(self, url, color): QWidget.__init__(self) self.setStyleSheet("background-color: black") self.file_name_font = QFont() self.file_name_font.setPointSize(24) self.file_name_label = QLabel(self) self.file_name_label.setText(url) self.file_name_label.setFont(self.file_name_font) self.file_name_label.setAlignment(Qt.AlignCenter) self.file_name_label.setStyleSheet("color: #eee") self.qrcode_label = QLabel(self) self.notify_font = QFont() self.notify_font.setPointSize(12) self.notify_label = QLabel(self) self.notify_label.setText("Scan above QR to copy information") self.notify_label.setFont(self.notify_font) self.notify_label.setAlignment(Qt.AlignCenter) self.notify_label.setStyleSheet("color: #eee") layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addStretch() layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter) layout.addSpacing(20) layout.addWidget(self.file_name_label, 0, Qt.AlignCenter) layout.addSpacing(40) layout.addWidget(self.notify_label, 0, Qt.AlignCenter) layout.addStretch() self.qrcode_label.setPixmap(qrcode.make(url, image_factory=Image).pixmap())
def __init__(self, parent = None): super().__init__(parent) self._note_created_at = datetime.utcnow() self._note_modified_at = datetime.utcnow() self._note_id = None self._main_layout = QVBoxLayout(self) # Use Liberation Mono font if present. If not, TypeWriter hint # will make Qt select some other monospace font. monospace_font = QFont("Liberation Mono", 10, QFont.TypeWriter) timestamp_font = QFont() timestamp_font.setPointSize(7) self._tag_editor = QLineEdit(self) self._body_editor = QTextEdit(self) self._body_editor.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.MinimumExpanding) document = self._body_editor.document() document.setDefaultFont(monospace_font) self._main_layout.addWidget(self._body_editor) self._main_layout.addWidget(self._tag_editor) self._body_editor.textChanged.connect(self.touch) self._tag_editor.textChanged.connect(lambda text: self.touch())
def setNameAndBrush(self, sigma, color=Qt.black): self.sigma = sigma self.setText(f'σ{self.column}'.translate(self.sub_trans)) if self.sigma is not None: total_window = (1 + 2 * int(self.sigma * self.window_size + 0.5)) self.setToolTip(f'sigma = {sigma:.1f} pixels, window diameter = {total_window:.1f}') font = QFont() font.setPointSize(10) # font.setBold(True) self.setFont(font) self.setForeground(color) pixmap = QPixmap(self.pixmapSize) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.setPen(color) brush = QBrush(color) painter.setBrush(brush) painter.drawEllipse(QRect(old_div(self.pixmapSize.width(), 2) - old_div(self.brushSize, 2), old_div(self.pixmapSize.height(), 2) - old_div(self.brushSize, 2), self.brushSize, self.brushSize)) painter.end() self.setIcon(QIcon(pixmap)) self.setTextAlignment(Qt.AlignVCenter)
def draw_path(self): plan = self.plan rect = plan.mapRectToScene(plan.viewport().rect()) rect.setWidth(10**floor(log10(rect.width()/2))) text = "{} m".format(round(rect.width())) tran = self.deviceTransform(plan.viewportTransform()).inverted()[0] width = tran.mapRect(QRectF( plan.mapFromScene(rect.topLeft()), plan.mapFromScene(rect.bottomRight()))).width() view = tran.mapRect(plan.viewport().rect()) x0 = QPointF(view.right() - view.width()/15, view.bottom() - view.height()/15) x1 = x0 - QPointF(width, 0) head = QPointF(0, 8) path = QPainterPath() path.moveTo(x0) path.lineTo(x1) path.moveTo(x0 + head) path.lineTo(x0 - head) path.moveTo(x1 + head) path.lineTo(x1 - head) # add label font = QFont(plan.font()) font.setPointSize(14) rect = QFontMetrics(font).boundingRect(text) size = tran.mapRect(QRectF(rect)).size() w, h = size.width(), size.height() offs = [-w/2, -h/2] path.addText((x0+x1)/2 + QPointF(*offs), font, text) return path
def createLabel(self, text): lbl = QLabel(text) lbl.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) font = QFont() font.setPointSize(12) lbl.setFont(font) return lbl
def __init__(self, parent=None, text=None, EditorHighlighterClass=PythonHighlighter, indenter=PythonCodeIndenter): QPlainTextEdit.__init__(self, parent) self.setFrameStyle(QFrame.NoFrame) self.setTabStopWidth(4) self.setLineWrapMode(QPlainTextEdit.NoWrap) font = QFont() font.setFamily("lucidasanstypewriter") font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.highlighter = EditorHighlighterClass(self) if text: self.setPlainText(text) self.frame_style = self.frameStyle() self.draw_line = True self.print_width = self.fontMetrics().width("x" * 78) self.line_pen = QPen(QColor("lightgrey")) self.last_row = self.last_col = -1 self.last_block = None self.highlight_line = True self.highlight_color = self.palette().highlight().color().light(175) self.highlight_brush = QBrush(QColor(self.highlight_color)) self.cursorPositionChanged.connect(self.onCursorPositionChanged) self.indenter = indenter(RopeEditorWrapper(self)) # True if you want to catch Emacs keys in actions self.disable_shortcuts = False self.prj = get_no_project() self.prj.root = None self.calltip = CallTip(self) self.autocomplete = AutoComplete(self)
def draw_frequency_marker(self, x_pos, frequency): if frequency is None: self.clear_frequency_marker() return y1 = self.sceneRect().y() y2 = self.sceneRect().y() + self.sceneRect().height() if self.frequency_marker is None: pen = QPen(constants.LINECOLOR, 0) self.frequency_marker = [None, None] self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen) self.frequency_marker[1] = self.addSimpleText("") self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR)) font = QFont() font.setBold(True) font.setPointSize(int(font.pointSize() * 1.25)+1) self.frequency_marker[1].setFont(font) self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2) scale_x, scale_y = self.__calc_x_y_scale(self.sceneRect()) self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False) self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3)) font_metric = QFontMetrics(self.frequency_marker[1].font()) text_width = font_metric.width("Tune to") * scale_x text_width += (font_metric.width(" ") * scale_x) / 2 self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
def __init__(self, engine, parent = None): super().__init__(parent) self._engine = engine self._styles = None self._path = "" self._icons = {} self._images = {} # Workaround for incorrect default font on Windows if sys.platform == "win32": default_font = QFont() default_font.setPointSize(9) QCoreApplication.instance().setFont(default_font) self._em_height = int(QFontMetrics(QCoreApplication.instance().font()).ascent()) self._em_width = self._em_height; self._initializeDefaults() Preferences.getInstance().addPreference("general/theme", Application.getInstance().getApplicationName()) try: theme_path = Resources.getPath(Resources.Themes, Preferences.getInstance().getValue("general/theme")) self.load(theme_path) except FileNotFoundError: Logger.log("e", "Could not find theme file.")
def __init__(self): """The constructor initializes the class AboutDialog.""" super().__init__() self.setAttribute(Qt.WA_DeleteOnClose) # initialize class constants self._BUTTON_MIN_WIDTH = 110 self._OXYGEN_PATH_48 = os.path.join("resources", "icons", "oxygen", "48") # fonts and margins settings hlFont = QFont() hlFont.setBold(True) hlFont.setPointSize(14) # scientific logo logo = QLabel(pixmap=QPixmap(os.path.join(self._OXYGEN_PATH_48, "applications-science.png"))) logoLayout = QVBoxLayout() logoLayout.addWidget(logo) logoLayout.addStretch() # begin the content # headline and description text self.headline = QLabel() self.headline.setFont(hlFont) self.description = QLabel(wordWrap=True) # the list with the open button self.listWidget = QListWidget() self.listWidget.setMinimumWidth(420) self.createArticles() self.openButton = QPushButton() self.openButton.clicked.connect(self.openAction) listLayout = QHBoxLayout() listLayout.addWidget(self.listWidget) listLayout.addWidget(self.openButton, alignment=Qt.AlignTop) # create a close button line = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.HLine) self.closeButton = QPushButton() self.closeButton.setFixedWidth(self._BUTTON_MIN_WIDTH) self.closeButton.clicked.connect(self.close) # content layout contentLayout = QVBoxLayout() contentLayout.addWidget(self.headline) contentLayout.addWidget(self.description) contentLayout.addLayout(listLayout) contentLayout.addWidget(line) contentLayout.addWidget(self.closeButton, alignment=Qt.AlignRight) # main layout layout = QHBoxLayout(self) layout.addLayout(logoLayout) layout.addLayout(contentLayout) # translate the graphical user interface self.retranslateUi()
def __init__(self, parent=None): super(CodeEditor, self).__init__(parent) self.numArea = LineNumArea(self) # Binding signals to slots self.blockCountChanged.connect(self.updateNumWidth) self.updateRequest.connect(self.updateNum) self.cursorPositionChanged.connect(self.highlightLine) self.textChanged.connect(self.highlightCode) # editor config font = QFont() font.setFamily("Courier") font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) font.setPointSize(12) self.setFont(font) metrics = QFontMetrics(font) self.setTabStopWidth(4 * metrics.width('a')) # tab width # highlighter self.highlighter = Highlighter(self.document()) # init self.updateNumWidth(0) self.highlightLine()
def __init__(self, engine, parent = None) -> None: super().__init__(parent) self._engine = engine self._styles = None # type: Optional[QObject] self._path = "" self._icons = {} # type: Dict[str, QUrl] self._images = {} # type: Dict[str, QUrl] # Workaround for incorrect default font on Windows if sys.platform == "win32": default_font = QFont() default_font.setPointSize(9) QCoreApplication.instance().setFont(default_font) self._em_height = int(QFontMetrics(QCoreApplication.instance().font()).ascent()) self._em_width = self._em_height # Cache the initial language in the preferences. For fonts, a special font can be defined with, for example, # "medium" and "medium_nl_NL". If the special one exists, getFont() will return that, otherwise the default # will be returned. We cache the initial language here is because Cura can only change its language if it gets # restarted, so we need to keep the fonts consistent in a single Cura run. self._preferences = UM.Application.Application.getInstance().getPreferences() self._lang_code = self._preferences.getValue("general/language") self._initializeDefaults() self.reload()
def paintEvent(self, event): # Check whether this orb is enhanced if type(self.parent) == Board: enh = self.parent.enhanced[self.position] else: enh = False painter = QPainter(self) painter.drawPixmap(event.rect().adjusted(2,2,-2,-2), self.pixmap()) w = event.rect().width() if enh: path = QPainterPath() pen = QPen() pen.setWidth(1); pen.setBrush(Qt.white) brush = QBrush(Qt.yellow) font = QFont() font.setPointSize(20) font.setWeight(QFont.Black) path.addText(event.rect().x()+w-15,event.rect().y()+w-5,font,'+') painter.setPen(pen) painter.setBrush(brush) painter.setFont(font) painter.drawPath(path)
def __init__(self, bookmark, parent=None): """ Constructor @param bookmark reference to the bookmark to be shown (Bookmark) @param parent reference to the parent widget (QWidget) """ super(BookmarkInfoDialog, self).__init__(parent) self.setupUi(self) self.__bookmark = bookmark self.icon.setPixmap(UI.PixmapCache.getPixmap("bookmark32.png")) font = QFont() font.setPointSize(font.pointSize() + 2) self.title.setFont(font) if bookmark is None: self.titleEdit.setEnabled(False) else: self.titleEdit.setText(bookmark.title) self.titleEdit.setFocus() msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
class FileUploaderWidget(QWidget): def __init__(self, url, color): QWidget.__init__(self) url = os.path.expanduser(url) self.setStyleSheet("background-color: black") self.file_name_font = QFont() self.file_name_font.setPointSize(24) self.file_name_label = QLabel(self) self.file_name_label.setText("Your file will uploading to\n{0}".format(url)) self.file_name_label.setFont(self.file_name_font) self.file_name_label.setAlignment(Qt.AlignCenter) self.file_name_label.setStyleSheet("color: #eee") self.qrcode_label = QLabel(self) self.notify_font = QFont() self.notify_font.setPointSize(12) self.notify_label = QLabel(self) self.notify_label.setText("Scan above QR to uploading file.\nMake sure that your smartphone is connected to the same WiFi network as this computer.") self.notify_label.setFont(self.notify_font) self.notify_label.setAlignment(Qt.AlignCenter) self.notify_label.setStyleSheet("color: #eee") layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addStretch() layout.addWidget(self.qrcode_label, 0, Qt.AlignCenter) layout.addSpacing(20) layout.addWidget(self.file_name_label, 0, Qt.AlignCenter) layout.addSpacing(40) layout.addWidget(self.notify_label, 0, Qt.AlignCenter) layout.addStretch() self.port = "8000" self.local_ip = self.get_local_ip() self.address = "http://{0}:{1}".format(self.local_ip, self.port) self.qrcode_label.setPixmap(qrcode.make(self.address, image_factory=Image).pixmap()) global upload_dir upload_dir = url t = threading.Thread(target=self.run_http_server, name='LoopThread') t.start() def run_http_server(self): http.server.test(SimpleHTTPRequestHandler, http.server.HTTPServer) def get_local_ip(self): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) return s.getsockname()[0] except OSError: print("Network is unreachable") sys.exit()
def set_font_style(self, family, size, form): font = QFont() font.setFamily(family) font.setPointSize(size) boldFlag, italicFlag = self.interprete_font_form(form) font.setBold(boldFlag) font.setItalic(italicFlag) self.setFont(font)
def createTitle(self): title = QLabel(self.bot1.name + ' vs ' + self.bot2.name) font = QFont() font.setBold(True) font.setPointSize(12) title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) title.setFont(font) return title
def fontForID(self, fontId): result = QFont(QApplication.font()) if fontId == FontID.Title: result.setPointSize(self.TITLE_FONT_SIZE) result.setBold(True) else: result.setPointSize(self.LEGEND_FONT_SIZE) return result
def createTitleLabel(self, title): titleLabel = QLabel(title) font = QFont() font.setBold(True) font.setPointSize(18) titleLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) titleLabel.setFont(font) return titleLabel
def __init__(self, parent): super(QKOSAbout, self).__init__(parent) gridlayout = QGridLayout(self) titlefont = QFont() titlefont.setPointSize(24) policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) label = QLabel("About QKeysOnScreen", self) label.setFont(titlefont) label.setSizePolicy(policy) gridlayout.addWidget(label, 0, 0) labelcopyright = QLabel("\u00a9 2015 Fredrick Brennan <*****@*****.**>") labelcopyright.setSizePolicy(policy) gridlayout.addWidget(labelcopyright, 1, 0) labeldesc = ( "<p>QKeysOnScreen is a simple application intended for " + "presentations, video tutorials, and any other case where" + " you'd want to display the current state of the keyboard" + ' on the screen. For more information see our <a href="' + 'https://github.com/ctrlcctrlv/QKeysOnScreen">Github</a>' + " project." ) qlabeldesc = QLabel(labeldesc) qlabeldesc.setWordWrap(True) gridlayout.addWidget(qlabeldesc, 2, 0) from PyQt5.QtCore import QT_VERSION_STR from PyQt5.Qt import PYQT_VERSION_STR import platform pyversion = ".".join([str(o) for o in sys.version_info]) uname_result = platform.uname() uname = "{} {}".format(uname_result.system, uname_result.release) labelversions = ( "<strong>Versions:</strong><br>Qt: {0}<br>PyQt: {1}" + "<br>Python: {2}<br>OS: {3}<br>QKeysOnScreen: 0.0.1" ).format(QT_VERSION_STR, PYQT_VERSION_STR, platform.python_version(), uname, platform.machine()) qlabelversions = QLabel(labelversions) qlabelversions.setStyleSheet("border: 1px solid green") gridlayout.addWidget(qlabelversions, 0, 1) self.kb = get_keyboard_path() self.mouse = get_mouse_path() self.infoqlabel = QLabel( "<strong>Devices:</strong><br>" + "Our mouse is {0}<br/>Our keyboard is {1}".format(self.mouse, self.kb), self, ) self.infoqlabel.setStyleSheet("border: 1px solid green") gridlayout.addWidget(self.infoqlabel, 2, 1) qte = QTextEdit(self) qte.setReadOnly(True) qfile = QFile(":/LICENSE") qfile.open(QIODevice.ReadOnly) qte.setPlainText(bytes(qfile.readAll()).decode("utf-8")) qfile.close() gridlayout.addWidget(qte, 3, 0, 1, 2) self.setLayout(gridlayout)
def __init__(self, *args, **kwargs): if "windowtype" in kwargs: self.windowname = kwargs["windowtype"] del kwargs["windowtype"] else: self.windowname = "XML Object" super().__init__(*args, **kwargs) self.resize(900, 500) self.setMinimumSize(QSize(300, 300)) self.centralwidget = QWidget(self) self.setWidget(self.centralwidget) self.entity = None font = QFont() font.setFamily("Consolas") font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) font.setPointSize(10) self.dummywidget = QWidget(self) self.dummywidget.setMaximumSize(0,0) self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.addWidget(self.dummywidget) self.goto_id_action = ActionWithOwner("Go To ID", self, action_owner=self) self.addAction(self.goto_id_action) self.goto_shortcut = QKeySequence(Qt.CTRL+Qt.Key_G) self.goto_id_action.setShortcut(self.goto_shortcut) #self.goto_id_action.setShortcutContext(Qt.WidgetShortcut) self.goto_id_action.setAutoRepeat(False) self.goto_id_action.triggered_owner.connect(self.open_new_window) self.textbox_xml = XMLTextEdit(self.centralwidget) self.button_xml_savetext = QPushButton(self.centralwidget) self.button_xml_savetext.setText("Save XML") self.button_xml_savetext.setMaximumWidth(400) self.textbox_xml.setLineWrapMode(QTextEdit.NoWrap) self.textbox_xml.setContextMenuPolicy(Qt.CustomContextMenu) self.textbox_xml.customContextMenuRequested.connect(self.my_context_menu) metrics = QFontMetrics(font) self.textbox_xml.setTabStopWidth(4 * metrics.width(' ')) self.textbox_xml.setFont(font) self.verticalLayout.addWidget(self.textbox_xml) self.verticalLayout.addWidget(self.button_xml_savetext) self.setWindowTitle(self.windowname)
def addLabels(self): font = QFont() font.setPointSize(15) infLbl = QLabel("Infantry", self) infLbl.setFont(font) infLbl.move(0, 0) cavLbl = QLabel("Cavlary", self) cavLbl.setFont(font) cavLbl.move(150, 0)
def lbl3(self): font = QFont() font.setFamily("Quicksand") font.setBold(True) font.setPointSize(15) lbl3 = QLabel('Don\'t show this at start up' ,self) lbl3.setFont(font) lbl3.setStyleSheet("QLabel { color : white; }") lbl3.move(580, 650)
def __init__(self,parent,text): QLabel.__init__(self,parent) self.parent=parent self.text=text self.setText(text) self.setAlignment(Qt.AlignCenter) font=QFont() font.setPointSize(self.parent.height()/2) self.setFont(font)
def lbl2(self): font = QFont() font.setFamily("Quicksand") font.setBold(True) font.setPointSize(19) lbl2 = QLabel('Welcome to Revolution OS, under this text you find usefull Links to get started.',self) lbl2.setFont(font) lbl2.setStyleSheet("QLabel { color : white; }") lbl2.move(15, 200)
def setupEditor(self): font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.editor = QTextEdit() self.editor.setFont(font) self.highlighter = Highlighter(self.editor.document())
def __init__(self): super(PayrecWidget, self).__init__() self.ui = Ui_PayrecWidget() self.ui.setupUi(self) font = QFont() font.setFamily("Comic Sans MS") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.ui.rec_label.setFont(font) self.ui.gsf_label.setFont(font)
def set_up_window(self): self.resize(200, 150) center_x = self.parent.x() + (self.parent.frameGeometry().width() - self.frameGeometry().width()) / 2 center_y = self.parent.y() + (self.parent.frameGeometry().height() - self.frameGeometry().height()) / 2 self.move(center_x, center_y) font = QFont() font.setPointSize(10) self.setFont(font)
def __init__(self, status, parent=None): QDialog.__init__(self) self.setWindowTitle("Status Message") self.resize(200, 50) self.move(200, 50) self.status = QLabel(self) self.status.setGeometry(QRect(10, 10, 180, 30)) font = QFont() font.setPointSize(16) self.status.setFont(font) self.status.setText(status) self.status.setAlignment(Qt.AlignCenter)
def test_storingFonts(self): font = QFont() font.setFamily('my family') font.setPointSize(20) writeToSettings('testFont', font, None, self.settings) family = readFromSettings('testFont', str, self.settings) size = readFromSettings('testFontSize', int, self.settings) self.assertEqual(family, 'my family') self.assertEqual(size, 20) newFont = readFromSettings('testFont', QFont, self.settings, QFont()) self.assertEqual(newFont.family(), family) self.assertEqual(newFont.pointSize(), size)
def show_info(self): # Create window displaying the manual. info_file = open(resource_path("documents/manual.html")) # Get the contents (text). info = info_file.read() self.info_window = ManualWindow(info) font1 = QFont() font1.setPointSize(11) self.info_window.setFont(font1) self.info_window.setWindowIcon(QIcon(resource_path( "images/logicheck_icon_3.png"))) self.info_window.show()
class select_param(QWidget): def set_save_function(self, save_function): self.save_function = save_function def __init__(self, treeview): QWidget.__init__(self) self.dest_treeview = treeview self.setFixedSize(500, 700) self.file_name_tab_pos = 0 self.token_tab_pos = 1 self.path_tab_pos = 2 self.main_vbox = QVBoxLayout() self.save_function = None self.setWindowIcon(icon_get("scan")) self.setWindowTitle( _("Select simulation parameter") + " (https://www.gpvdm.com)") self.tab = QTreeWidget() self.scan_human_labels = get_scan_human_labels() #self.tab.setHeaderItem("Scan items") self.font = QFont() # self.font.setFamily('DejaVu Sans') # self.font.setBold(True) # self.font.setStyleHint(QFont.Monospace) # self.font.setFixedPitch(True) self.font.setPointSize(int(20)) self.tab.setFont(self.font) self.main_vbox.addWidget(self.tab) self.hwidget = QWidget() okButton = QPushButton(_("OK")) cancelButton = QPushButton(_("Cancel")) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(okButton) hbox.addWidget(cancelButton) self.hwidget.setLayout(hbox) self.main_vbox.addWidget(self.hwidget) self.setLayout(self.main_vbox) okButton.clicked.connect(self.tree_apply_click) cancelButton.clicked.connect(self.close) #self.tab.itemSelectionChanged.connect(self.tree_apply_click) self.tab.header().close() self.update() def make_entry(self, root, text): depth = 0 pointer = root for depth in range(0, len(text)): found = False for i in range(0, pointer.childCount()): if pointer.child(i).text(0) == text[depth]: found = True pointer = pointer.child(i) break if found == False: pointer = QTreeWidgetItem(pointer, [text[depth]]) def update(self): self.tab.clear() self.scan_human_labels.populate_from_files() root = QTreeWidgetItem(self.tab, [_("Simulation parameters")]) root.setExpanded(True) param_list = self.scan_human_labels.list i = 0 for item in range(0, len(param_list)): div_str = param_list[item].human_label.replace("\\", "/") div_str = div_str.split("/") piter = None self.make_entry(root, div_str) def on_destroy(self): self.hide() return True def cal_path(self): getSelected = self.tab.selectedItems() if getSelected: item = getSelected[0] # getChildNode = baseNode.text(0) path = [] while item is not None: path.append(str(item.text(0))) item = item.parent() ret = "/".join(reversed(path)) ret = ret.split('/', 1)[-1] ret = ret.replace("/", os.path.sep) return ret def tree_apply_click(self): index = self.dest_treeview.selectionModel().selectedRows() if len(index) > 0: #print("row=",index[0].row(),len(index)) pos = index[0].row() path = self.cal_path() file_name = self.scan_human_labels.get_file_from_human_label(path) token = self.scan_human_labels.get_token_from_human_label(path) self.dest_treeview.set_value(pos, self.file_name_tab_pos, file_name) self.dest_treeview.set_value(pos, self.token_tab_pos, token) self.dest_treeview.set_value(pos, self.path_tab_pos, path) if self.save_function != None: self.save_function() self.close() else: error_dlg( self, _("No row selected in the scan window, can't insert the selection" ))
def initUI(self): font = QFont() font.setBold(True) font.setPointSize(10) self.setFont(font)
class Editor(QPlainTextEdit): def __init__(self, parent): super().__init__(parent) self.parent = parent self.font = QFont() self.size = 12 self.dialog = MessageBox() self.menu_font = QFont() self.menu_font.setFamily("Iosevka") self.menu_font.setPointSize(10) self.font.setFamily(editor["editorFont"]) self.font.setPointSize(editor["editorFontSize"]) self.focused = None self.replace_tabs = 4 self.setWordWrapMode(4) self.setFont(self.font) self.l = 0 self.highlightingRules = [] self.indexes = None self.setTabStopWidth(editor["TabWidth"]) self.createStandardContextMenu() self.setWordWrapMode(QTextOption.NoWrap) def newFile(self): """This and most of the functions below will just be wrappers for the functions defined in Main""" self.new_action = QAction("New") self.new_action.triggered.connect(self.parent.parent.newFile) def openFile(self): self.open_action = QAction("Open") self.open_action.triggered.connect(self.parent.parent.openFileFromMenu) def runFile(self): self.run_action = QAction("Run") self.run_action.triggered.connect(self.parent.parent.Terminal) def contextMenuEvent(self, event): menu = QMenu() """Initializing actions""" self.newFile() self.openFile() self.runFile() menu.addAction(self.new_action) menu.addAction(self.open_action) menu.addAction(self.run_action) menu.setFont(self.menu_font) menu.exec(event.globalPos()) del menu def moveCursorPosBack(self): textCursor = self.textCursor() textCursorPos = textCursor.position() textCursor.setPosition(textCursorPos - 1) self.setTextCursor(textCursor) def keyPressEvent(self, e): textCursor = self.textCursor() key = e.key() if key == Qt.Key_H: # self.parent.completer.wordList # TODO: implement dynamic completion pass textCursorPos = textCursor.position() isSearch = (e.modifiers() == Qt.ControlModifier and e.key() == Qt.Key_F) if isSearch: try: currentWidget = self.parent currentFile = currentWidget.fileName currentEditor = currentWidget.editor textCursor = currentEditor.textCursor() textCursorPos = textCursor.position() except (AttributeError, UnboundLocalError) as E: print(E) if currentWidget is not None: text, okPressed = QInputDialog.getText(self, 'Find', 'Find what: ') if okPressed: if text == "": text = " " self.dialog.noMatch(text) self.searchtext = text try: with open(currentFile, 'r') as file: contents = file.read() self.indexes = list(find_all(contents, text)) if len(self.indexes) == 0: self.dialog.noMatch(text) except FileNotFoundError as E: print(E) if key == Qt.Key_QuoteDbl: self.insertPlainText('"') self.moveCursorPosBack() if (e.modifiers() == Qt.ControlModifier and e.key() == 61): # Press Ctrl+Equal key to make font bigger self.font.setPointSize(self.size + 1) self.font.setFamily(editor["editorFont"]) self.setFont(self.font) self.size += 1 if (e.modifiers() == Qt.ControlModifier and e.key() == 45): # Press Ctrl+Minus key to make font smaller self.font.setPointSize(self.size - 1) self.font.setFamily(editor["editorFont"]) self.setFont(self.font) self.size -= 1 if key == Qt.Key_F3: try: index = self.indexes[0 + self.l] currentWidget = self.parent currentFile = currentWidget.fileName currentEditor = currentWidget.editor textCursor.setPosition(index) textCursor.movePosition(textCursor.Right, textCursor.KeepAnchor, len(self.searchtext)) currentEditor.setTextCursor(textCursor) self.l += 1 except IndexError: self.l = 0 if key == 39: self.insertPlainText("'") self.moveCursorPosBack() if key == Qt.Key_BraceLeft: self.insertPlainText("}") self.moveCursorPosBack() if key == Qt.Key_BracketLeft: self.insertPlainText("]") self.moveCursorPosBack() if key == Qt.Key_ParenLeft: self.insertPlainText(")") self.moveCursorPosBack() if key == Qt.Key_ParenRight: textCursor = self.textCursor() textCursor.select(QTextCursor.WordUnderCursor) if textCursor.selectedText() == "()" or "()" in textCursor.selectedText(): return if key == Qt.Key_BraceRight: textCursor = self.textCursor() textCursor.select(QTextCursor.WordUnderCursor) if textCursor.selectedText == "": return if key not in [16777217, 16777219, 16777220]: super().keyPressEvent(e) return e.accept() cursor = self.textCursor() if key == 16777217: # and self.replace_tabs: amount = 4 - self.textCursor().positionInBlock() % 4 self.insertPlainText(' ' * amount) elif key == 16777219 and cursor.selectionStart() == cursor.selectionEnd() and self.replace_tabs and \ cursor.positionInBlock(): position = cursor.positionInBlock() end = cursor.position() start = end - (position % 4) if start == end and position >= 4: start -= 4 string = self.toPlainText()[start:end] if not len(string.strip()): # if length is 0 which is binary for false for i in range(end - start): cursor.deletePreviousChar() else: super().keyPressEvent(e) elif key == 16777220: end = cursor.position() start = end - cursor.positionInBlock() line = self.toPlainText()[start:end] indentation = len(line) - len(line.lstrip()) chars = '\t' if self.replace_tabs: chars = ' ' indentation /= self.replace_tabs if line.endswith(':'): if self.replace_tabs: indentation += 1 super().keyPressEvent(e) self.insertPlainText(chars * int(indentation)) else: super().keyPressEvent(e)
self.game_window.show() def double_player(self): self.close() self.game_window = DoublePlayer() self.game_window.exitSignal.connect(self.game_over) # 游戏结束 self.game_window.backSignal.connect(self.show) # 游戏 self.game_window.show() def network_player(self): self.close() self.game_window = NetworkConfig(main_window=self) self.game_window.show() def game_over(self): sys.exit(app.exec_()) app = None # 游戏运行的主逻辑 if __name__ == '__main__': app = QApplication(sys.argv) w = MainWindow() font = QFont() font.setFamily("微软雅黑") font.setPointSize(12) # palette = QPalette() # palette.setColor(QPalette.Text,QColor()) w.setFont(font) w.show() # w.setPalette(palette) sys.exit(app.exec_())
class Main(QMainWindow): def __init__(self): super().__init__() self.DontUseNativeDialogs = None self.onStart() self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.setGeometry(0, 0, 800, 600) #self.editor = QPlainTextEdit() self.numbers = NumberBar(self.editor) self.move(0, 0) self.filename = '' self.setWindowIcon(QtGui.QIcon('resources/notes.png')) self.exit() self.new() self.run_m() self.is_opened = False self.saved = False self.open() self.undo() self.cut() self.copy() self.paste() self.all() self.printPreview() self.redo() self.find() self.printButton() self.saveButton() self.saveAs() self.initUI() self.setWindowTitle('PyPad') self.files = None def onStart(self): with open("config.json", "r") as jsonFile: read = jsonFile.read() self.data = json.loads(read) if self.data["editor"][0]["windowStaysOnTop"] is True: self.setWindowFlags(Qt.WindowStaysOnTopHint) else: pass if self.data["editor"][0]["DontUseNativeDialog"] is True: self.DontUseNativeDialogs = True else: self.DontUseNativeDialogs = False self.font = QFont() self.font.setFamily(self.data["editor"][0]["editorFont"]) self.font.setPointSize(self.data["editor"][0]["editorFontSize"]) jsonFile.close() self.editor = QPlainTextEdit() self.editor.setTabStopWidth(self.data["editor"][0]["TabWidth"]) self.editor.setPlainText('''Welcome to Notepad !!''') def exit(self): self.exitAct = QAction('Quit', self) self.exitAct.setShortcut('Ctrl+Q') self.exitAct.setStatusTip('Exit application') self.exitAct.triggered.connect(qApp.quit) @staticmethod def execute(self): out, err = Popen(['python main.py'], shell=True, stdout=PIPE, stderr=PIPE).communicate() return (out + err).decode() def new(self): self.newAct = QAction('New', self) self.newAct.setShortcut('Ctrl+N') self.newAct.setStatusTip('Create a file') self.newAct.triggered.connect(self.execute) def open(self): self.openAct = QAction('Open...', self) self.openAct.setShortcut('Ctrl+O') self.openAct.setStatusTip('Open a file') self.is_opened = False self.openAct.triggered.connect(self.open1) def open1(self): try: self.is_opened = True options = QFileDialog.Options() if self.DontUseNativeDialogs is True: options |= QFileDialog.DontUseNativeDialog else: pass self.files, _ = QFileDialog.getOpenFileNames( self, 'Open a file', '', 'All Files (*);;Python Files (*.py);;Text Files (*.txt)', options=options) self.files = self.files[0] if self.files: with open(self.files, 'r+') as file_o: print(self.files) if self.files.endswith('.py'): self.highlighter = Highlighter(self.editor.document()) self.setWindowTitle("PyPad [" + self.files + "]") else: print( 'Non-Python file opened. Highlighting will not be used.' ) del self.highlighter self.setWindowTitle("PyPad [" + self.files + "]") self.filename = file_o, self.editor.setPlainText( file_o.read()) except IndexError: print("File open dialog closed...") def saveFileAs(self): try: options = QFileDialog.Options() if self.DontUseNativeDialogs is True: options |= QFileDialog.DontUseNativeDialog else: pass name = QFileDialog.getSaveFileName( self, 'Save File', '', 'All Files (*);;Python Files (*.py);;Text Files (*.txt)', options=options) name = name[0] file_s = open(name, 'w+') self.filename = name self.saved = True if name[0].endswith(".py"): self.highlighter = Highlighter(self.editor.document()) text = self.editor.toPlainText() file_s.write(text) file_s.close() self.setWindowTitle(self.filename) with open(self.filename, 'r+') as file: self.files = self.filename self.editor.setPlainText(file.read()) print("test") except FileNotFoundError: print("Save as dialog closed") def saveButton(self): self.saveAct = QAction('Save', self) self.saveAct.setShortcut('Ctrl+S') self.saveAct.setStatusTip('Save a file') self.saveAct.triggered.connect(self.save) def save(self): print(self.files) if self.is_opened: with open(self.files, 'w+') as saving: self.filename = saving self.saved = True saving.write(self.editor.toPlainText()) else: QMessageBox.warning(self, 'No file opened', "No file opened", QMessageBox.Yes | QMessageBox.No) def saveAs(self): self.saveAsAct = QAction('Save as...', self) self.saveAsAct.setShortcut('Shift+Ctrl+S') self.saveAsAct.setStatusTip('Save a file as') self.saveAsAct.triggered.connect(self.saveFileAs) def printButton(self): self.printAct = QAction('Print...', self) self.printAct.setShortcut('Ctrl+P') self.printAct.setStatusTip('Print a file') def _action(): dialog = QtPrintSupport.QPrintDialog() if dialog.exec_() == QDialog.Accepted: self.textArea.document().print_(dialog.printer()) self.printAct.triggered.connect(_action) def printPreview(self): self.printPrAct = QAction('Print preview', self) self.printPrAct.setShortcut('Shift+Ctrl+P') self.printPrAct.setStatusTip('See a print preview') def _action(): dialog = QtPrintSupport.QPrintPreviewDialog() dialog.paintRequested.connect(self.textArea.print_) dialog.exec_() self.printPrAct.triggered.connect(_action) def undo(self): self.undoAct = QAction('Undo', self) self.undoAct.setShortcut('Ctrl+Z') self.undoAct.setStatusTip('Undo') self.undoAct.triggered.connect(lambda: hotkey('ctrl', 'z')) def redo(self): self.redoAct = QAction('Redo', self) self.redoAct.setShortcut('Shift+Ctrl+Z') self.redoAct.setStatusTip('Redo') self.redoAct.triggered.connect(lambda: hotkey('shift', 'ctrl', 'z')) def run(self): if self.files is None or self.files.endswith(".py") is False: print( "Can't run a non python file or a file that doesn't exist...") else: Popen(['python ' + self.files], shell=True, stdout=PIPE, stderr=PIPE).communicate() def run_m(self): self.runAct = QAction('Run', self) self.runAct.setShortcut('Ctrl+R') self.runAct.setStatusTip('Run your program') self.runAct.triggered.connect(self.run) def cut(self): self.cutAct = QAction('Cut', self) self.cutAct.setShortcut('Ctrl+X') self.cutAct.setStatusTip('Cut') self.cutAct.triggered.connect(lambda: hotkey('ctrl', 'x')) def copy(self): self.copyAct = QAction('Copy', self) self.copyAct.setShortcut('Ctrl+C') self.copyAct.setStatusTip('Copy') self.copyAct.triggered.connect(lambda: hotkey('ctrl', 'c')) def paste(self): self.pasteAct = QAction('Paste', self) self.pasteAct.setShortcut('Ctrl+V') self.pasteAct.setStatusTip('Paste') self.pasteAct.triggered.connect(lambda: hotkey('ctrl', 'v')) def all(self): self.allAct = QAction('Select all', self) self.allAct.setShortcut('Ctrl+A') self.allAct.setStatusTip('Select all') self.allAct.triggered.connect(lambda: hotkey('ctrl', 'a')) def findWindow(self): text, ok = QInputDialog.getText(self, 'Find', 'Find what: ') if not ok: return False try: with open(self.files, 'r') as read: index = read.read().find(text) if index != -1: self.cursors.setPosition(index) self.cursors.movePosition(self.cursors.Right, self.cursors.KeepAnchor, len(text)) self.editor.setTextCursor(self.cursors) else: qApp.beep() except: QMessageBox.warning(self, "No file open", "No file open, Ctrl+O to open a file") def find(self): self.findAct = QAction('Find', self) self.findAct.setShortcut('Ctrl+F') self.findAct.setStatusTip('Find') self.findAct.triggered.connect(self.findWindow) def closeEvent(self, e): if self.maybeSave(): e.accept() else: e.ignore() def isModified(self): return self.editor.document().isModified() def maybeSave(self): if not self.isModified(): return True if self.saved is False: ret = QMessageBox.question(self, 'Warning', '<h4><p>The document was modified.</p>\n' \ '<p>Do you want to save changes?</p></h4>', QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if ret == QMessageBox.Yes: if self.filename == '': self.saveFileAs() return False else: self.save() return True if ret == QMessageBox.Cancel: return False return True else: return True def initUI(self): self.statusBar() self.font.setFixedPitch(True) menubar = self.menuBar() # Creating a menu bar fileMenu = menubar.addMenu( 'File' ) # Creating the first menu which will have options listed below fileMenu.addAction(self.newAct) # Adding a newact button fileMenu.addAction(self.openAct) fileMenu.addAction(self.saveAct) fileMenu.addAction(self.saveAsAct) fileMenu.addSeparator() fileMenu.addAction(self.printPrAct) fileMenu.addAction(self.printAct) fileMenu.addSeparator() fileMenu.addAction(self.exitAct) editMenu = menubar.addMenu('Edit') editMenu.addAction(self.undoAct) editMenu.addAction(self.redoAct) editMenu.addSeparator() editMenu.addAction(self.cutAct) editMenu.addAction(self.copyAct) editMenu.addAction(self.pasteAct) editMenu.addSeparator() editMenu.addAction(self.allAct) searchMenu = menubar.addMenu('Search') searchMenu.addAction(self.findAct) runMenu = menubar.addMenu('Run') runMenu.addAction(self.runAct) layoutH = QHBoxLayout() layoutH.addWidget(self.numbers) layoutH.addWidget(self.editor) layoutV = QVBoxLayout() layoutV.addLayout(layoutH) mainWindow = QWidget(self) mainWindow.setLayout(layoutV) self.editor.setFont(self.font) self.setCentralWidget(mainWindow) self.installEventFilter(self) self.editor.setFocus() self.cursor = QTextCursor() self.editor.moveCursor(self.cursor.End) self.cursors = self.editor.textCursor() self.show()
def __init__(self, buttons, preset_buttons=None, *__args): super().__init__(*__args) self.setStyleSheet("padding: 0px;") self.layout = QHBoxLayout(self) image_dir = parent_dir / 'img' self.lbl_count = OSMWDLabel('', enabled=False) font = QFont() font.setPointSize(14) font.setBold(True) self.lbl_count.setFont(font) self.layout.addWidget(self.lbl_count) self.buttons = {} self.layout.addStretch() if preset_buttons: for button_letter in preset_buttons: self.buttons[button_letter] = OSMWDPushButton(button_letter, "preset_" + button_letter, enabled=False) self.buttons[button_letter].setMinimumWidth(20) self.buttons[button_letter].setVisible(False) self.layout.addWidget(self.buttons[button_letter]) self.layout.addStretch() if 'straighten' in buttons: self.straighten_icon = QIcon( str(image_dir / 'StraightenAndDivideEvenly.svg')) self.buttons['straighten'] = OSMWDPushButton( '', "btn_straighten", icon=self.straighten_icon) self.layout.addWidget(self.buttons['straighten']) if 'combine' in buttons: self.combine_icon = QIcon(str(image_dir / 'CombineTracks.svg')) self.buttons['combine'] = OSMWDPushButton('', "btn_combine", icon=self.combine_icon) self.layout.addWidget(self.buttons['combine']) if 'copy' in buttons: self.copy_icon = QIcon(str(image_dir / 'CopyToClipboard.svg')) self.buttons['copy'] = OSMWDPushButton('', "btn_copy", icon=self.copy_icon) self.layout.addWidget(self.buttons['copy']) if 'replace' in buttons: self.replace_icon = QIcon(str(image_dir / 'Replace.svg')) self.buttons['replace'] = OSMWDPushButton('', "btn_replace", icon=self.replace_icon) self.layout.addWidget(self.buttons['replace']) if 'add' in buttons: self.add_icon = QIcon(str(image_dir / 'Add.svg')) self.buttons['add'] = OSMWDPushButton('', "btn_add", icon=self.add_icon) self.layout.addWidget(self.buttons['add']) if 'save' in buttons: self.save_icon = QIcon(str(image_dir / 'Save.svg')) self.buttons['save'] = OSMWDPushButton('', "btn_save", icon=self.save_icon) self.layout.addWidget(self.buttons['save']) if 'historical' in buttons: self.historical_icon = QIcon(str(image_dir / 'Historical.svg')) self.buttons['historical'] = OSMWDPushButton( '', "btn_historical", icon=self.historical_icon) self.layout.addWidget(self.buttons['historical']) if 'filter' in buttons: self.filter_icon = QIcon(str(image_dir / 'Filter.svg')) self.buttons['filter'] = OSMWDPushButton('', "btn_filter", icon=self.filter_icon) self.layout.addWidget(self.buttons['filter']) if 'link_segment' in buttons: self.link_segment_icon = QIcon( str(image_dir / 'LinkSegmentToPoi.svg')) self.buttons['link_segment'] = OSMWDPushButton( '', "btn_link_segment", icon=self.link_segment_icon) self.layout.addWidget(self.buttons['link_segment']) if 'split_track' in buttons: self.split_track_icon = QIcon(str(image_dir / 'SplitTrack.svg')) self.buttons['split_track'] = OSMWDPushButton( '', "btn_split_track", icon=self.split_track_icon) self.layout.addWidget(self.buttons['split_track']) if 'delete' in buttons: self.delete_icon = QIcon(str(image_dir / 'Remove.svg')) self.buttons['delete'] = OSMWDPushButton('', "btn_delete", icon=self.delete_icon) self.layout.addWidget(self.buttons['delete'])
class MainApp(QWidget): def __init__(self): super().__init__() self.setGeometry(0, 0, 400, 600) self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowTitle("Feats") self.stim_filename = None self.meeg_filename = None self.files_loaded = False self.font = QFont() self.font.setPointSize(24) self.layout.setHorizontalSpacing(25) self.loadlabel = QLabel("Load") self.loadlabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.loadlabel.setFont(self.font) self.launchlabel = QLabel("Launch") self.launchlabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.launchlabel.setFont(self.font) self.layout.addWidget(self.loadlabel, 0, 0) self.layout.addWidget(self.launchlabel, 0, 1) butts = [["Stimuli", "M/EEG", "Definitions"], ["Explore", "Collect", "Infer"]] self.butt_dict = {} for col_idx, col in enumerate(butts): for row_idx, butt in enumerate(col): tempbutt = QPushButton(butt) tempbutt.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) tempbutt.setFont(self.font) tempbutt.setEnabled(False) self.layout.addWidget(tempbutt, row_idx + 1, col_idx) self.butt_dict[butt] = tempbutt self.butt_dict["Stimuli"].clicked.connect(self.stim_click) self.butt_dict["Stimuli"].setEnabled(True) self.butt_dict["M/EEG"].clicked.connect(self.meeg_click) self.butt_dict["M/EEG"].setEnabled(True) self.butt_dict["Definitions"].clicked.connect(self.def_click) self.show() def check_files(self): if self.stim_filename and self.meeg_filename: self.files_loaded = True self.butt_dict["Definitions"].setEnabled(True) else: self.files_loaded = False def stim_click(self): self.stim_filename, _ = QFileDialog.getOpenFileName() self.check_files() def meeg_click(self): self.meeg_filename, _ = QFileDialog.getOpenFileName() self.check_files() def def_click(self): self.def_filename, _ = QFileDialog.getOpenFileName() defs = importlib.import_module(self.def_filename)
#################################### # (c) Radu Berdan # ArC Instruments Ltd. # This code is licensed under GNU v3 license (see LICENSE.txt for details) #################################### from PyQt5.QtGui import QFont font1 = QFont() font1.setPointSize(12) font1.setBold(True) font2 = QFont() font2.setPointSize(10) font2.setBold(False) font3 = QFont() font3.setPointSize(9) font3.setBold(False) history_child = QFont() history_child.setPointSize(8) history_child.setBold(False) history_top = QFont() history_top.setPointSize(10) history_top.setBold(True)
class EditorBase(QsciScintilla): ARROW_MARKER_NUM = 8 def __init__(self, parent=None): super(EditorBase, self).__init__(parent) # don't allow editing by default self.setReadOnly(True) # Set the default font self.font = QFont() self.font.setFamily('Courier') self.font.setFixedPitch(True) self.font.setPointSize(12) self.setFont(self.font) self.setMarginsFont(self.font) # Margin 0 is used for line numbers self.setMarginsFont(self.font) self.set_margin_width(7) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QColor("#cccccc")) # Clickable margin 1 for showing markers self.setMarginSensitivity(1, False) # setting marker margin width to zero make the marker highlight line self.setMarginWidth(1, 0) #self.matginClicked.connect(self.on_margin_clicked) self.markerDefine(QsciScintilla.Background, self.ARROW_MARKER_NUM) self.setMarkerBackgroundColor(QColor("#ffe4e4"), self.ARROW_MARKER_NUM) # Brace matching: enable for a brace immediately before or after # the current position # self.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Current line visible with special background color self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor("#ffe4e4")) # Set custom gcode lexer self.set_gcode_lexer() # Don't want to see the horizontal scrollbar at all # Use raw message to Scintilla here (all messages are documented # here: http://www.scintilla.org/ScintillaDoc.html) #self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTH, 700) self.SendScintilla(QsciScintilla.SCI_SETSCROLLWIDTHTRACKING) # default gray background self.set_background_color('#C0C0C0') self._stylebackgroundColor = '#C0C0C0' # not too small self.setMinimumSize(200, 100) self.filepath = None def set_margin_width(self, width): fontmetrics = QFontMetrics(self.font) self.setMarginsFont(self.font) self.setMarginWidth(0, fontmetrics.width("0" * width) + 6) # must set lexer paper background color _and_ editor background color it seems def set_background_color(self, color): self.SendScintilla(QsciScintilla.SCI_STYLESETBACK, QsciScintilla.STYLE_DEFAULT, QColor(color)) self.lexer.setPaperBackground(QColor(color)) def on_margin_clicked(self, nmargin, nline, modifiers): # Toggle marker for the line the margin was clicked on if self.markersAtLine(nline) != 0: self.markerDelete(nline, self.ARROW_MARKER_NUM) else: self.markerAdd(nline, self.ARROW_MARKER_NUM) def set_python_lexer(self): self.lexer = QsciLexerPython() self.lexer.setDefaultFont(self.font) self.setLexer(self.lexer) #self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier') def set_gcode_lexer(self): self.lexer = GcodeLexer(self) self.setLexer(self.lexer) def new_text(self): self.setText('') def load_text(self, filepath): self.filepath = filepath try: fp = os.path.expanduser(filepath) self.setText(open(fp).read()) except: LOG.error('File path is not valid: {}'.format(filepath)) self.setText('') return self.ensureCursorVisible() self.SendScintilla(QsciScintilla.SCI_VERTICALCENTRECARET) self.setModified(False) def save_text(self): with open(self.filepath + 'text', "w") as text_file: text_file.write(self.text()) def replace_text(self, text): self.replace(text) def search(self, text, re=False, case=False, word=False, wrap=False, fwd=True):
class SanGUI(QMainWindow): def __init__(self): super().__init__() self.init_window() self.init_menu() self.init_info() self.init_maingame() self.init_progress() self.init_background() def init_window(self): self.resize(1280, 720) self.move(300, 100) self.Main = QWidget() self.Main_layout = QGridLayout() self.Main.setLayout(self.Main_layout) self.Info = QWidget() self.Info_layout = QGridLayout() self.Info.setLayout(self.Info_layout) self.Progress = QWidget() self.Progress_layout = QGridLayout() self.Progress.setLayout(self.Progress_layout) self.MainGame = QWidget() self.MainGame_layout = QGridLayout() self.MainGame.setLayout(self.MainGame_layout) self.MainGame.setStyleSheet('QWidget{background:url(background.jpg)}') self.Main_layout.addWidget(self.Info, 0, 0, 1, 20) self.Main_layout.addWidget(self.Progress, 1, 0, 21, 4) self.Main_layout.addWidget(self.MainGame, 1, 4, 21, 16) self.setCentralWidget(self.Main) def init_menu(self): self.menu = self.menuBar() self.building = self.menu.addMenu('建造') self.military = self.menu.addMenu('军事') # 建造 self.b_econ = QMenu('经济建筑', self) self.b_mili = QMenu('军事建筑', self) self.b_foreign = QMenu('外交建筑', self) self.building.addMenu(self.b_econ) self.building.addMenu(self.b_mili) self.building.addMenu(self.b_foreign) # 经济建筑 self.mkt = QAction('市场', self) self.farm = QAction('农场', self) self.lumber = QAction('伐木场', self) self.ore = QAction('采矿场', self) self.b_econ.addAction(self.mkt) self.b_econ.addAction(self.farm) self.b_econ.addAction(self.lumber) self.b_econ.addAction(self.ore) # 军事建筑 self.camp = QAction('兵营', self) self.stable = QAction('马厩', self) self.range = QAction('射手营', self) self.machine = QAction('攻城器械厂', self) self.b_mili.addAction(self.camp) self.b_mili.addAction(self.stable) self.b_mili.addAction(self.range) self.b_mili.addAction(self.machine) # 外交建筑 # 军事 self.m_training = QAction('训练', self) self.m_conscription = QAction('征兵', self) self.military.addAction(self.m_training) self.military.addAction(self.m_conscription) # Font self.menu_font = self.menu.font() self.menu_font.setPointSize(14) self.menu_font.setFamily('楷体') self.menu.setFont(self.menu_font) self.building.setFont(self.menu_font) self.b_econ.setFont(self.menu_font) self.b_mili.setFont(self.menu_font) self.military.setFont(self.menu_font) def init_info(self): self.money_L = QLabel('金币:') self.wheat_L = QLabel('粮食:') self.lumber_L = QLabel('木材:') self.ore_L = QLabel('铁矿:') self.population_L = QLabel('人口:') self.money_L.setAlignment(Qt.AlignCenter) self.wheat_L.setAlignment(Qt.AlignCenter) self.lumber_L.setAlignment(Qt.AlignCenter) self.ore_L.setAlignment(Qt.AlignCenter) self.population_L.setAlignment(Qt.AlignCenter) self.info_font = QFont() self.info_font.setPointSize(13) self.info_font.setFamily('楷体') self.money_L.setFont(self.info_font) self.wheat_L.setFont(self.info_font) self.lumber_L.setFont(self.info_font) self.ore_L.setFont(self.info_font) self.population_L.setFont(self.info_font) self.money_LE = QLabel() self.wheat_LE = QLabel() self.lumber_LE = QLabel() self.ore_LE = QLabel() self.population_LE = QLabel() self.money_LE.setFixedSize(150, 25) self.wheat_LE.setFixedSize(150, 25) self.lumber_LE.setFixedSize(150, 25) self.ore_LE.setFixedSize(150, 25) self.population_LE.setFixedSize(150, 25) self.money_LE.setAlignment(Qt.AlignRight) self.wheat_LE.setAlignment(Qt.AlignRight) self.lumber_LE.setAlignment(Qt.AlignRight) self.ore_LE.setAlignment(Qt.AlignRight) self.population_LE.setAlignment(Qt.AlignRight) self.money_LE.setStyleSheet( 'background:white; border-width:1; border-style:solid; border-color:black' ) self.wheat_LE.setStyleSheet( 'background:white; border-width:1; border-style:solid; border-color:black' ) self.lumber_LE.setStyleSheet( 'background:white; border-width:1; border-style:solid; border-color:black' ) self.ore_LE.setStyleSheet( 'background:white; border-width:1; border-style:solid; border-color:black' ) self.population_LE.setStyleSheet( 'background:white; border-width:1; border-style:solid; border-color:black' ) self.Info_layout.addWidget(self.money_L, 0, 0, 1, 2) self.Info_layout.addWidget(self.money_LE, 0, 2, 1, 2) self.Info_layout.addWidget(self.wheat_L, 0, 4, 1, 2) self.Info_layout.addWidget(self.wheat_LE, 0, 6, 1, 2) self.Info_layout.addWidget(self.lumber_L, 0, 8, 1, 2) self.Info_layout.addWidget(self.lumber_LE, 0, 10, 1, 2) self.Info_layout.addWidget(self.ore_L, 0, 12, 1, 2) self.Info_layout.addWidget(self.ore_LE, 0, 14, 1, 2) self.Info_layout.addWidget(self.population_L, 0, 16, 1, 2) self.Info_layout.addWidget(self.population_LE, 0, 18, 1, 2) def init_maingame(self): self.maingame_title = QLabel('建筑信息') self.mkt1 = QPushButton('市场1') self.mkt2 = QPushButton('市场2') self.farm1 = QPushButton('农场1') self.farm2 = QPushButton('农场2') self.lumber1 = QPushButton('伐木场1') self.lumber2 = QPushButton('伐木场2') self.ore1 = QPushButton('矿场1') self.ore2 = QPushButton('矿场2') self.camp1 = QPushButton('兵营1') self.camp2 = QPushButton('兵营2') self.range1 = QPushButton('射手营1') self.range2 = QPushButton('射手营2') self.stable1 = QPushButton('马厩1') self.stable2 = QPushButton('马厩2') self.machine = QPushButton('器械厂') self.trade = QPushButton('交易市场') self.policy = QPushButton('策略营') self.tavern = QPushButton('酒馆') self.mkt1.setStyleSheet('background:white') self.maingame_title.setFont(QFont('楷体', 20)) self.maingame_title.setAlignment(Qt.AlignCenter) self.MainGame_layout.addWidget(self.maingame_title, 1, 0, 1, 12) self.MainGame_layout.addWidget(self.mkt1, 1, 1, 2, 3) self.MainGame_layout.addWidget(self.mkt2, 1, 5, 2, 3) self.MainGame_layout.addWidget(self.farm1, 1, 9, 2, 3) self.MainGame_layout.addWidget(self.farm2, 2, 1, 2, 3) self.MainGame_layout.addWidget(self.lumber1, 2, 5, 2, 3) self.MainGame_layout.addWidget(self.lumber2, 2, 9, 2, 3) self.MainGame_layout.addWidget(self.ore1, 3, 1, 2, 3) self.MainGame_layout.addWidget(self.ore2, 3, 5, 2, 3) self.MainGame_layout.addWidget(self.camp1, 3, 9, 2, 3) self.MainGame_layout.addWidget(self.camp2, 4, 1, 2, 3) self.MainGame_layout.addWidget(self.range1, 4, 5, 2, 3) self.MainGame_layout.addWidget(self.range2, 4, 9, 2, 3) self.MainGame_layout.addWidget(self.stable1, 5, 1, 2, 3) self.MainGame_layout.addWidget(self.stable2, 5, 5, 2, 3) self.MainGame_layout.addWidget(self.machine, 5, 9, 2, 3) self.MainGame_layout.addWidget(self.trade, 6, 1, 2, 3) self.MainGame_layout.addWidget(self.policy, 6, 5, 2, 3) self.MainGame_layout.addWidget(self.tavern, 6, 9, 2, 3) def init_progress(self): self.upgrade1 = QLabel('队列1') self.upgrade2 = QLabel('队列2') self.upgrade3 = QLabel('队列3') self.upgrade4 = QLabel('队列4') self.upgrade5 = QLabel('队列5') self.t1 = QLabel() self.t2 = QLabel() self.t3 = QLabel() self.t4 = QLabel() self.t5 = QLabel() self.p1 = QProgressBar() self.p2 = QProgressBar() self.p3 = QProgressBar() self.p4 = QProgressBar() self.p5 = QProgressBar() self.p1.setFixedSize(200, 15) self.p2.setFixedSize(200, 15) self.p3.setFixedSize(200, 15) self.p4.setFixedSize(200, 15) self.p5.setFixedSize(200, 15) self.blank = QLabel() self.Progress_layout.addWidget(self.upgrade1, 0, 0, 1, 1) self.Progress_layout.addWidget(self.t1, 1, 0, 1, 1) self.Progress_layout.addWidget(self.p1, 2, 0, 1, 4) self.Progress_layout.addWidget(self.upgrade2, 3, 0, 1, 1) self.Progress_layout.addWidget(self.t2, 4, 0, 1, 1) self.Progress_layout.addWidget(self.p2, 5, 0, 1, 4) self.Progress_layout.addWidget(self.upgrade3, 6, 0, 1, 1) self.Progress_layout.addWidget(self.t3, 7, 0, 1, 1) self.Progress_layout.addWidget(self.p3, 8, 0, 1, 4) self.Progress_layout.addWidget(self.upgrade4, 9, 0, 1, 1) self.Progress_layout.addWidget(self.t4, 10, 0, 1, 1) self.Progress_layout.addWidget(self.p4, 11, 0, 1, 4) self.Progress_layout.addWidget(self.upgrade5, 12, 0, 1, 1) self.Progress_layout.addWidget(self.t5, 13, 0, 1, 1) self.Progress_layout.addWidget(self.p5, 14, 0, 1, 4) self.Progress_layout.addWidget(self.blank, 15, 0, 10, 4) self.Progress.setFont(QFont('楷体', 12)) def init_background(self): # opacity = QGraphicsOpacityEffect() # opacity.setOpacity(0.5) # # self.Info.setStyleSheet('background:rgb(199, 199, 199)') # self.Progress.setStyleSheet('background:rgb(199, 199, 199)') self.MainGame.setFont(self.menu_font) # self.MainGame.setStyleSheet('background:white') # self.MainGame.setGraphicsEffect(opacity) self.Main_layout.setSpacing(0)
def setupUi(self, MainWindow): QDesk MainWindow.resize(1200, 800) #메인 화면 색상py self.setStyleSheet("color: black;" "background-color: white;") font = QFont() font.setFamily("NanumGothic") MainWindow.setFont(font) self.centralwidget = QWidget(MainWindow) self.label = QLabel(self.centralwidget) self.label.setGeometry(QRect(20, 20, 101, 31)) font = QFont() font.setFamily("NanumGothic") font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.button_add = QPushButton(self.centralwidget) self.button_add.setGeometry(QRect(60, 730, 131, 34)) #버튼 스타일 변경 self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_add.setFont(staticValues.buttonFont) self.button_modi = QPushButton(self.centralwidget) self.button_modi.setGeometry(QRect(260, 730, 131, 34)) self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_modi.setFont(staticValues.buttonFont) self.button_del = QPushButton(self.centralwidget) self.button_del.setGeometry(QRect(460, 730, 131, 34)) self.button_del.setStyleSheet(staticValues.redButtonStyleSheet) self.button_del.setFont(staticValues.buttonFont) self.button_upload = QPushButton(self.centralwidget) self.button_upload.setGeometry(QRect(790, 730, 131, 34)) self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_upload.setFont(staticValues.buttonFont) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QRect(40, 70, 1121, 621)) self.tab = QWidget() self.tab.layout = QVBoxLayout() self.tabWidget.addTab(self.tab, "회원 목록") self.tableWidget = QTableWidget(self.tab) self.tableWidget.setGeometry(QRect(0, 0, 1111, 591)) self.tableWidget.setObjectName("회원 목록") self.tableWidget.setColumnCount(13) self.tableWidget.setRowCount(0) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels([ "회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근", "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소" ]) # self.tableView = QTableWidget() # self.tableView.setColumnCount(5) # self.tableView.setRowCount(3) # self.tab.layout.addWidget(self.tableView) # self.tab.setLayout(self.tab.layout) # self.tab_2 = QWidget() # self.tabWidget.addTab(self.tab_2, "") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.setWindowModality(Qt.NonModal) MainWindow.resize(423, 347) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.gridLayoutWidget = QWidget(self.centralwidget) self.gridLayoutWidget.setObjectName(u"gridLayoutWidget") self.gridLayoutWidget.setGeometry(QRect(10, 40, 123, 68)) self.gridLayout = QGridLayout(self.gridLayoutWidget) self.gridLayout.setObjectName(u"gridLayout") self.gridLayout.setSizeConstraint(QLayout.SetMaximumSize) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName(u"verticalLayout_2") self.chkScreenRest = QCheckBox(self.gridLayoutWidget) self.chkScreenRest.setObjectName(u"chkScreenRest") sizePolicy1 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth( self.chkScreenRest.sizePolicy().hasHeightForWidth()) self.chkScreenRest.setSizePolicy(sizePolicy1) font = QFont() font.setFamily(u"Roboto") font.setPointSize(14) font.setBold(False) font.setItalic(True) font.setWeight(50) self.chkScreenRest.setFont(font) self.chkScreenRest.setChecked(False) self.verticalLayout_2.addWidget(self.chkScreenRest) self.chkEyeBlink = QCheckBox(self.gridLayoutWidget) self.chkEyeBlink.setObjectName(u"chkEyeBlink") font1 = QFont() font1.setFamily(u"Roboto") font1.setPointSize(14) font1.setItalic(True) self.chkEyeBlink.setFont(font1) self.verticalLayout_2.addWidget(self.chkEyeBlink) self.gridLayout.addLayout(self.verticalLayout_2, 1, 0, 1, 1) self.lblMonitor = QLabel(self.centralwidget) self.lblMonitor.setObjectName(u"lblMonitor") self.lblMonitor.setGeometry(QRect(20, 10, 141, 21)) sizePolicy2 = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) sizePolicy2.setHorizontalStretch(0) sizePolicy2.setVerticalStretch(0) sizePolicy2.setHeightForWidth( self.lblMonitor.sizePolicy().hasHeightForWidth()) self.lblMonitor.setSizePolicy(sizePolicy2) font2 = QFont() font2.setFamily(u"Open Sans") font2.setPointSize(16) font2.setBold(True) font2.setWeight(75) self.lblMonitor.setFont(font2) self.lblNotification = QLabel(self.centralwidget) self.lblNotification.setObjectName(u"lblNotification") self.lblNotification.setGeometry(QRect(190, 10, 141, 21)) sizePolicy2.setHeightForWidth( self.lblNotification.sizePolicy().hasHeightForWidth()) self.lblNotification.setSizePolicy(sizePolicy2) self.lblNotification.setFont(font2) self.gridLayoutWidget_2 = QWidget(self.centralwidget) self.gridLayoutWidget_2.setObjectName(u"gridLayoutWidget_2") self.gridLayoutWidget_2.setGeometry(QRect(180, 40, 233, 68)) self.gridLayout_2 = QGridLayout(self.gridLayoutWidget_2) self.gridLayout_2.setObjectName(u"gridLayout_2") self.gridLayout_2.setSizeConstraint(QLayout.SetMaximumSize) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName(u"verticalLayout") self.chkNotificationBanner = QCheckBox(self.gridLayoutWidget_2) self.chkNotificationBanner.setObjectName(u"chkNotificationBanner") self.chkNotificationBanner.setFont(font1) self.verticalLayout.addWidget(self.chkNotificationBanner) self.chkConnectSmartphone = QCheckBox(self.gridLayoutWidget_2) self.chkConnectSmartphone.setObjectName(u"chkConnectSmartphone") sizePolicy1.setHeightForWidth( self.chkConnectSmartphone.sizePolicy().hasHeightForWidth()) self.chkConnectSmartphone.setSizePolicy(sizePolicy1) self.chkConnectSmartphone.setFont(font) self.chkConnectSmartphone.setChecked(False) self.verticalLayout.addWidget(self.chkConnectSmartphone) self.gridLayout_2.addLayout(self.verticalLayout, 1, 0, 1, 1) self.lblSetting = QLabel(self.centralwidget) self.lblSetting.setObjectName(u"lblSetting") self.lblSetting.setGeometry(QRect(20, 120, 141, 31)) sizePolicy2.setHeightForWidth( self.lblSetting.sizePolicy().hasHeightForWidth()) self.lblSetting.setSizePolicy(sizePolicy2) self.lblSetting.setFont(font2) self.btnStart = QPushButton(self.centralwidget) self.btnStart.setObjectName(u"btnStart") self.btnStart.setGeometry(QRect(50, 270, 161, 31)) font3 = QFont() font3.setFamily(u"Malgun Gothic") font3.setPointSize(14) self.btnStart.setFont(font3) self.btnStop = QPushButton(self.centralwidget) self.btnStop.setObjectName(u"btnStop") self.btnStop.setGeometry(QRect(260, 270, 91, 31)) self.btnStop.setFont(font3) self.widget = QWidget(self.centralwidget) self.widget.setObjectName(u"widget") self.widget.setGeometry(QRect(10, 160, 409, 99)) self.horizontalLayout = QHBoxLayout(self.widget) self.horizontalLayout.setObjectName(u"horizontalLayout") self.horizontalLayout.setSizeConstraint(QLayout.SetMinimumSize) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.lblBlinkTime = QLabel(self.widget) self.lblBlinkTime.setObjectName(u"lblBlinkTime") self.horizontalLayout.addWidget(self.lblBlinkTime) self.txtBlinkTime = QLineEdit(self.widget) self.txtBlinkTime.setObjectName(u"txtBlinkTime") font4 = QFont() font4.setPointSize(10) self.txtBlinkTime.setFont(font4) self.horizontalLayout.addWidget(self.txtBlinkTime) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName(u"menubar") self.menubar.setGeometry(QRect(0, 0, 423, 21)) MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(u"statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) # settingsRestoration self.chkScreenRest.setChecked(bool(Util.get_screen_rest_monitoring())) self.chkEyeBlink.setChecked(bool(Util.get_blink_monitoring())) self.chkNotificationBanner.setChecked( bool(Util.get_notification_enabled())) self.chkConnectSmartphone.setChecked( bool(Util.get_smart_notification_enabled())) self.txtBlinkTime.setText(Util.get_timeout()) # events self.btnStart.clicked.connect( lambda: start_blink_detection()) # Set Start button self.chkScreenRest.stateChanged.connect( lambda: Util.set_screen_rest_monitoring(self.chkScreenRest. isChecked())) self.chkEyeBlink.stateChanged.connect( lambda: Util.set_blink_monitoring(self.chkEyeBlink.isChecked())) self.chkConnectSmartphone.stateChanged.connect( lambda: Util.set_smart_notification_enabled( self.chkConnectSmartphone.isChecked())) self.chkNotificationBanner.stateChanged.connect( lambda: Util.set_notification_enabled(self.chkNotificationBanner. isChecked())) self.txtBlinkTime.editingFinished.connect( lambda: Util.set_timeout(self.txtBlinkTime.text())) self.btnStop.clicked.connect(sys.exit) QMetaObject.connectSlotsByName(MainWindow)
def paintEvent(self, event): fs = self.font_size cfs = self.current_font_size p = QPainter(self) p.setRenderHint(QPainter.Antialiasing, True) center_point = QPointF(self.width() / 2, self.height() / 2) p.translate(center_point) font = QFont() font.setFamily('consolas') font.setBold(True) font.setPointSize(cfs * 2) p.setFont(font) rect = QRectF(-10 * fs, -2 * fs, 20 * fs, 4 * fs) p.drawText(rect, Qt.AlignCenter, f'{self.year}/{self.month:02}/{self.day:02}') hour = self.hour int_hour = int(hour) point_hour = QPoint(18 * fs, 0) minute = self.minute int_minute = int(minute) point_minute = QPoint(21 * fs, 0) second = self.second int_second = int(second) point_second = QPoint(24 * fs, 0) font.setPointSize(cfs) p.setFont(font) rect = QRectF(point_hour.x() + fs, point_hour.y() - fs - 1, 2 * fs, 2 * fs) p.drawText(rect, Qt.AlignVCenter, ':') rect = QRectF(point_minute.x() + fs, point_minute.y() - fs - 1, 2 * fs, 2 * fs) p.drawText(rect, Qt.AlignVCenter, ':') for H in range(int_hour, 24 + int_hour): point_hour = self.rotate(point_hour, (H + math.modf(hour)[0] + 1) * 15) H = 24 - H + int_hour - 1 if H == int_hour + int(self._flag_h): font.setBold(True) font.setPointSize(cfs) elif H == 0 and int_hour == 23 and self._flag_h: font.setBold(True) font.setPointSize(cfs) else: font.setBold(False) font.setPointSize(fs) p.setFont(font) rect = QRectF(point_hour.x() - fs, point_hour.y() - fs, 2 * fs, 2 * fs) p.drawText(rect, Qt.AlignCenter, f'{H:02}') for M in range(int_minute, 60 + int_minute): point_minute = self.rotate(point_minute, (M + math.modf(minute)[0] + 1) * 6) M = 60 - M + int_minute - 1 if M == int_minute + int(self._flag_m): font.setBold(True) font.setPointSize(cfs) elif int_minute == 59 and M == 0 and self._flag_m: font.setBold(True) font.setPointSize(cfs) else: font.setBold(False) font.setPointSize(fs) p.setFont(font) rect = QRectF(point_minute.x() - fs, point_minute.y() - fs, 2 * fs, 2 * fs) p.drawText(rect, Qt.AlignCenter, f'{M:02}') for S in range(int_second, 60 + int_second): point = self.rotate(point_second, (S + math.modf(second)[0] + 1) * 6) S = 60 - S + int_second - 1 if S == int_second + 1 or S == 0 and int_second == 59: font.setBold(True) font.setPointSize(cfs) else: font.setBold(False) font.setPointSize(fs) p.setFont(font) rect = QRectF(point.x() - fs, point.y() - fs, 2 * fs, 2 * fs) p.drawText(rect, Qt.AlignCenter, f'{S:02}')
def draw(self): if len(self.line_xs) == 0: return to_plot_x = [] to_plot_y = [] for k in self.line_map.keys(): if self.line_active[k]: to_plot_x.append(self.line_xs[self.line_map[k]]) to_plot_y.append(self.line_ys[self.line_map[k]]) if len(to_plot_y) == 0: return if self.force_xmax is None: self.max_x = np.amax(to_plot_x) else: self.max_x = self.force_xmax if self.force_ymax is None: self.max_y = np.amax(to_plot_y) else: self.max_y = self.force_ymax x_ceil, x_step = self.get_ceil(self.max_x) y_ceil, y_step = self.get_ceil(self.max_y) self.x_ceil = x_ceil self.y_ceil = y_ceil xs = np.multiply(np.divide(self.line_xs, x_ceil), self.base_line_x) ys = np.multiply(np.divide(self.line_ys, y_ceil), self.base_line_y) if self.sub_sampling > 4: for i in range(ys.shape[0]): wf = np.clip(self.sub_sampling, 0, ys.shape[1] - 1) if wf % 2 == 0: wf -= 1 ys[i] = savgol_filter(ys[i], wf, 3) p = QPen() p.setWidth(0.1) to_plot = [] for k in self.line_map.keys(): if self.line_active[k]: to_plot.append(self.line_map[k]) for j in range(xs.shape[0]): if j not in to_plot: continue p.setColor(self.line_cols[j]) path = None for i in range(xs.shape[1]): x = xs[j][i] y = self.base_line_y - ys[j][i] if i == 0: path = QPainterPath(QPointF(x, y)) else: path.lineTo(QPointF(x, y)) if path is not None: path = self.scene().addPath(path, p) self.lines.append(path) p.setColor(QColor(255,255,255,200)) n_legend = len(list(self.line_map.keys())) legend_box = self.scene().addRect(QRectF(self.base_line_x + 50, 50, 200, 30 * n_legend), p) font = QFont() font.setPointSize(10) c = 1 for name in sorted(list(self.line_map.keys())): if not self.line_active[name]: continue y = 50 + ((c * 30) - 15) p.setColor(self.line_cols[self.line_map[name]]) lbl = self.scene().addText(name, font) lbl.setPos(self.base_line_x + 55, y - lbl.boundingRect().height() / 2) lbl.setDefaultTextColor(QColor(255,255,255,255)) self.scene().addLine(self.base_line_x + 55 + lbl.boundingRect().width() + 5, y, self.base_line_x + 245, y, p) c += 1
cerrar.exec_() if cerrar.clickedButton() == botonSalir: event.accept() else: event.ignore() # =============================================================== if __name__ == "__main__": import sys aplicacion = QApplication(sys.argv) traductor = QTranslator(aplicacion) lugar = QLocale.system().name() path = QLibraryInfo.location(QLibraryInfo.TranslationsPath) traductor.load("qtbase_%s" % lugar, path) aplicacion.installTranslator(traductor) fuente = QFont() fuente.setPointSize(10) aplicacion.setFont(fuente) ventana = Siacle() ventana.showMaximized() sys.exit(aplicacion.exec_())
class WarehouseReceipt_Bill(JPReport): def __init__(self, PaperSize=QPrinter.A5, Orientation=QPrinter.Orientation(1)): super().__init__(PaperSize, Orientation) self.SetMargins(30, 60, 30, 30) self.CopyInfo = JPPub().getCopysInfo('BillCopys_WarehouseRreceipt') self.Copys = len(self.CopyInfo) self.logo = JPPub().MainForm.logoPixmap self.FillColor = JPPub().getConfigData( )['PrintHighlightBackgroundColor'] self.font_Algerian = QFont("Algerian") self.font_Algerian_11 = QFont(self.font_Algerian) self.font_Algerian_12 = QFont(self.font_Algerian) self.font_Algerian_11.setPointSize(11) self.font_Algerian_12.setPointSize(12) self.font_YaHei = QFont("微软雅黑") self.font_YaHei_8 = QFont(self.font_YaHei) self.font_YaHei_8.setPointSize(8) self.font_YaHei_10 = QFont(self.font_YaHei) self.font_YaHei_10.setPointSize(10) self.font_YaHei_10.setBold(True) def init_ReportHeader_title(self, title1="Outbound Order", title2="(ESTE DOCUMENTO É DO USO INTERNO)"): RH = self.ReportHeader RH.AddItemRect(2, (0, 0, 274, 50), self.logo) RH.AddItemRect(1, (274, 0, 400, 25), title1, Font=self.font_Algerian_12, AlignmentFlag=(Qt.AlignCenter), Bolder=False) RH.AddItemRect(1, (274, 25, 400, 25), title2, Font=self.font_Algerian_11, AlignmentFlag=(Qt.AlignTop | Qt.AlignHCenter), Bolder=False) def init_ReportHeader(self): # 第1行 RH = self.ReportHeader RH.AddItemRect(1, (0, 55, 90, 20), "入库单日期Date", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (90, 55, 90, 20), "fOrderDate", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(1, (180, 55, 150, 20), "入库日期WarehousingDate:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (330, 55, 70, 20), "fWarehousingDate", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(1, (400, 55, 90, 20), "入库单号Nº", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (490, 55, 160, 20), "fOrderID", Font=self.font_YaHei_10, AlignmentFlag=Qt.AlignCenter) # 第2行 RH.AddItemRect(1, (0, 75, 90, 20), "客户Supplier:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (90, 75, 310, 20), "fSupplierName", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") RH.AddItemRect(1, (400, 75, 90, 20), "采购Purchaser:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (490, 75, 160, 20), "fPurchaser", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") # 第3行 RH.AddItemRect(1, (0, 95, 90, 20), "税号NUIT:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (90, 95, 310, 20), "fNUIT", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") RH.AddItemRect(1, (400, 95, 90, 20), "城市City:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (490, 95, 160, 20), "fCity", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") # 第4行 RH.AddItemRect(1, (0, 115, 90, 20), "联系人Contato:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (90, 115, 90, 20), "fContato", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") RH.AddItemRect(1, (180, 115, 130, 20), "手机Celular:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (310, 115, 90, 20), "fCelular", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") RH.AddItemRect(1, (400, 115, 90, 20), "电子邮件Email:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) RH.AddItemRect(3, (490, 115, 160, 20), "fEmail", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft | Qt.AlignVCenter, FormatString=" {}") # 联次信息 tempItem = RH.AddItemRect(1, (655, 60, 120, 20), " CONT. / PRDUCAO", Bolder=False, Transform=True, Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignLeft) def init_ReportHeader_Individualization(self): # 第6行 Order个性部分 RH = self.ReportHeader RH.AddPrintLables( 0, 135, 20, ["#", "名称Descrição", "数量Qtd", "单价P. Unitario", "金额Total"], [40, 370, 80, 80, 80], [ Qt.AlignCenter, Qt.AlignCenter, Qt.AlignCenter, Qt.AlignCenter, Qt.AlignCenter ], FillColor=self.FillColor, Font=self.font_YaHei_8) def init_PageHeader(self, title1="Outbound Order", title2="(ESTE DOCUMENTO É DO USO INTERNO)"): PH = self.PageHeader PH.AddItemRect(2, (0, 0, 274, 50), self.logo) font_title = QFont("Algerian", 12) font_title.setBold(True) PH.AddItemRect(1, (274, 0, 400, 25), title1, Font=self.font_Algerian_12, AlignmentFlag=(Qt.AlignCenter), Bolder=False) PH.AddItemRect(1, (274, 25, 400, 25), title2, Font=self.font_Algerian_11, AlignmentFlag=(Qt.AlignTop | Qt.AlignVCenter | Qt.AlignHCenter), Bolder=False) # 第1行 PH.AddItemRect(1, (0, 55, 90, 20), "入库单日期Date", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) PH.AddItemRect(3, (90, 55, 90, 20), "fOrderDate", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) PH.AddItemRect(1, (180, 55, 130, 20), "入库日期WarehousingDate:", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) PH.AddItemRect(3, (310, 55, 90, 20), "fWarehousingDate", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) self.font_YaHei_10.setBold(True) PH.AddItemRect(1, (400, 55, 90, 20), "出库单号码Nº", Font=self.font_YaHei_8, AlignmentFlag=Qt.AlignCenter) PH.AddItemRect(3, (490, 55, 160, 20), "fOrderID", Font=self.font_YaHei_10, AlignmentFlag=Qt.AlignCenter) # 第2行 PH.AddPrintLables( 0, 75, 20, ["#", "名称Descrição", "数量Qtd", "单价P. Unitario", "金额Total"], [40, 370, 80, 80, 80], [ Qt.AlignCenter, Qt.AlignCenter, Qt.AlignCenter, Qt.AlignCenter, Qt.AlignCenter ], Font=self.font_YaHei_8, FillColor=self.FillColor) def init_Detail(self): D = self.Detail D.AddPrintFields(0, 0, 20, ["fQuant", "fProductName"], [40, 370], [Qt.AlignCenter, Qt.AlignLeft], Font=self.font_YaHei_8) D.AddPrintFields(410, 0, 20, ["fQuant", "fPrice"], [80, 80], [(Qt.AlignRight | Qt.AlignVCenter), (Qt.AlignRight | Qt.AlignVCenter)], Font=self.font_YaHei_8, FormatString='{:,.3f} ') D.AddPrintFields(570, 0, 20, ["fAmount"], [80], [(Qt.AlignRight | Qt.AlignVCenter)], Font=self.font_YaHei_8, FormatString='{:,.2f} ') def init_ReportFooter(self): RF = self.ReportFooter RF.AddItemRect(1, (430, 0, 140, 20), "金额合计SubTotal:", Font=self.font_YaHei_8, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter)) RF.AddItemRect(3, (570, 0, 80, 20), "fAmount", FormatString='{:,.2f} ', AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(1, (430, 20, 140, 20), "折扣Desconto:", AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(3, (570, 20, 80, 20), "fDesconto", AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), FormatString='{:,.2f} ', Font=self.font_YaHei_8) RF.AddItemRect(1, (430, 40, 140, 20), "税金IVA:", AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(3, (570, 40, 80, 20), "fTax", FormatString='{:,.2f} ', AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(1, (430, 60, 140, 20), "应付金额Valor a Pagar:", Font=self.font_YaHei_8, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter)) RF.AddItemRect(3, (570, 60, 80, 20), "fPayable", FormatString='{:,.2f} ', AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(3, (0, 0, 430, 80), "fNote1", FormatString='备注Note:\n{}', Bolder=True, AlignmentFlag=(Qt.AlignLeft | Qt.TextWordWrap), Font=self.font_YaHei_8) # 签字部分 RF.AddItemRect(1, (0, 110, 100, 20), '制作人 Productor:', Bolder=False, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(1, (100, 125, 100, 0), '') RF.AddItemRect(1, (220, 110, 100, 20), '审核人 Aprovar:', Bolder=False, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(1, (320, 125, 100, 0), '') RF.AddItemRect(1, (420, 110, 120, 20), '会计Caixa:', Bolder=False, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(1, (540, 125, 100, 0), '') RF.AddItemRect(1, (390, 140, 150, 20), '库管Warehouse Managem:', Bolder=False, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) RF.AddItemRect(1, (540, 155, 100, 0), '') self.PageFooter.AddItemRect(4, (10, 0, 100, 20), '', FormatString='Page: {Page}/{Pages}', Bolder=False, AlignmentFlag=Qt.AlignLeft, Font=self.font_YaHei_8) self.PageFooter.AddItemRect( 5, (110, 0, 540, 20), '', FormatString="PrintTime: %Y-%m-%d %H:%M:%S", Bolder=False, AlignmentFlag=(Qt.AlignRight | Qt.AlignVCenter), Font=self.font_YaHei_8) # 修改联次 def onBeforePrint(self, Copys, Sec, CurrentPrintDataRow, obj): title = self.CopyInfo[Copys - 1]['title'] flag = self.CopyInfo[Copys - 1]['flag'] if obj.PrintObject == " CONT. / PRDUCAO": return False, title elif obj.PrintObject == 'fProductName': return False, self.getFullProductName( CurrentPrintDataRow['fProductID']) else: if obj.PrintObject in [ "fPrice", "fAmountDetail", "fAmount", "fDesconto", "fTax", "fPayable" ]: return False, ' ' if flag is False else None return False, None def init_data(self, OrderID: str): SQL = f""" SELECT o.fOrderID, o.fOrderDate, o.fWarehousingDate , o.fSupplierName, o.fNUIT , o.fCity, o.fEndereco, o.fEmail , o.fContato, o.fCelular , o.fTelefone, o.fAmount , o.fTax, o.fPayable, o.fDesconto , o.fPurchaser , d.fQuant, d.fProductID, d.fPrice , d.fAmount as fAmount_detail, if(isnull(o.fNote),' ',o.fNote) AS fNote1 FROM v_product_warehousereceipt_order o RIGHT JOIN t_product_warehousereceipt_order_detail d ON o.fOrderID = d.fOrderID WHERE d.fOrderID='{OrderID}' """ db = JPDb() data = db.getDict(SQL) data.sort(key=lambda x: (x['fSupplierName'], x['fCity'], x['fAmount'] is None, x['fAmount'])) self.DataSource = data def BeginPrint(self): # 大于9行自动更改纸型 if len(self.DataSource) > 9: self.PaperSize = QPrinter.A4 self.Orientation = QPrinter.Orientation(0) return super().BeginPrint() def onFormat(self, SectionType, CurrentPage, RowDate=None): if (SectionType == JPPrintSectionType.PageHeader and CurrentPage == 1): return True def PrintCurrentReport(self, OrderID: str): self.init_data(OrderID) self.init_ReportHeader_title( title1="入库单 Warehouse Receipt", title2="(ESTE DOCUMENTO É DO USO INTERNO)") self.init_ReportHeader() self.init_ReportHeader_Individualization() self.init_PageHeader() self.init_Detail() self.init_ReportFooter() super().BeginPrint()
def __init__(self, number): super().__init__() self.number = number self.setFixedSize(200, 200) # 设置字体 font = QFont() font.setPointSize(30) font.setBold(True) self.setFont(font) # 设置字体颜色 pa = QPalette() pa.setColor(QPalette.WindowText, Qt.white) self.setPalette(pa) # 设置文字位置 self.setAlignment(Qt.AlignCenter) # 设置背景颜色\圆角和文本内容 if self.number == 0: self.setStyleSheet( "background-color:white") # border-image:url(./bc.gif); # if self.number == 2: # self.setStyleSheet("border - image: url(./2.png);background-color:white") # if self.number == 3: # self.setStyleSheet("border - image: url(./3.png);background-color:white") # if self.number == 4: # self.setStyleSheet("border - image: url(./4.png);background-color:white") # if self.number == 5: # self.setStyleSheet("border - image: url(./5.png);background-color:white") # if self.number == 6: # self.setStyleSheet("border - image: url(./6.png);background-color:white") # if self.number == 7: # self.setStyleSheet("border - image: url(./7.png);background-color:white") # if self.number == 8: # self.setStyleSheet("border - image: url(./8.png);background-color:white") # if self.number == 9: # self.setStyleSheet("border - image: url(./9.png);background-color:white") else: # self.setStyleSheet("background-color:red") # self.setText(str(self.number)) if self.number == 1: self.setStyleSheet( "border-image:url(./1.jpg);background-color:white") if self.number == 2: self.setStyleSheet( "border-image:url(./2.jpg);background-color:white") if self.number == 3: self.setStyleSheet( "border-image:url(./3.jpg);background-color:white") if self.number == 4: self.setStyleSheet( "border-image:url(./4.jpg);background-color:white") if self.number == 5: self.setStyleSheet( "border-image:url(./5.jpg);background-color:white") if self.number == 6: self.setStyleSheet( "border-image:url(./6.jpg);background-color:white") if self.number == 7: self.setStyleSheet( "border-image:url(./7.jpg);background-color:white") if self.number == 8: self.setStyleSheet( "border-image:url(./8.jpg);background-color:white") if self.number == 9: self.setStyleSheet( "border-image:url(./9.jpg);background-color:white")
class Text(DesignItem): def __init__(self, text, scene): super(Text, self).__init__(scene) self.font = QFont("Arial") self.font.setPointSize(14) self.font.setStyleName("Standard") self.text = text self.textcolor = QColor(Qt.black) self.data = str.encode(self.getSvg()) self.renderer = QSvgRenderer() self.renderer.load(self.data) self.svg = QGraphicsSvgItem(self) self.svg.setSharedRenderer(self.renderer) self.setRect(0, 0, self.svg.boundingRect().width(), self.svg.boundingRect().height()) def typeName(self): return "Text" def paint(self, paint, option, widget): if option.state & QStyle.State_Selected: self.drawHighlightSelected(paint, option) def getTextTag(self, id): fm = QFontMetrics(self.font) svg = "<text " if id: svg += "id=\"" + id + "\" " svg += "x=\"0\" y=\"" + str(fm.ascent()) + "\" " svg += "font-family=\"" + self.font.family() + "\" " svg += "font-size=\"" + str(self.font.pointSize() * 1.25) + "px\" " if self.font.bold(): svg += "font-weight=\"bold\" " if self.font.italic(): svg += "font-style=\"italic\" " svg += "fill=\"" + self.textcolor.name() + "\" " svg += "opacity=\"" + str(self.opacity()) + "\" " svg += ">" svg += self.text svg += "</text>" return svg def getSvg(self): font = QFont(self.font.family()) font.setBold(self.font.bold()) font.setItalic(self.font.italic()) font.setPixelSize(self.font.pointSize() * 1.25) fm = QFontMetrics(font) self.width = fm.width(self.text) + 2 self.height = fm.height() svg = "<svg width=\"" + str(self.width) + "\" " svg += "height=\"" + str(self.height) + "\" >" svg += self.getTextTag("") svg += "</svg>" return svg def setScale(self, x, y): self.xscale = x self.yscale = y trans = QTransform() trans.scale(self.xscale, self.yscale) self.svg.setTransform(trans) self.setRect(0, 0, self.svg.boundingRect().width() * x, self.svg.boundingRect().height() * y) def scaleObjects(self): self.xscale = self.rect.width() / self.svg.boundingRect().width() self.yscale = self.rect.height() / self.svg.boundingRect().height() trans = QTransform() trans.scale(self.xscale, self.yscale) self.svg.setTransform(trans)
class Window(QtWidgets.QWidget): def __init__(self): ''' Initilize all the widgets then call the GuiSetup to customize them ''' QtWidgets.QWidget.__init__(self) self.intents = json.loads(open('./src/data/intents.json').read()) self.words = pickle.load(open('./src/data/words.pkl', 'rb')) self.classes = pickle.load(open('./src/data/classes.pkl', 'rb')) self.model = load_model('./src/data/chatbot_model.h5') self.layout = QtWidgets.QVBoxLayout(self) self.font = QFont() self.font.setPointSize(12) self.chatlog = QtWidgets.QTextEdit() self.chatlog.setReadOnly(True) self.userinput = QtWidgets.QLineEdit() self.userinput.returnPressed.connect(self.AddToChat) self.GuiSetup() threading.Thread(target=self.run).start() def GuiSetup(self): self.chatlog.setStyleSheet(setStyleQte) self.userinput.setStyleSheet(setStyletui) self.userinput.setFont(self.font) self.layout.addWidget(self.chatlog) self.layout.addWidget(self.userinput) def AddToChat(self): umsg = self.userinput.text() self.chatlog.append("User: "******"~wait for answer~") self.userinput.setReadOnly(True) threading.Thread(target=self.chatbot_response, args=(umsg, )).start() def clean_up_sentence(self, sentence): #Remove "useless" words sentence_words = nltk.word_tokenize(sentence) return sentence_words # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence def bow(self, sentence, words, show_details=True): # tokenize the pattern sentence_words = self.clean_up_sentence(sentence) # bag of words - matrix of N words, vocabulary matrix bag = [0] * len(words) for s in sentence_words: for i, w in enumerate(words): if w == s: # assign 1 if current word is in the vocabulary position bag[i] = 1 if show_details: print("found in bag: %s" % w) return (np.array(bag)) def predict_class(self, sentence, model): # filter out predictions below a threshold p = self.bow(sentence, self.words, show_details=False) res = model.predict(np.array([p]))[0] ERROR_THRESHOLD = 0.4 results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD] # sort by strength of probability if (len(results) == 0): return_list = [] return_list.append({"intent": "no_result"}) else: results.sort(key=lambda x: x[1], reverse=True) return_list = [] for r in results: return_list.append({ "intent": self.classes[r[0]], "probability": str(r[1]) }) return return_list def getResponse(self, ints, msg, intents_json): tag = ints[0]['intent'] if (tag == "order"): self.order(msg) else: self.talk(tag) list_of_intents = intents_json['intents'] for i in list_of_intents: if (i['tag'] == tag): result = random.choice(i['responses']) break return result def chatbot_response(self, msg): ints = self.predict_class(msg.lower(), self.model) res = self.getResponse(ints, msg.lower(), self.intents) self.chatlog.append("PiLDIM: " + res) self.chatlog.setAlignment(Qt.AlignRight) self.userinput.setReadOnly(False) self.userinput.setText("") return res def order(self, content): global orders orders.put(content) def talk(self, tag): global talk talk.put(tag) def order_done(self, msg): self.chatlog.setAlignment(Qt.AlignRight) self.chatlog.append(msg) def run(self): while True: global tasks_done if (tasks_done.empty() is False): msg = tasks_done.get() self.order_done(msg)
def setupUi(self, MainWindow): resolution = QDesktopWidget().screenGeometry(self) # MainWindow.setGeometry(QRect(0,0,0,0)) MainWindow.setFixedSize(resolution.size().width()*0.99, resolution.size().height()*0.90)#1200 800 # self.setWindowState(Qt.WindowMaximized) print("resol : ", MainWindow.size()) #메인 화면 색상py self.setStyleSheet("color: black;" "background-color: white;") font = QFont() font.setFamily("NanumGothic") MainWindow.setFont(font) self.centralwidget = QWidget(MainWindow) self.label = QLabel(self.centralwidget) self.label.setGeometry(QRect(20, 20, 130, 35)) font = QFont() font.setFamily("NanumGothic") font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.button_add = QPushButton(self.centralwidget) self.button_add.setGeometry(QRect(MainWindow.size().width()*0.05, MainWindow.size().height() - 80, 131, 34)) #버튼 스타일 변경 self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_add.setFont(staticValues.buttonFont) self.button_modi = QPushButton(self.centralwidget) self.button_modi.setGeometry(QRect(MainWindow.size().width()*0.20, MainWindow.size().height() - 80, 131, 34)) self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_modi.setFont(staticValues.buttonFont) self.button_del = QPushButton(self.centralwidget) self.button_del.setGeometry(QRect(MainWindow.size().width()*0.35, MainWindow.size().height() - 80, 131, 34)) self.button_del.setStyleSheet(staticValues.redButtonStyleSheet) self.button_del.setFont(staticValues.buttonFont) self.button_upload = QPushButton(self.centralwidget) self.button_upload.setGeometry(QRect(MainWindow.size().width()*0.7, MainWindow.size().height() - 80, 131, 34)) self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_upload.setFont(staticValues.buttonFont) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QRect(10, 70, MainWindow.size().width()-15, MainWindow.size().height() - 180)) self.tab = QWidget() self.tab.layout = QVBoxLayout() self.tabWidget.addTab(self.tab, "회원 목록") self.tableWidget = QTableWidget(self.tab) self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25)) self.tableWidget.setColumnCount(13) self.tableWidget.setRowCount(0) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근" , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"]) self.tableWidget2 = QTableWidget(self.tab2) self.tableWidget2.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25)) self.tableWidget2.setColumnCount(3) self.tableWidget2.setRowCount(0) self.tableWidget2.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "현재 단톡방", "중복 단톡방"]) self.edit_search = QLineEdit(self.centralwidget) self.edit_search.setGeometry(QRect(MainWindow.size().width()-280, 35, 200, 30)) self.edit_search.setStyleSheet(staticValues.solidStyleSheet) self.button_search = QPushButton(self.centralwidget) self.button_search.setGeometry(QRect(MainWindow.size().width()-80, 35, 70, 30)) self.button_search.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_search.setFont(staticValues.buttonFont) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
class Main(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.onStart(choiceIndex) self.status = QStatusBar(self) self.custom = Customize() # Initializing the main widget where text is displayed self.tab = Tabs(self.openFile, app, palette) self.tabsOpen = [] self.pic_opened = False if file is not None: self.openFile(file) self.fileNameChange() self.dialog = MessageBox() self.pyConsoleOpened = None self.setWindowIcon(QIcon('resources/Python-logo-notext.svg_.png') ) # Setting the window icon self.setWindowTitle('PyPad') # Setting the window title self.tab.tabs.currentChanged.connect(self.fileNameChange) self.search = DocumentSearch() self.os = sys.platform self.openPy() self.openTerm() self.new() self.newProject() self.findDocument() self.openProjectF() self.open() self.save() self.saveAs() self.customize() self.exit() self.dir_opened = False self._dir = None # Without this, the whole layout is broken self.setCentralWidget(self.tab) self.newFileCount = 0 # Tracking how many new files are opened self.files = None # Tracking the current file that is open self.pyFileOpened = False # Tracking if python file is opened, this is useful to delete highlighting self.cFileOpened = False self.initUI() # Main UI def fileNameChange(self): try: currentFileName = self.tab.tabs.currentWidget().baseName self.setWindowTitle("PyPad ~ " + str(currentFileName)) except AttributeError: self.setWindowTitle("PyPad ~ ") def onStart(self, index): if index == 0: editor = config0['editor'] elif index == 1: editor = config1['editor'] elif index == 2: editor = config2['editor'] else: editor = config0['editor'] if editor["windowStaysOnTop"] is True: self.setWindowFlags(Qt.WindowStaysOnTopHint) else: pass self.font = QFont() self.font.setFamily(editor["editorFont"]) self.font.setPointSize(editor["editorFontSize"]) self.tabSize = editor["TabWidth"] def initUI(self): self.setStatusBar(self.status) # Initializing the status bar self.font.setFixedPitch(True) menuFont = QFont() menuFont.setFamily(editor["menuFont"]) menuFont.setPointSize(editor['menuFontSize']) menu = self.menuBar() menu.setFont(menuFont) # Creating the file menu fileMenu = menu.addMenu('File') # Adding options to the file menu # self.setStatusBar(self.status) fileMenu.addAction(self.newAct) fileMenu.addAction(self.newProjectAct) fileMenu.addAction(self.openAct) fileMenu.addAction(self.openProjectAct) fileMenu.addAction(self.saveAct) fileMenu.addAction(self.saveAsAct) fileMenu.addSeparator() fileMenu.addAction(self.exitAct) toolMenu = menu.addMenu('Tools') toolMenu.addAction(self.openPyAct) toolMenu.addAction(self.openTermAct) appearance = menu.addMenu('Appearance') appearance.addAction(self.colorSchemeAct) searchDoc = menu.addMenu('Find document') searchDoc.addAction(self.findDocumentAct) self.showMaximized() def open(self): self.openAct = QAction('Open...', self) self.openAct.setShortcut('Ctrl+O') self.openAct.setStatusTip('Open a file') self.openAct.triggered.connect(self.openFileFromMenu) def new(self): self.newAct = QAction('New') self.newAct.setShortcut('Ctrl+N') self.newAct.setStatusTip('Create a new file') self.newAct.triggered.connect(self.newFile) def newProject(self): self.newProjectAct = QAction('New project') self.newProjectAct.setShortcut('Ctrl+Shift+N') self.newProjectAct.setStatusTip('Create a new project') self.newProjectAct.triggered.connect(self.newProjectFolder) def openProjectF(self): self.openProjectAct = QAction('Open project') self.openProjectAct.setShortcut('Ctrl+Shift+O') self.openProjectAct.setStatusTip('Open a project') self.openProjectAct.triggered.connect(self.openProject) def customize(self): self.colorSchemeAct = QAction('Customize', self) self.colorSchemeAct.setShortcut('Alt+C') self.colorSchemeAct.setStatusTip('Select a color scheme') self.colorSchemeAct.triggered.connect(self.theme) def theme(self): self.custom.run() self.custom.selector.clicked.connect(self.custom.test) def save(self): self.saveAct = QAction('Save') self.saveAct.setShortcut('Ctrl+S') self.saveAct.setStatusTip('Save a file') self.saveAct.triggered.connect(self.saveFile) def openPy(self): self.openPyAct = QAction('IPython console', self) self.openPyAct.setShortcut('Ctrl+Y') self.openPyAct.setStatusTip('Open IPython console') self.openPyAct.triggered.connect(self.Console) def openTerm(self): self.openTermAct = QAction('Run', self) self.openTermAct.setShortcut('Shift+F10') self.openTermAct.setStatusTip('Run your code') self.openTermAct.triggered.connect(self.Terminal) def saveAs(self): self.saveAsAct = QAction('Save As...') self.saveAsAct.setShortcut('Ctrl+Shift+S') self.saveAsAct.setStatusTip('Save a file as') self.saveAsAct.triggered.connect(self.saveFileAs) def findDocument(self): self.findDocumentAct = QAction('Find document') self.findDocumentAct.setShortcut('Ctrl+Shift+F') self.findDocumentAct.setStatusTip('Find a document') self.findDocumentAct.triggered.connect(self.findDocumentFunc) def findDocumentFunc(self): self.search.run() def exit(self): self.exitAct = QAction('Quit', self) self.exitAct.setShortcut('Ctrl+Q') self.exitAct.setStatusTip('Exit application') self.exitAct.triggered.connect(qApp.quit) def openFileFromMenu(self): options = QFileDialog.Options() filenames, _ = QFileDialog.getOpenFileNames( self, 'Open a file', '', 'All Files (*);;Python Files (*.py);;Text Files (*.txt)', options=options) if filenames: # If file is selected, we can open it filename = filenames[0] if filename[-3:] in ['gif', 'png', 'jpg', 'bmp' ] or filename[-4:] in ['jpeg']: self.pic_opened = True self.openFile(filename) def openFile(self, filename): try: for index, tabName in enumerate(self.tab.tabCounter): with open(filename, 'r+') as file_o: if filename[-3:] in ['gif', 'png', 'jpg', 'bmp' ] or filename[-4:] in ['jpeg']: self.pic_opened = True else: self.pic_opened = False try: text = file_o.read() except UnicodeDecodeError as E: text = str(E) basename = os.path.basename(filename) if not self.pic_opened: tab = Content(text, filename, basename, self.custom.index, self, ex) tab.saved = True tab.modified = False else: tab = Image(filename, basename) if tabName == tab.baseName: self.tab.tabs.removeTab(index) self.tab.tabCounter.remove(tab.baseName) try: with open(filename, 'r+') as file_o: try: if self.pic_opened is not True: text = file_o.read() else: text = None except (FileNotFoundError, UnicodeDecodeError, AttributeError) as E: text = str(E) except FileNotFoundError: with open(filename, 'w+') as newFileCreated: text = newFileCreated.read() basename = os.path.basename(filename) if self.pic_opened is True: tab = Image(filename, basename) else: tab = Content(text, filename, basename, self.custom.index, self, ex) # Creating a tab object *IMPORTANT* tab.saved = True tab.modified = False self.tab.tabCounter.append(tab.baseName) dirPath = os.path.dirname(filename) self.files = filename self.tabsOpen.append(self.files) index = self.tab.tabs.addTab( tab, tab.fileName ) # This is the index which we will use to set the current if not self.dir_opened: # If a project isnt opened then we open a directory everytime we open a file self.tab.directory.openDirectory(dirPath) self.tab.showDirectory() else: pass self.tab.setLayout(self.tab.layout) # Finally we set the layout self.tab.tabs.setCurrentIndex( index) # Setting the index so we could find the current widget self.currentTab = self.tab.tabs.currentWidget() if self.pic_opened is not True: self.currentTab.editor.setFont(self.font) # Setting the font self.currentTab.editor.setTabStopWidth( self.tabSize) # Setting tab size self.currentTab.editor.setFocus( ) # Setting focus to the tab after we open it self.pic_opened = False except (IsADirectoryError, AttributeError, UnboundLocalError, PermissionError) as E: print(E) def newFile(self): text = "" if self._dir: fileName = str(self._dir) + "/" + "Untitled_file_" + str( random.randint(1, 100)) + ".py" else: current = os.getcwd() fileName = current + "/" + "Untitled_file_" + str( random.randint(1, 100)) + ".py" self.pyFileOpened = True # Creates a new blank file file = Content(text, fileName, fileName, self.custom.index, self, ex) self.tab.splitterH.addWidget( self.tab.tabs ) # Adding tabs, now the directory tree will be on the left self.tab.tabCounter.append(file.fileName) self.tab.setLayout(self.tab.layout) # Finally we set the layout index = self.tab.tabs.addTab( file, file.fileName ) # addTab method returns an index for the tab that was added self.tab.tabs.setCurrentIndex( index) # Setting focus to the new tab that we created widget = self.tab.tabs.currentWidget() widget.editor.setFocus() widget.editor.setFont(self.font) widget.editor.setTabStopWidth(self.tabSize) def newProjectFolder(self): self.dialog = MessageBox() self.dialog.newProject() def openProject(self): self._dir = QFileDialog.getExistingDirectory(None, 'Select a folder:', '', QFileDialog.ShowDirsOnly) self.tab.directory.openDirectory(self._dir) self.dir_opened = True self.tab.showDirectory() def saveFile(self): try: active_tab = self.tab.tabs.currentWidget() if self.tab.tabs.count(): # If a file is already opened with open(active_tab.fileName, 'w+') as saveFile: saveFile.write(active_tab.editor.toPlainText()) active_tab.saved = True active_tab.modified = False saveFile.close() active_tab.tokenize_file() else: options = QFileDialog.Options() name = QFileDialog.getSaveFileName( self, 'Save File', '', 'All Files (*);;Python Files (*.py);;Text Files (*.txt)', options=options) fileName = name[0] with open(fileName, "w+") as saveFile: active_tab.saved = True active_tab.modified = False self.tabsOpen.append(fileName) saveFile.write(active_tab.editor.toPlainText()) saveFile.close() ex.setWindowTitle("PyPad ~ " + str(active_tab.baseName) + " [SAVED]") active_tab.tokenize_file() except Exception as E: print(E) def saveFileAs(self): try: active_tab = self.tab.tabs.currentWidget() if active_tab is not None: active_index = self.tab.tabs.currentIndex() options = QFileDialog.Options() name = QFileDialog.getSaveFileName( self, 'Save File', '', 'All Files (*);;Python Files (*.py);;Text Files (*.txt)', options=options) fileName = name[0] with open(fileName, "w+") as saveFile: active_tab.saved = True active_tab.modified = False self.tabsOpen.append(fileName) try: baseName = os.path.basename(fileName) except AttributeError: print("All tabs closed") saveFile.write(active_tab.editor.toPlainText()) text = active_tab.editor.toPlainText() newTab = Content(str(text), fileName, baseName, self.custom.index, self, ex) self.tab.tabs.removeTab( active_index ) # When user changes the tab name we make sure we delete the old one index = self.tab.tabs.addTab( newTab, newTab.fileName) # And add the new one! self.tab.tabs.setCurrentIndex(index) newActiveTab = self.tab.tabs.currentWidget() newActiveTab.editor.setFont(self.font) newActiveTab.editor.setFocus() if fileName.endswith( ".py" ): # If we are dealing with a python file we use highlighting on it self.pyhighlighter = PyHighlighter( newActiveTab.editor.document(), index=self.custom.index) newActiveTab.editor.setTabStopWidth(self.tabSize) saveFile.close() ex.setWindowTitle("PyPad ~ " + str(active_tab.baseName) + " [SAVED]") else: print("No file opened") except FileNotFoundError: print("File dialog closed") def Console(self): self.pyConsoleOpened = True self.ind = self.tab.splitterV.indexOf(self.tab.term) self.o = self.tab.splitterV.indexOf(self.tab.Console) if self.tab.splitterV.indexOf( self.tab.Console ) == -1: # If the Console widget DOESNT EXIST YET! self.tab.splitterV.addWidget(self.tab.term) self.ind = self.tab.splitterV.indexOf(self.tab.term) if self.tab.splitterV.indexOf( self.tab.term ) == -1: # If the terminal widget doesnt exist yet self.tab.splitterV.replaceWidget(self.o, self.tab.term) self.o = self.tab.splitterV.indexOf(self.tab.Console) self.ind = self.tab.splitterV.indexOf(self.tab.term) def Terminal(self): active_tab = self.tab.tabs.currentWidget() if self.pyConsoleOpened: self.o = self.tab.splitterV.indexOf(self.tab.Console) self.ind = self.tab.splitterV.indexOf(self.tab.term) if self.ind == -1: if platform.system() == "Linux": self.tab.Console.run("python3 " + active_tab.fileName) elif platform.system() == "Windows": self.tab.Console.run("python " + active_tab.fileName) else: self.tab.Console.run("python3 " + active_tab.fileName) else: self.tab.splitterV.replaceWidget(self.ind, self.tab.Console) try: if platform.system() == "Linux": self.tab.Console.run("python3 " + active_tab.fileName) elif platform.system() == "Windows": self.tab.Console.run("python " + active_tab.fileName) else: self.tab.Console.run("python3 " + active_tab.fileName) except AttributeError as E: print(E) else: self.tab.splitterV.addWidget(self.tab.Console) try: active_tab = self.tab.tabs.currentWidget() if platform.system() == "Linux": self.tab.Console.run("python3 " + active_tab.fileName) elif platform.system() == "Windows": self.tab.Console.run("python " + active_tab.fileName) else: self.tab.Console.run("python3 " + active_tab.fileName) except AttributeError as E: print(E)
def load(self, path: str, is_first_call: bool = True) -> None: if path == self._path: return theme_full_path = os.path.join(path, "theme.json") Logger.log( "d", "Loading theme file: {theme_full_path}".format( theme_full_path=theme_full_path)) try: with open(theme_full_path, encoding="utf-8") as f: data = json.load(f) except EnvironmentError as e: Logger.error( "Unable to load theme file at {theme_full_path}: {err}".format( theme_full_path=theme_full_path, err=e)) return except UnicodeDecodeError: Logger.error( "Theme file at {theme_full_path} is corrupt (invalid UTF-8 bytes)." .format(theme_full_path=theme_full_path)) return except json.JSONDecodeError: Logger.error( "Theme file at {theme_full_path} is corrupt (invalid JSON syntax)." .format(theme_full_path=theme_full_path)) return # Iteratively load inherited themes try: theme_id = data["metadata"]["inherits"] self.load(Resources.getPath(Resources.Themes, theme_id), is_first_call=False) except FileNotFoundError: Logger.log("e", "Could not find inherited theme %s", theme_id) except KeyError: pass # No metadata or no inherits keyword in the theme.json file if "colors" in data: for name, color in data["colors"].items(): try: c = QColor(color[0], color[1], color[2], color[3]) except IndexError: # Color doesn't have enough components. Logger.log( "w", "Colour {name} doesn't have enough components. Need to have 4, but had {num_components}." .format(name=name, num_components=len(color))) continue # Skip this one then. self._colors[name] = c fonts_dir = os.path.join(path, "fonts") if os.path.isdir(fonts_dir): for root, dirnames, filenames in os.walk(fonts_dir): for filename in filenames: if filename.lower().endswith(".ttf"): QFontDatabase.addApplicationFont( os.path.join(root, filename)) if "fonts" in data: system_font_size = QCoreApplication.instance().font().pointSize() for name, font in data["fonts"].items(): q_font = QFont() q_font.setFamily( font.get("family", QCoreApplication.instance().font().family())) if font.get("bold"): q_font.setBold(font.get("bold", False)) else: q_font.setWeight(font.get("weight", 50)) q_font.setLetterSpacing(QFont.AbsoluteSpacing, font.get("letterSpacing", 0)) q_font.setItalic(font.get("italic", False)) q_font.setPointSize(int( font.get("size", 1) * system_font_size)) q_font.setCapitalization(QFont.AllUppercase if font.get( "capitalize", False) else QFont.MixedCase) self._fonts[name] = q_font if "sizes" in data: for name, size in data["sizes"].items(): s = QSizeF() s.setWidth(round(size[0] * self._em_width)) s.setHeight(round(size[1] * self._em_height)) self._sizes[name] = s iconsdir = os.path.join(path, "icons") if os.path.isdir(iconsdir): for icon in os.listdir(iconsdir): name = os.path.splitext(icon)[0] self._icons[name] = QUrl.fromLocalFile( os.path.join(iconsdir, icon)) imagesdir = os.path.join(path, "images") if os.path.isdir(imagesdir): for image in os.listdir(imagesdir): name = os.path.splitext(image)[0] self._images[name] = QUrl.fromLocalFile( os.path.join(imagesdir, image)) styles = os.path.join(path, "styles.qml") if os.path.isfile(styles): c = QQmlComponent(self._engine, styles) context = QQmlContext(self._engine, self._engine) context.setContextProperty("Theme", self) self._styles = c.create(context) if c.isError(): for error in c.errors(): Logger.log("e", error.toString()) Logger.log("d", "Loaded theme %s", path) self._path = path # only emit the theme loaded signal once after all the themes in the inheritance chain have been loaded if is_first_call: self.themeLoaded.emit()
class GuiDocDetails(QFrame): C_NAME = 0 C_COUNT = 1 C_FLAGS = 2 C_HANDLE = 3 def __init__(self, theParent, theProject): QFrame.__init__(self, theParent) logger.debug("Initialising DocDetails ...") self.mainConf = nw.CONFIG self.debugGUI = self.mainConf.debugGUI self.theParent = theParent self.theProject = theProject self.mainBox = QGridLayout(self) self.mainBox.setVerticalSpacing(1) self.mainBox.setHorizontalSpacing(15) self.setLayout(self.mainBox) self.fntOne = QFont() self.fntOne.setPointSize(10) self.fntOne.setBold(True) self.fntTwo = QFont() self.fntTwo.setPointSize(10) self.colTwo = [QLabel(""), QLabel(""), QLabel(""), QLabel("")] colOne = ["Name", "Status", "Class", "Layout"] for nRow in range(4): lblOne = QLabel(colOne[nRow]) lblOne.setFont(self.fntOne) self.mainBox.addWidget(lblOne, nRow, 0) self.mainBox.addWidget(self.colTwo[nRow], nRow, 1) self.mainBox.setColumnStretch(0, 0) self.mainBox.setColumnStretch(1, 1) logger.debug("DocDetails initialisation complete") return def buildViewBox(self, tHandle): nwItem = self.theProject.getItem(tHandle) if nwItem is None: colTwo = [""] * 4 else: colTwo = [ nwItem.itemName, nwItem.itemStatus, nwLabels.CLASS_NAME[nwItem.itemClass], nwLabels.LAYOUT_NAME[nwItem.itemLayout], ] for nRow in range(4): self.colTwo[nRow].setText(colTwo[nRow]) return
class Ui_MainWindow(object): ARROW_MARKER_NUM = 8 def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(640, 480) self.vindu = QtWidgets.QWidget(MainWindow) self.vindu.setStyleSheet(_fromUtf8('notusedasyet')) #MainWindow.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.filename = "" self.vindu.setObjectName(_fromUtf8("vindu")) self.verticalLayout = PyQt5.QtWidgets.QVBoxLayout(self.vindu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/ico/python.png")), QtGui.QIcon.Normal, QtGui.QIcon.On) MainWindow.setWindowIcon(icon) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName(_fromUtf8('verticalLayout')) self.codebox = Qsci.QsciScintilla(self.vindu) self.codebox.setToolTip(_fromUtf8("")) self.codebox.setWhatsThis(_fromUtf8("")) self.codebox.setAutoFillBackground(False) self.codebox.setFrameShape(QtWidgets.QFrame.NoFrame) self.codebox.setObjectName(_fromUtf8("codebox")) self.verticalLayout.addWidget(self.codebox) MainWindow.setCentralWidget(self.vindu) #toolbar self.toolBar = QtWidgets.QToolBar(MainWindow) self.toolBar.setAutoFillBackground(False) self.toolBar.setIconSize(QtCore.QSize(32, 32)) self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.toolBar.setObjectName(_fromUtf8("toolBar2")) MainWindow.addToolBar(QtCore.Qt.LeftToolBarArea, self.toolBar) self.toolBar.addSeparator() #toolbar2 debugger #self.toolBar2 = QtGui.QToolBar(MainWindow) #self.toolBar2.setAutoFillBackground(False) #self.toolBar2.setIconSize(QtCore.QSize(32, 32)) #self.toolBar2.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) #self.toolBar2.setObjectName(_fromUtf8("toolBar")) # MainWindow.addToolBar(QtCore.Qt.RightToolBarArea, self.toolBar2) # self.toolBar2.addSeparator() #getting ready for debugger self.codebox.setMarginSensitivity(1, True) self.codebox.marginClicked.connect(self.on_margin_clicked) self.codebox.markerDefine(QsciScintilla.FullRectangle, self.ARROW_MARKER_NUM) self.codebox.setMarkerBackgroundColor(QColor("#ee1111"), self.ARROW_MARKER_NUM) #first action Newfile self.toolBar.newAction = QtWidgets.QAction( QtGui.QIcon(":/ico/new.png"), "New", self.toolBar) self.toolBar.newAction.setStatusTip( "Clear TextBox or make new document.") self.toolBar.newAction.setShortcut("Ctrl+N") self.toolBar.newAction.triggered.connect(self.newfile) #second Action OpenFile self.toolBar.secondAction = QtWidgets.QAction( QtGui.QIcon(":/ico/open.png"), "Open", self.toolBar) self.toolBar.secondAction.setStatusTip( "Create a new document from scratch.") self.toolBar.secondAction.setShortcut("Ctrl+O") self.toolBar.secondAction.triggered.connect(self.open) # action 3 save file self.toolBar.Action3 = QtWidgets.QAction(QtGui.QIcon(":/ico/save.png"), "Save", self.toolBar) self.toolBar.Action3.setStatusTip("Save Your File.") self.toolBar.Action3.setShortcut("Ctrl+S") self.toolBar.Action3.triggered.connect(self.savefile) #action 4 run file self.toolBar.Action4 = QtWidgets.QAction( QtGui.QIcon(":/ico/run32.png"), "Run", self.toolBar) self.toolBar.Action4.setStatusTip("Run") self.toolBar.Action4.setShortcut("Ctrl+E") self.toolBar.Action4.triggered.connect(self.runto) #action 21 debug #self.toolBar2.Action21 = QtGui.QAction(QtGui.QIcon(":/ico/run32.png"),"Debug",self.toolBar) #self.toolBar2.Action21.setStatusTip("Debug File.") #self.toolBar2.Action21.setShortcut("Ctrl+7") #self.toolBar2.Action21.triggered.connect(self.debugto) #action 6 undo self.toolBar.Action6 = QtWidgets.QAction(QtGui.QIcon(":/ico/undo.png"), "Redo", self.toolBar) self.toolBar.Action6.setStatusTip("Undo.") self.toolBar.Action6.setShortcut("Ctrl+Z") self.toolBar.Action6.triggered.connect(self.codebox.undo) #action 7 redo self.toolBar.Action7 = QtWidgets.QAction(QtGui.QIcon(":/ico/redo.png"), "Redo", self.toolBar) self.toolBar.Action7.setStatusTip("Redo.") self.toolBar.Action7.setShortcut("Ctrl+Y") self.toolBar.Action7.triggered.connect(self.codebox.redo) #action8 rerset Folding self.toolBar.Action8 = QtWidgets.QAction( QtGui.QIcon(":/ico/align-justify.png"), "Reset Folding", self.toolBar) self.toolBar.Action8.setStatusTip("Reset Folding.") self.toolBar.Action8.setShortcut("Ctrl+R") self.toolBar.Action8.triggered.connect(self.nofoldingl) #actions9 CircledTreeFoldStyle self.toolBar.Action9 = QtWidgets.QAction( QtGui.QIcon(":/ico/bullet.png"), "Circled Tree Folding", self.toolBar) self.toolBar.Action9.setStatusTip("Circled Tree Folding.") self.toolBar.Action9.setShortcut("Ctrl+C") self.toolBar.Action9.triggered.connect(self.Circledfold) #actions10 plainFoldStyle self.toolBar.Action10 = QtWidgets.QAction( QtGui.QIcon(":/ico/number.png"), "Plain Folding", self.toolBar) self.toolBar.Action10.setStatusTip("Plain Folding") self.toolBar.Action10.setShortcut("Ctrl+P") self.toolBar.Action10.triggered.connect(self.plainfold) # fonts self.toolBar.Action21 = QtWidgets.QAction( QtGui.QIcon(":/ico4/font.png"), "Fonts", self.toolBar) self.toolBar.Action21.setStatusTip("Fonts") self.toolBar.Action21.setShortcut("Ctrl+F") self.toolBar.Action21.triggered.connect(self.font_choice) #web baby self.toolBar.Action11 = QtWidgets.QAction(QtGui.QIcon(":/ico/web.png"), "Hex-rays Homepage", self.toolBar) self.toolBar.Action11.setStatusTip("Home of Hex-rays") self.toolBar.Action11.setShortcut("Ctrl+W") self.toolBar.Action11.triggered.connect(self.webopen) #irc self.toolBar.Action12 = QtWidgets.QAction( QtGui.QIcon(":/ico3/settings.png"), "Open Ida Pro Python SDK", self.toolBar) self.toolBar.Action12.setStatusTip("Ida Pro Python SDK") self.toolBar.Action12.setShortcut("Ctrl+I") self.toolBar.Action12.triggered.connect(self.sdkopen) #github Python self.toolBar.Action14 = QtWidgets.QAction( QtGui.QIcon(":/ico/github.png"), "Open git python", self.toolBar) self.toolBar.Action14.setStatusTip("Open git python") self.toolBar.Action14.setShortcut("Ctrl+G") self.toolBar.Action14.triggered.connect(self.gitopen) #auther me :) self.toolBar.Action15 = QtWidgets.QAction( QtGui.QIcon(":/ico/auth.png"), "Author", self.toolBar) self.toolBar.Action15.setStatusTip("Author") self.toolBar.Action15.setShortcut("Ctrl+B") self.toolBar.Action15.triggered.connect(self.Author) #toggle off code regonision self.toolBar.Action16 = QtWidgets.QAction( QtGui.QIcon(":/ico2/pythonminus.png"), "Disable Code recognition", self.toolBar) self.toolBar.Action16.setStatusTip("Disable Code recognition") self.toolBar.Action16.setShortcut("Alt+D") self.toolBar.Action16.triggered.connect(self.Diablecode) #toogle on self.toolBar.Action17 = QtWidgets.QAction( QtGui.QIcon(":/ico2/pypluss.png"), "Enable Code recognition", self.toolBar) self.toolBar.Action17.setStatusTip("Enable Code recognition") self.toolBar.Action17.setShortcut("Alt+E") self.toolBar.Action17.triggered.connect(self.Reiablecode) # zoom in self.toolBar.Action18 = QtWidgets.QAction(QtGui.QIcon(":/ico3/in.png"), "Zoom In", self.toolBar) self.toolBar.Action18.setStatusTip("Zoom In") self.toolBar.Action18.setShortcut("CTRL+SHIFT++") self.toolBar.Action18.triggered.connect(self.udder) #zoom out self.toolBar.Action19 = QtWidgets.QAction( QtGui.QIcon(":/ico3/out.png"), "Zoom Out", self.toolBar) self.toolBar.Action19.setStatusTip("Zoom Out") self.toolBar.Action19.setShortcut("CTRL+SHIFT+-") self.toolBar.Action19.triggered.connect(self.odder) self.toolBar.Action20 = QtWidgets.QAction(QtGui.QIcon(":/ico3/10.png"), "Profile Code", self.toolBar) self.toolBar.Action20.setStatusTip("Profile Code") self.toolBar.Action20.setShortcut("CTRL+SHIFT+E") self.toolBar.Action20.triggered.connect(self.runtoprob) #actions self.toolBar.addAction(self.toolBar.newAction) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.secondAction) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action3) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action4) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action6) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action7) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action8) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action9) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action10) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action21) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action11) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action12) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action14) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action15) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action16) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action17) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action18) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action19) self.toolBar.addSeparator() self.toolBar.addAction(self.toolBar.Action20) #self.toolBar2.addAction(self.toolBar.Action21) #self.toolBar2.addSeparator() #font self.skrift = QFont() self.skrift.setFamily('Consolas') self.skrift.setFixedPitch(True) self.skrift.setPointSize(12) self.codebox.setFont(self.skrift) #python style self.lexer = QsciLexerPython(self.codebox) self.lexer.setFont(self.skrift) self.lexer.setEolFill(True) #api test not working api = Qsci.QsciAPIs(self.lexer) API_FILE = dn + '\\Python.api' API_FILE2 = dn + '\\idc.api' API_FILE3 = dn + '\\idaapi.api' api.load(API_FILE) api.load(API_FILE2) api.load(API_FILE3) api.prepare() self.codebox.setAutoCompletionThreshold(0) self.codebox.setAutoCompletionThreshold(6) self.codebox.setAutoCompletionThreshold(8) self.codebox.setAutoCompletionSource(Qsci.QsciScintilla.AcsAPIs) self.lexer.setDefaultFont(self.skrift) self.codebox.setLexer(self.lexer) self.codebox.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Consolas') #line numbers fontmetrics = QFontMetrics(self.skrift) self.codebox.setMarginsFont(self.skrift) self.codebox.setMarginWidth(0, fontmetrics.width("00000") + 6) self.codebox.setTabWidth(4) #brace self.codebox.setBraceMatching(QsciScintilla.SloppyBraceMatch) #auto line tab =4 self.codebox.setAutoIndent(True) #scroolbar self.codebox.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 1) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle( _translate("MainWindow", "Ida Pro Python Script Editor", None)) self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None)) def udder(self): self.codebox.zoomIn() def odder(self): self.codebox.zoomOut() def newfile(self): self.codebox.clear() def open(self): self.path = QtCore.QFileInfo(self.filename).path() # Get filename and show only .writer files (self.filename, _) = \ QtWidgets.QFileDialog.getOpenFileName(self.vindu, 'Open File', self.path, 'Python Files (*.py *.pyc *.pyw)', '') if self.filename: with open(self.filename, 'r') as self.file: self.codebox.setText(self.file.read()) os.chdir(str(self.path)) def savefile(self): self.path = QtCore.QFileInfo(self.filename).path() (self.filename, _) = \ QtWidgets.QFileDialog.getSaveFileName(self.vindu, 'Save as' , self.path, 'Python Files (*.py *.pyc *.pyw)') if self.filename: self.savetext(self.filename) os.chdir(str(self.path)) def savetext(self, fileName): textout = self.codebox.text() file = QtCore.QFile(fileName) if file.open(QtCore.QIODevice.WriteOnly): QtCore.QTextStream(file) << textout else: QtWidgets.QMessageBox.information(self.vindu, 'Unable to open file', file.errorString()) os.chdir(str(self.path)) def runto(self): self.path = QtCore.QFileInfo(self.filename).path() g = globals() os.chdir(str(self.path)) script = str(self.codebox.text()) try: os.chdir(str(self.path)) os.path.join(os.path.expanduser('~'), os.path.expandvars(str(self.path))) sys.path.insert(0, str(self.path)) exec(script, g) except Exception as e: print e.__doc__ print e.message else: exec(script, g) def runtoprob(self): try: self.path = QtCore.QFileInfo(self.filename).path() self.path = QtCore.QFileInfo(self.filename).path() g = globals() os.chdir(str(self.path)) script = str(self.codebox.text()) import cProfile cProfile.run(script) except Exception as e: print e.__doc__ print e.message else: import cProfile cProfile.run(script) def Diablecode(self): self.codebox.setAutoCompletionSource(Qsci.QsciScintilla.AcsNone) def Reiablecode(self): self.codebox.setAutoCompletionSource(Qsci.QsciScintilla.AcsAPIs) def nofoldingl(self): self.codebox.setFolding(QsciScintilla.NoFoldStyle) def Circledfold(self): self.codebox.setFolding(QsciScintilla.CircledTreeFoldStyle) def plainfold(self): self.codebox.setFolding(QsciScintilla.PlainFoldStyle) def webopen(self): import webbrowser webbrowser.open('https://www.hex-rays.com/') def sdkopen(self): import webbrowser webbrowser.open( 'https://www.hex-rays.com/products/ida/support/idapython_docs/') def gitopen(self): import webbrowser webbrowser.open('https://github.com/idapython/src/tree/build-1.7.2') def Author(self): import webbrowser webbrowser.open('https://github.com/techbliss') def font_choice(self): self.lbl = self.lexer font, ok = QtWidgets.QFontDialog.getFont() if ok: self.lbl.setFont(font) def on_margin_clicked(self, nmargin, nline, modifiers): # Toggle marker for the line the margin was clicked on if self.codebox.markersAtLine(nline) != 0: self.codebox.markerDelete(nline, self.ARROW_MARKER_NUM) else: self.codebox.markerAdd(nline, self.ARROW_MARKER_NUM)
def setupUi(self, Widget): Widget.setObjectName("Widget") Widget.resize(1013, 772) Widget.setMinimumSize(QSize(492, 522)) Widget.setMaximumSize(QSize(1076, 845)) Widget.setStyleSheet("*{\n" "font-size:24px;\n" "font-family:Century Gothic;\n" "}\n" "#Widget{ \n" "background: url(:/resources/background.jpg)\n" "}\n" "QFrame{\n" "background:rgba(0,0,0,0.8);\n" "border-radius:15px;\n" "}\n" "\n" "QToolButton{\n" "background:#49ebff;\n" "border-radius:60px;\n" "}\n" "QLabel{\n" "color:white;\n" "background:transparent;\n" "}\n" "QPushButton{\n" "background:#49ebff;\n" "border-radius:15px;\n" "}\n" "QPushButton:hover{\n" "background:white;\n" "border-radius:15px;\n" "\n" "}\n" "QLineEdit{\n" "background:transparent;\n" "border:none;\n" "color:#717072;\n" "border-bottom:1px solid #717072;\n" "}\n" "\n" "QPushLabel:hover{\n" "background:red;\n" "border-radius:15px;\n" "\n" "}") self.frame = QFrame(Widget) self.frame.setGeometry(QRect(240, 120, 491, 521)) self.frame.setStyleSheet("Frame{hiden();}") self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.frame.setObjectName("frame") self.label = QLabel(self.frame) self.label.setGeometry(QRect(160, 70, 161, 61)) self.label.setObjectName("label") self.pushButton = QPushButton(self.frame) self.pushButton.setGeometry(QRect(80, 420, 321, 41)) self.pushButton.setStyleSheet( "font: 75 14pt \"Adobe Garamond Pro Bold\";\n" "") self.pushButton.setObjectName("pushButton") self.lineEdit = QLineEdit(self.frame) self.lineEdit.setGeometry(QRect(70, 190, 351, 41)) self.lineEdit.setText("") self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QLineEdit(self.frame) self.lineEdit_2.setGeometry(QRect(70, 280, 351, 41)) self.lineEdit_2.setText("") self.lineEdit_2.setEchoMode(QLineEdit.Password) self.lineEdit_2.setObjectName("lineEdit_2") self.label_2 = ClickLabel.ClickLabel(self.frame) self.label_2.setGeometry(QRect(90, 340, 91, 31)) font = QFont() font.setFamily("Adobe Garamond Pro Bold") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(9) self.label_2.setFont(font) self.label_2.setStyleSheet( "color: rgb(53, 228, 255);\n" "selection-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));\n" "\n" "font: 75 12pt \"Adobe Garamond Pro Bold\";\n" "") self.label_2.setObjectName("label_2") self.label_3 = ClickLabel.ClickLabel(self.frame) self.label_3.setGeometry(QRect(310, 340, 91, 31)) font = QFont() font.setFamily("Adobe Garamond Pro Bold") font.setPointSize(12) font.setBold(False) font.setItalic(False) font.setWeight(9) self.label_3.setFont(font) self.label_3.setStyleSheet( "color: rgb(53, 228, 255);\n" "\n" "font: 75 12pt \"Adobe Garamond Pro Bold\";\n" "") self.label_3.setObjectName("label_3") self.toolButton = QToolButton(Widget) self.toolButton.setGeometry(QRect(420, 40, 131, 121)) self.toolButton.setText("") icon = QIcon() icon.addPixmap(QPixmap(":/resources/people.png"), QIcon.Normal, QIcon.Off) self.toolButton.setIcon(icon) self.toolButton.setIconSize(QSize(64, 64)) self.toolButton.setObjectName("toolButton") self.retranslateUi(Widget) QMetaObject.connectSlotsByName(Widget)
def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.setWindowIcon(QIcon(App.resource_path("AGH.png"))) self.file = "LABIRYNT.png" self.label = QLabel(self) self.label.setGeometry(QRect(140, 42, 760, 60)) font = QFont() font.setPointSize(28) font.setBold(True) font.setWeight(50) self.label.setFont(font) self.label.setText("Symulator pokonywania labiryntu") self.image = QLabel(self) self.image.setGeometry(QRect(20, 20, 100, 100)) pixmap = QPixmap(App.resource_path('AGH.png')) pixmap = pixmap.scaledToHeight(100) self.image.setPixmap(pixmap) self.groupBox_generator = QGroupBox(self) self.groupBox_generator.setGeometry(QRect(42, 140, 410, 155)) self.groupBox_generator.setTitle("Generator labiryntu:") self.textBrowser_wall_thick = QLineEdit(self.groupBox_generator) self.textBrowser_wall_thick.setGeometry(QRect(10,30, 160, 30)) self.textBrowser_wall_thick.setPlaceholderText("grubosc scianki [mm]") self.textBrowser_wall_dimension = QLineEdit(self.groupBox_generator) self.textBrowser_wall_dimension.setGeometry(QRect(180,30, 220, 30)) self.textBrowser_wall_dimension.setPlaceholderText("odleglosc miedzy sciankami [mm]") self.textBrowser_x_number = QLineEdit(self.groupBox_generator) self.textBrowser_x_number.setGeometry(QRect(10,70, 390, 30)) self.textBrowser_x_number.setPlaceholderText("ilosc pol poziomo i pionowo") self.pushButton_load_directory = QPushButton(self.groupBox_generator) self.pushButton_load_directory.setGeometry(QRect(220, 110, 70, 30)) self.pushButton_load_directory.setText("Wybierz") self.pushButton_load_directory.clicked.connect(self.set_directory) self.textBrowser_load_directory = QTextBrowser(self.groupBox_generator) self.textBrowser_load_directory.setGeometry(QRect(10, 110, 200, 30)) self.textBrowser_load_directory.setPlaceholderText("lokalizacja pliku") self.pushButton_load_dwg = QPushButton(self.groupBox_generator) self.pushButton_load_dwg.setGeometry(QRect(220, 110, 70, 30)) self.pushButton_load_dwg.setText("Wybierz") self.pushButton_load_dwg.clicked.connect(self.set_directory) self.pushButton_genr = QPushButton(self.groupBox_generator) self.pushButton_genr.setGeometry(QRect(300, 110, 100, 30)) self.pushButton_genr.setText("generuj") self.pushButton_genr.clicked.connect(self.connect_to_maze) self.groupBox_generator_map= QGroupBox(self) self.groupBox_generator_map.setGeometry(QRect(42, 310, 410, 145)) self.groupBox_generator_map.setTitle("Generator mapowania:") self.textBrowser_precision = QLineEdit(self.groupBox_generator_map) self.textBrowser_precision.setGeometry(QRect(10,30, 160, 30)) self.textBrowser_precision.setPlaceholderText("dokladnosc [mm]") self.checkBox_map01 = QCheckBox(self.groupBox_generator_map) self.checkBox_map01.setGeometry(QRect(10, 70, 170, 20)) self.checkBox_map01.setText("mapowanie obszaru 0/1") self.checkBox_pos_txt = QCheckBox(self.groupBox_generator_map) self.checkBox_pos_txt.setGeometry(QRect(190, 70, 180, 20)) self.checkBox_pos_txt.setText("pozycje przeszkod [mm]") self.label = QLabel(self.groupBox_generator_map) self.label.setGeometry(QRect(180, 15, 760, 60)) self.label.setText("mininalna dokladnosc - 1 mm") self.pushButton_load_directory_map = QPushButton(self.groupBox_generator_map) self.pushButton_load_directory_map.setGeometry(QRect(220, 100, 70, 30)) self.pushButton_load_directory_map.setText("Wybierz") self.pushButton_load_directory_map.clicked.connect(self.set_directory_map) self.pushButton_load_directory_map = QTextBrowser(self.groupBox_generator_map) self.pushButton_load_directory_map.setGeometry(QRect(10, 100, 200, 30)) self.pushButton_load_directory_map.setPlaceholderText("lokalizacja pliku") self.pushButton_genr = QPushButton(self.groupBox_generator_map) self.pushButton_genr.setGeometry(QRect(300, 100, 100, 30)) self.pushButton_genr.setText("generuj") self.pushButton_genr.clicked.connect(self.connect_to_mapping) self.groupBox_manual = QGroupBox(self) self.groupBox_manual.setGeometry(QRect(42, 470, 410, 70)) self.groupBox_manual.setTitle("Tryb Manualny:") self.label = QLabel(self.groupBox_manual) self.label.setGeometry(QRect(10, 15, 80, 60)) self.label.setText("Predkosc:") self.slider_speed = QSlider(Qt.Horizontal, self.groupBox_manual) self.slider_speed.setGeometry(QRect(80, 31, 230, 30)) self.slider_speed.setRange(2, 12) self.start = QPushButton(self.groupBox_manual) self.start.setGeometry(QRect(320, 31, 80, 30)) self.start.setText("start") self.start.clicked.connect(self.connect_to_play) self.image = QLabel(self) self.image.setGeometry(QRect(480, 160, 380, 380)) self.pixmap = QPixmap(App.resource_path(self.file)) self.pixmap = self.pixmap.scaledToHeight(380) self.image.setPixmap(self.pixmap) self.groupBox_automat= QGroupBox(self) self.groupBox_automat.setGeometry(QRect(42, 550, 820, 70)) self.groupBox_automat.setTitle("Tryb automatyczny z Arduino:") self.label = QLabel(self.groupBox_automat) self.label.setGeometry(QRect(10, 15, 80, 60)) self.label.setText("Predkosc:") self.slider_speed_automat = QSlider(Qt.Horizontal, self.groupBox_automat) self.slider_speed_automat.setGeometry(QRect(80, 31, 230, 30)) self.slider_speed_automat.setRange(2, 12) self.textBrowser_port = QLineEdit(self.groupBox_automat) self.textBrowser_port.setGeometry(QRect(320 ,30, 100, 30)) self.textBrowser_port.setPlaceholderText("port szeregowy") self.textBrowser_port = QLineEdit(self.groupBox_automat) self.textBrowser_port.setGeometry(QRect(320 ,30, 120, 30)) self.textBrowser_port.setPlaceholderText("port szeregowy") self.textBrowser_baud_rate = QLineEdit(self.groupBox_automat) self.textBrowser_baud_rate.setGeometry(QRect(450 ,30, 210, 30)) self.textBrowser_baud_rate.setPlaceholderText("predkosc transmisji") self.start_automat = QPushButton(self.groupBox_automat) self.start_automat.setGeometry(QRect(680, 31, 120, 30)) self.start_automat.setText("start") self.start_automat.clicked.connect(self.connect_to_automatic) self.show()
def initui(self): palette = QPalette() palette.setColor(QPalette.Background, QColor(100, 100, 100)) # ************ Header ************ # ------------ Frame ---------- frame = QFrame(self) frame.setFrameShape(QFrame.NoFrame) frame.setFrameShadow(QFrame.Sunken) frame.setAutoFillBackground(True) frame.setPalette(palette) frame.setFixedWidth(800) frame.setFixedHeight(84) frame.move(0, 0) # ------------ Icon ---------- label_icon = QLabel(frame) label_icon.setFixedWidth(40) label_icon.setFixedHeight(40) label_icon.setPixmap( QPixmap("./images/LoginIcon.png").scaled(40, 40, Qt.KeepAspectRatio, Qt.SmoothTransformation)) label_icon.move(57, 22) # ------------ Tittle ---------- tittle_font = QFont() tittle_font.setPixelSize(16) tittle_font.setBold(True) tittle_label = QLabel("<font color='white'> Ariadna </rfont>", frame) tittle_label.setFont(tittle_font) tittle_label.move(103, 20) # ------------ Sub Tittle ---------- sub_tittle_font = QFont() sub_tittle_font.setPointSize(9) sub_tittle_label = QLabel( "<font color='white'> Labyrinth Solver </font>", frame) sub_tittle_label.setFont(sub_tittle_font) sub_tittle_label.move(111, 46) # ************ Body ************ # ------------ Labyrinth Frame ---------- labyrinth_frame = QFrame(self) labyrinth_frame.setFrameShape(QFrame.NoFrame) labyrinth_frame.setFrameShadow(QFrame.Sunken) labyrinth_frame.setAutoFillBackground(False) labyrinth_frame.setPalette(palette) labyrinth_frame.setFixedWidth(800) labyrinth_frame.setFixedHeight(500) labyrinth_frame.move(0, 150) # ------------ Labyrinth ---------- self.labyrinth_label = QLabel("", labyrinth_frame) self.labyrinth_label.setPixmap(QPixmap("./images/AriadnaFile.jpg")) self.labyrinth_label.setFixedWidth(420) self.labyrinth_label.setFixedHeight(280) self.labyrinth_label.setScaledContents(True) self.labyrinth_label.move(200, 100) # ---------- Buttons ---------- load_labyrinth_button = QPushButton("Cargar Laberinto", self) load_labyrinth_button.setFixedWidth(175) load_labyrinth_button.setFixedHeight(28) load_labyrinth_button.move(60, 90) solve_labyrinth_button = QPushButton("Solucionar Laberinto", self) solve_labyrinth_button.setFixedWidth(175) solve_labyrinth_button.setFixedHeight(28) solve_labyrinth_button.move(315, 90) save_labyrinth_button = QPushButton("Guardar Laberinto", self) save_labyrinth_button.setFixedWidth(175) save_labyrinth_button.setFixedHeight(28) save_labyrinth_button.move(565, 90) back_main_menu_button = QPushButton("Menu Principal", self) back_main_menu_button.setFixedWidth(175) back_main_menu_button.setFixedHeight(28) back_main_menu_button.move(320, 680) # ---------- Button's Events ---------- load_labyrinth_button.clicked.connect(self.load_labyrinth) solve_labyrinth_button.clicked.connect(self.solve_labyrinth) save_labyrinth_button.clicked.connect(self.save_labyrinth) back_main_menu_button.clicked.connect(self.back_main_menu)
class form_renovar(QWidget): def __init__(self, username, codigo): # Inicialización de la ventana super().__init__() self.setWindowTitle("Renovar Contraseña") self.setWindowIcon(QIcon("static/icono_CEIC.png")) self.setStyleSheet('background-color: rgb(236, 240, 241)') self.setFixedSize(380, 220) paleta = QPalette() paleta.setColor(QPalette.Background, QColor(243, 243, 243)) self.setPalette(paleta) self.fuente = QFont() self.fuente.setPointSize(10) self.fuente.setFamily("Bahnschrift Light") self.fuenteCode = QFont() self.fuenteCode.setPointSize(15) self.fuenteCode.setFamily("Bahnschrift Light") self.labelInfo = QLabel( "Se envió un codigo de verificación al correo\n de la cuenta del Usuario\n", self) self.labelInfo.move(25, 40) self.labelInfo.setFont(self.fuente) self.labelInfo.setStyleSheet("text-align: justify; color: #575757;") self.code = QLineEdit(self) self.code.setFrame(False) self.code.setTextMargins(8, 0, 4, 1) self.code.setStyleSheet( "QLineEdit\n{\n border: 1px solid #C9C9C9;\n border-radius: 3px;\n background-color: white;\n}" ) self.code.setFixedWidth(238) self.code.setFixedHeight(50) self.code.move(72, 120) self.code.setFont(self.fuenteCode) self.repeat_password = QLineEdit(self) self.repeat_password.setFrame(False) self.repeat_password.setTextMargins(8, 0, 4, 1) self.repeat_password.setStyleSheet( "QLineEdit\n{\n border: 1px solid #C9C9C9;\n border-radius: 3px;\n background-color: white;\n}" ) self.repeat_password.setFixedWidth(238) self.repeat_password.setFixedHeight(40) self.repeat_password.setPlaceholderText("Repetir Contraseña") self.repeat_password.move(72, 300) self.repeat_password.setFont(self.fuenteCode) # Conexion self.code.returnPressed.connect( lambda: self.changePasswordForm(username, codigo)) # Funcion para mostrar form de cambio de contraseña def changePasswordForm(self, username, codigo): if (self.code.text() != codigo): ErrorPrompt("Error", "Código Erroneo!") return self.labelInfo.setText("Ingrese la Nueva Contraseña") self.labelInfo.move(77, 20) self.code.setText("") self.code.setPlaceholderText("Nueva Contraseña") self.code.setEchoMode(QLineEdit.Password) self.code.setFixedHeight(40) self.code.move(72, 90) self.repeat_password.setText("") self.repeat_password.setPlaceholderText("Repetir Contraseña") self.repeat_password.setEchoMode(QLineEdit.Password) self.repeat_password.setFixedHeight(40) self.repeat_password.move(72, 140) # Conexion self.code.returnPressed.connect(lambda: self.changePassword(username)) self.repeat_password.returnPressed.connect( lambda: self.changePassword(username)) # Funcion para cambiar la password del usuario def changePassword(self, username): if (self.code.text() != self.repeat_password.text()): ErrorPrompt("Error", "Las contraseñas no coinciden!") return self.query = QSqlQuery() success = self.query.exec_("UPDATE CEIC_User SET password_ = crypt('" + str(self.code.text()) + "', gen_salt('bf', 8)) WHERE username = '******';") if (success): InfoPrompt("Success", "La contraseña ha sido modificada!") else: ErrorPrompt("Error", "Error Desconocido") self.close()
def update_preview(self): painter = QPainter() pagesize = self.previewPagesizeDropdown.currentText() orientation = self.previewOrientationDropdown.currentText().lower() if pagesize == "From File": if self.tabWidget.currentWidget() is self.singleTab: filename = self.singleSrcFileTxtBox.text() if filename and os.path.isfile(filename): pagesize = [ float(e) for e in PdfFileReader(open( filename, "rb")).getPage(0).mediaBox[2:] ] orientation = "portrait" else: pagesize = pagesizes.letter orientation = "portrait" elif self.tabWidget.currentWidget() is self.batchTab: file_list = self.get_batch_file_list() if file_list: filename = file_list[0] pagesize = [ float(e) for e in PdfFileReader(open( filename, "rb")).getPage(0).mediaBox[2:] ] orientation = "portrait" else: pagesize = pagesizes.letter orientation = "portrait" else: pagesize = self.pagesizes[pagesize] pageRatio = pagesize[0] / pagesize[1] if orientation == "landscape": pageRatio = 1 / pageRatio drawHeight = self.previewCanvas.height() - 10 page = [drawHeight * pageRatio, drawHeight] self.previewPixmap = QPixmap(self.previewCanvas.size()) painter.begin(self.previewPixmap) painter.fillRect(0, 0, self.previewPixmap.width(), self.previewPixmap.height(), QColor(200, 200, 200)) pageRect = [ self.previewPixmap.width() / 2 - page[0] / 2, self.previewPixmap.height() / 2 - page[1] / 2, page[0], page[1] ] painter.fillRect(pageRect[0] - 1, pageRect[1] - 1, pageRect[2] + 2, pageRect[3] + 2, QColor(0, 0, 0)) painter.fillRect(*pageRect, QColor(255, 255, 255)) text = self.watermarkTxtBox.toPlainText() text_lines = text.splitlines(False) text_font = QFont("Helvetica", 1) try: text_font.setFamily(marker.text_font.split("-")[0].split(" ")[0]) if "Bold" in marker.text_font: text_font.setBold(True) if "Oblique" in marker.text_font or "Italic" in marker.text_font: text_font.setItalic(True) except Exception as ex: print(ex) test_width = max( [QFontMetrics(text_font).width(line) for line in text_lines]) test_ratio = test_width / len(text_lines) text_size = math.sqrt( ((pageRect[2] * marker.text_scale)**2 + (pageRect[3] * marker.text_scale)**2)) / (test_ratio + 1) / len(text_lines) text_font.setPointSize(text_size) painter.setFont(text_font) painter.setPen( QColor(*[e * 255 for e in marker.text_color], marker.text_opacity * 255)) text_width = QFontMetrics(text_font).width(text) angle = math.atan2(pageRect[2], pageRect[3]) painter.translate(pageRect[0] + pageRect[2] / 2, pageRect[1] + pageRect[3] / 2) painter.rotate(-(90 - math.degrees(angle))) i = -(len(text_lines) - 1) / 2 for line in text_lines: painter.drawText(-QFontMetrics(text_font).width(line) / 2, text_size / 3 + text_size * i, line) i += 1 # painter.drawText(-text_width / 2, text_size / 3, text) self.previewCanvas.setPixmap(self.previewPixmap)
class Content(QWidget): def __init__(self, text, fileName, baseName, themeIndex, parent, window): super().__init__() self.editor = Editor(self) self.text = text self.window = window # This should be the Main class self.parent = parent self.status_bar = QStatusBar(self) self.wordlist = wordList self.fileName = fileName self.baseName = baseName self.temporary = 0 self.font = QFont() self.custom = Customize() self.font.setFamily(editor["editorFont"]) self.font.setPointSize(editor["editorFontSize"]) self.tabSize = editor["TabWidth"] self.editor.textChanged.connect(self.changeSaved) self.custom = Customize() self.saved = True self.editor.setPlainText(str(text)) self.editor.cursorPositionChanged.connect(self.change_col) if self.baseName.endswith(".py"): self.highlighter = PyHighlighter(self.editor.document(), index=self.custom.index) self.tokenize_file() else: pass self.main_layout = QVBoxLayout(self) self.test = QLabel(self) self.test.setText(" ") self.hbox = QHBoxLayout() self.status_bar_layout = QHBoxLayout() self.status_bar = QStatusBar(self) # Create a widget for the line numbers self.numbers = NumberBar(self.editor, index=themeIndex) self.hbox.addWidget(self.numbers) self.hbox.addWidget(self.editor) self.status_bar_layout.addWidget(self.status_bar) self.status_bar_layout.addWidget(self.test) self.main_layout.addLayout(self.hbox) self.main_layout.addLayout(self.status_bar_layout) self.completer = Completer(self.wordlist) self.moveCursorRight = QShortcut( QKeySequence(editor["moveCursorRight"]), self) self.moveCursorLeft = QShortcut(QKeySequence(editor["moveCursorLeft"]), self) self.selectAllBeforeCursor = QShortcut( QKeySequence(editor["selectAllWordsBeforeCursor"]), self) self.moveUp = QShortcut(QKeySequence(editor["moveCursorUp"]), self) self.moveDown = QShortcut(QKeySequence(editor["moveCursorDown"]), self) self.moveDown.activated.connect(self.moveCursorDown) self.moveUp.activated.connect(self.moveCursorUp) self.selectAllBeforeCursor.activated.connect(self.selectBeforeCursor) self.moveCursorRight.activated.connect(self.moveCursorRightFunc) self.moveCursorLeft.activated.connect(self.moveCursorLeftFunc) self.editor.textChanged.connect(self.changeSaved) self.setCompleter(self.completer) def change_col(self): cursor = self.editor.textCursor() current_row = cursor.blockNumber() current_line = cursor.positionInBlock() self.status_bar.showMessage("Line: " + str(current_row) + " Column: " + str(current_line)) def tokenize_file(self): for i in tokenize(self.fileName): for j in i: if j not in self.wordlist: self.wordlist.append(j) self.completer = Completer(self.wordlist) self.setCompleter(self.completer) def getTextCursor(self): textCursor = self.editor.textCursor() textCursorPos = textCursor.position() return textCursor, textCursorPos def changeSaved(self): self.modified = self.editor.document().isModified() try: if self.modified: self.window.setWindowTitle("PyPad ~ " + str(self.baseName) + " [UNSAVED]") else: pass except NameError as E: print(E) def moveCursorRightFunc(self): textCursor, textCursorPos = self.getTextCursor() textCursor.setPosition(textCursorPos + 1) self.editor.setTextCursor(textCursor) def moveCursorUp(self): textCursor, textCursorPos = self.getTextCursor() textCursor.movePosition(textCursor.Up) self.editor.setTextCursor(textCursor) def moveCursorDown(self): textCursor, textCursorPos = self.getTextCursor() textCursor.movePosition(textCursor.Down) self.editor.setTextCursor(textCursor) def moveCursorLeftFunc(self): textCursor, textCursorPos = self.getTextCursor() textCursor.setPosition(textCursorPos - 1) self.editor.setTextCursor(textCursor) def selectBeforeCursor(self): textCursor, textCursorPos = self.getTextCursor() text = self.textUnderCursor() textCursor.movePosition(textCursor.StartOfWord, textCursor.KeepAnchor, len(text)) self.editor.setTextCursor(textCursor) def setCompleter(self, completer): self.completer.setWidget(self) completer.setCompletionMode(QCompleter.PopupCompletion) completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer = completer self.completer.insertText.connect(self.insertCompletion) def insertCompletion(self, completion): textCursor = self.editor.textCursor() extra = (len(completion) - len(self.completer.completionPrefix())) textCursor.movePosition(QTextCursor.Left) textCursor.movePosition(QTextCursor.EndOfWord) textCursor.insertText(completion[-extra:]) if completion.endswith("()"): cursorPos = textCursor.position() textCursor.setPosition(cursorPos - 1) self.editor.setTextCursor(textCursor) def textUnderCursor(self): textCursor = self.editor.textCursor() textCursor.select(QTextCursor.WordUnderCursor) return textCursor.selectedText() def focusInEvent(self, event): if self.completer: self.completer.setWidget(self) QPlainTextEdit.focusInEvent(self, event) def keyPressEvent(self, event): if self.completer and self.completer.popup() and self.completer.popup( ).isVisible(): if event.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Escape, Qt.Key_Tab, Qt.Key_Backtab): event.ignore() return isShortcut = (event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_Space) if not self.completer or not isShortcut: QPlainTextEdit.keyPressEvent(self.editor, event) completionPrefix = self.textUnderCursor() if not isShortcut: if self.completer.popup(): self.completer.popup().hide() return self.completer.setCompletionPrefix(completionPrefix) popup = self.completer.popup() popup.setFont(self.font) popup.setCurrentIndex(self.completer.completionModel().index(0, 0)) cr = self.editor.cursorRect() cr.translate(QPoint(10, 10)) cr.setWidth \ (self.completer.popup().sizeHintForColumn(0) + self.completer.popup().verticalScrollBar().sizeHint().width()) self.completer.complete(cr)