def _loop_analysis_show_window(self):
"""Show feedback window. This window updates the feedback at an interval
defined by the user.
If this function is called, `func` must return a string to be displayed
in the feedback window. This string can include HTML and CSS, though not
all CSS is supported. See PyQt's stylesheet.
"""
app = QApplication.instance()
if not app:
app = QApplication(sys.argv)
self.window = MainWindow(self.stream, self.func,
self.args, self.buffer_len,
self._kill_signal)
self.window.show()
# Stop the analysis loop if MainWindow is closed.
app.aboutToQuit.connect(self.stop)
sys.exit(app.exec_())
python类instance()的实例源码
def closeEvent(self, event):
print('Closing')
app = _QApplication.instance()
app.closeAllWindows()
app.quit()
self.bcpre.pop_to_last(all=True)
del_flag = 0
for count in self.bcpre.cut_list:
try:
_os.remove(count + '.pickle')
except:
print('Error in deleting old pickle files')
else:
del_flag += 1
if del_flag == len(self.bcpre.cut_list):
del self.bcpre.cut_list
else:
print('Did not delete pickle file cut list... Something went wrong')
def __init__(self, parent=None):
# call widget init
QWidget.__init__(self, parent)
# link app
self._app = QApplication.instance()
# dictionary for remove background widgets
self._background_widgets = {}
# set fixed size
self.setFixedWidth(320)
self.setFixedHeight(321)
# set window title
self.setWindowTitle("Remove Background")
def __init__(self, parent=None):
# call widget init
QWidget.__init__(self, parent)
# link app
self._app = QApplication.instance()
# dictionary for spectrum widgets
self._spectrum_widgets = {}
self._current_widget = None
# set fixed size
self.setFixedWidth(480)
self.setFixedHeight(415)
# set window title
self.setWindowTitle("Spectrum")
def __init__(self, parent, map_handle):
# call widget init
QWidget.__init__(self, parent)
# link app
self._app = QApplication.instance()
# link map handle
self._map = map_handle
# load and set up UI
self.ui = UiPixelInformationWidget(self)
# set fixed size
self.setFixedWidth(320)
self.setFixedHeight(240)
def __init__(self, parent=None):
# call widget init
QWidget.__init__(self, parent)
# link app
self._app = QApplication.instance()
# dictionary for pixel information widgets
self._pixel_information_widgets = {}
self._current_widget = None
# set fixed size
self.setFixedWidth(320)
self.setFixedHeight(240)
# set window title
self.setWindowTitle("Pixel Information")
def execute(self):
# Define this here to give users something to look at.
qApp = QApplication.instance()
self.expression = self.text()
try:
result = str(eval(str(self.expression)))
# Emit the result of the evaluated expression.
self.pythonOutput.emit(result)
# Clear the line edit, append the successful expression to the
# history, and update the current command index.
self.clear()
self.history.append(self.expression)
self.current = len(self.history)
except:
pass
def __init__(self, parent=None):
super(ShapedClock, self).__init__(parent,
Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
timer = QTimer(self)
timer.timeout.connect(self.update)
timer.start(1000)
quitAction = QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=QApplication.instance().quit)
self.addAction(quitAction)
self.setContextMenuPolicy(Qt.ActionsContextMenu)
self.setToolTip("Drag the clock with the left mouse button.\n"
"Use the right mouse button to open a context menu.")
self.setWindowTitle(self.tr("Shaped Analog Clock"))
def execute(self):
# Define this here to give users something to look at.
qApp = QApplication.instance()
self.expression = self.text()
try:
result = str(eval(str(self.expression)))
# Emit the result of the evaluated expression.
self.pythonOutput.emit(result)
# Clear the line edit, append the successful expression to the
# history, and update the current command index.
self.clear()
self.history.append(self.expression)
self.current = len(self.history)
except:
pass
def __init__(self, parent=None):
super(ShapedClock, self).__init__(parent,
Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
timer = QTimer(self)
timer.timeout.connect(self.update)
timer.start(1000)
quitAction = QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=QApplication.instance().quit)
self.addAction(quitAction)
self.setContextMenuPolicy(Qt.ActionsContextMenu)
self.setToolTip("Drag the clock with the left mouse button.\n"
"Use the right mouse button to open a context menu.")
self.setWindowTitle(self.tr("Shaped Analog Clock"))
def closeEvent(self, event):
# ????,??????
with open("pos.dat", "wb") as fp:
pickle.dump(cache.globalPos, fp)
QApplication.instance().quit()
# return QWidget.closeEvent(self, event)
# def eventFilter(self, s, e):
# print(s, e)
# if s == self.headLabel and e.type() == QEvent.Enter:
# t = ToolTip(self, "?oo???o?", "resources/icon.ico", "", "data/head/1.png" "data/head/2.png" "data/head/3.png").show(s, self.frameGeometry().topLeft().x(), e.globalPos().y(), self.width(), self.dheight)
# t.move(938, 120)
# t.show()
# return super(Ucics, self).eventFilter(s, e)
# ??????
def test_close_all(self):
self.add_signal_to_form("esaver.complex")
self.assertEqual(self.form.signal_tab_controller.num_frames, 1)
self.form.close_all()
QApplication.instance().processEvents()
QTest.qWait(self.CLOSE_TIMEOUT)
self.assertEqual(self.form.signal_tab_controller.num_frames, 0)
# Add a bunch of signals
num_frames = 5
for _ in range(num_frames):
self.add_signal_to_form("esaver.complex")
self.assertEqual(self.form.signal_tab_controller.num_frames, num_frames)
self.form.close_all()
QApplication.instance().processEvents()
QTest.qWait(self.CLOSE_TIMEOUT)
self.add_signal_to_form("ask.complex")
self.assertEqual(self.form.signal_tab_controller.num_frames, 1)
def test_zoom(self):
self.add_signal_to_form("esaver.complex")
frame = self.form.signal_tab_controller.signal_frames[0]
QApplication.instance().processEvents()
x_zoom = frame.ui.spinBoxXZoom.value()
self.assertIn(x_zoom, range(100, 111))
for _ in range(10):
frame.ui.gvSignal.zoom(1.1)
self.assertGreater(frame.ui.spinBoxXZoom.value(), x_zoom)
x_zoom = frame.ui.spinBoxXZoom.value()
for _ in range(10):
frame.ui.gvSignal.zoom(0.99)
self.assertLess(frame.ui.spinBoxXZoom.value(), x_zoom)
x_zoom = frame.ui.spinBoxXZoom.value()
samples_in_view = frame.ui.lSamplesInView.text()
frame.ui.spinBoxXZoom.setValue(frame.ui.spinBoxXZoom.value() + 400)
self.assertNotEqual(samples_in_view, frame.ui.lSamplesInView.text())
def tearDown(self):
if hasattr(self, "dialog"):
self.dialog.close()
if hasattr(self, "form"):
self.form.close_all()
QApplication.instance().processEvents()
QTest.qWait(self.CLOSE_TIMEOUT)
self.form.close()
QApplication.instance().processEvents()
QTest.qWait(self.CLOSE_TIMEOUT)
sip.delete(self.form)
self.form = None
QApplication.instance().processEvents()
QTest.qWait(self.CLOSE_TIMEOUT)
def setUp(self):
super().setUp()
QApplication.instance().processEvents()
QTest.qWait(self.WAIT_TIMEOUT_BEFORE_NEW)
self.form.add_protocol_file(get_path_for_data_file("protocol.proto.xml"))
self.cframe = self.form.compare_frame_controller
self.cframe.add_protocol_label(9, 19, 0, 0, edit_label_name=False) # equals 10-20 in view
self.cframe.add_protocol_label(39, 54, 1, 0, edit_label_name=False) # equals 40-55 in view
self.assertEqual(len(self.cframe.proto_analyzer.protocol_labels), 2)
self.dialog = ProtocolLabelController(preselected_index=1,
message=self.cframe.proto_analyzer.messages[0],
viewtype=0, parent=self.cframe)
if self.SHOW:
self.dialog.show()
def __make_setting(self, signal_frame, pause_threshold=None, message_divisor_length=None):
def accept_dialog():
for widget in QApplication.instance().topLevelWidgets():
if isinstance(widget, AdvancedModulationOptionsController):
if pause_threshold is not None:
widget.ui.spinBoxPauseThreshold.setValue(pause_threshold)
if message_divisor_length is not None:
widget.ui.spinBoxMessageLengthDivisor.setValue(message_divisor_length)
widget.ui.buttonBox.accepted.emit()
return
timer = QTimer()
timer.setSingleShot(True)
timer.timeout.connect(accept_dialog)
timer.setInterval(10)
timer.start()
signal_frame.ui.btnAdvancedModulationSettings.click()
def test_create_context_menu(self):
self.add_signal_to_form("esaver.complex")
self.form.signal_tab_controller.signal_frames[0].ui.cbProtoView.setCurrentIndex(2)
logger.debug("Get text edit")
text_edit = self.form.signal_tab_controller.signal_frames[0].ui.txtEdProto
menu = text_edit.create_context_menu()
QApplication.instance().processEvents()
line_wrap_action = next(action for action in menu.actions() if action.text().startswith("Linewrap"))
checked = line_wrap_action.isChecked()
line_wrap_action.trigger()
menu = text_edit.create_context_menu()
QApplication.instance().processEvents()
line_wrap_action = next(action for action in menu.actions() if action.text().startswith("Linewrap"))
self.assertNotEqual(checked, line_wrap_action.isChecked())
def test_table_selection(self):
self.form.ui.tabWidget.setCurrentIndex(1)
self.cfc.ui.cbProtoView.setCurrentIndex(0)
self.cfc.ui.tblViewProtocol.selectRow(1)
QApplication.instance().processEvents()
self.assertEqual(self.cfc.ui.lBitsSelection.text(), self.cfc.proto_analyzer.messages[1].plain_bits_str)
self.cfc.ui.tblViewProtocol.clearSelection()
QApplication.instance().processEvents()
self.assertEqual("", self.cfc.ui.lBitsSelection.text())
self.cfc.ui.tblViewProtocol.select(0, 0, 0, 3)
QApplication.instance().processEvents()
self.assertEqual("1010", self.cfc.ui.lBitsSelection.text())
self.cfc.ui.cbProtoView.setCurrentIndex(1)
QApplication.instance().processEvents()
min_row, max_row, start, end = self.cfc.ui.tblViewProtocol.selection_range()
self.assertEqual(min_row, 0)
self.assertEqual(max_row, 0)
self.assertEqual(start, 0)
self.assertEqual(end, 1)
def test_hide_row(self):
num_messages = len(self.cfc.proto_analyzer.messages)
self.form.ui.tabWidget.setCurrentIndex(1)
self.assertGreater(num_messages, 0)
self.assertEqual(self.cfc.protocol_model.rowCount(), num_messages)
self.cfc.ui.tblViewProtocol.hide_row(0)
self.assertTrue(self.cfc.ui.tblViewProtocol.isRowHidden(0))
self.assertEqual(len(self.cfc.protocol_model.hidden_rows), 1)
for msg in range(1, num_messages):
self.assertFalse(self.cfc.ui.tblViewProtocol.isRowHidden(msg))
self.form.ui.tabWidget.setCurrentIndex(2)
QApplication.instance().processEvents()
self.form.ui.tabWidget.setCurrentIndex(1)
QApplication.instance().processEvents()
self.assertEqual(self.cfc.protocol_model.rowCount(), num_messages)
self.assertTrue(self.cfc.ui.tblViewProtocol.isRowHidden(0))
for msg in range(1, num_messages):
self.assertFalse(self.cfc.ui.tblViewProtocol.isRowHidden(msg))
self.assertEqual(len(self.cfc.protocol_model.hidden_rows), 1)
def draw_sine_wave(self):
if self.dialog_ui.graphicsViewSineWave.scene_manager:
self.dialog_ui.graphicsViewSineWave.scene_manager.clear_path()
QApplication.instance().setOverrideCursor(Qt.WaitCursor)
self.__set_status_of_editable_elements(enabled=False)
t = np.arange(0, self.num_samples) / self.sample_rate
arg = ((2 * np.pi * self.frequency * t + self.phase) * 1j).astype(np.complex64)
self.complex_wave = self.amplitude * np.exp(arg) # type: np.ndarray
self.draw_data = np.insert(self.original_data, self.position, self.complex_wave).imag.astype(np.float32)
y, h = self.dialog_ui.graphicsViewSineWave.view_rect().y(), self.dialog_ui.graphicsViewSineWave.view_rect().height()
self.insert_indicator.setRect(self.position, y - h, self.num_samples, 2 * h + abs(y))
self.__set_status_of_editable_elements(enabled=True)
QApplication.instance().restoreOverrideCursor()
self.dialog_ui.graphicsViewSineWave.plot_data(self.draw_data)
self.dialog_ui.graphicsViewSineWave.show_full_scene()
def __init__(self, *args, **kwargs):
super(ScreenSelectWidget, self).__init__(*args, **kwargs)
self._active_screen = -1
self._buttons = []
layout = QVBoxLayout()
# layout.addStretch(1)
layout.addWidget(QLabel(self.tr("Lyrics screen")))
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
self.refresh_widget()
desktop = QApplication.desktop()
desktop.screenCountChanged.connect(self.refresh_widget)
# TODO : update to qt 5.6 and uncomment the next line
# QApplication.instance().primaryScreenChanged.connect(self.refresh_widget)
def execute(self):
# Define this here to give users something to look at.
qApp = QApplication.instance()
self.expression = self.text()
try:
result = str(eval(str(self.expression)))
# Emit the result of the evaluated expression.
self.pythonOutput.emit(result)
# Clear the line edit, append the successful expression to the
# history, and update the current command index.
self.clear()
self.history.append(self.expression)
self.current = len(self.history)
except:
pass
def __init__(self, parent=None):
super(ShapedClock, self).__init__(parent,
Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
timer = QTimer(self)
timer.timeout.connect(self.update)
timer.start(1000)
quitAction = QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=QApplication.instance().quit)
self.addAction(quitAction)
self.setContextMenuPolicy(Qt.ActionsContextMenu)
self.setToolTip("Drag the clock with the left mouse button.\n"
"Use the right mouse button to open a context menu.")
self.setWindowTitle(self.tr("Shaped Analog Clock"))
def draw_network(self, nodes, links):
app = QApplication.instance()
logger = logging.getLogger()
# we are plotting wholesale. So, disable signals temporily
with u.updates_disabled_temporarily(self.get_plot()):
if(nodes):
logger.info("Drawing nodes")
app.processEvents()
self.draw_nodes(nodes)
# we don't want users to select grid, or nodes and they should not appear in the item list.
# So lock'em up.
self.set_all_private()
if(links):
logger.info("Drawing links")
app.processEvents()
self.draw_links(links)
self.get_plot().do_autoscale(replot=True)
def init_gui():
""" Tries to find the main Binja window. If we've already found it, does nothing.
Call this as many times as you want, just in case. """
global main_window
if main_window is None:
app = QApplication.instance()
main_window = [x for x in app.allWidgets() if x.__class__ is QMainWindow][0]
def get_qt_application_instance():
q_app = QApplication.instance()
if q_app is None:
q_app = QApplication([])
q_app.lastWindowClosed.connect(QtManager.empty_windows_list)
return q_app
def center_window(window):
"""Center the given window on the screen.
Args:
q_app (QApplication): for desktop information
window (QMainWindow): the window to center
"""
q_app = QApplication.instance()
frame_gm = window.frameGeometry()
screen = q_app.desktop().screenNumber(q_app.desktop().cursor().pos())
center_point = q_app.desktop().screenGeometry(screen).center()
frame_gm.moveCenter(center_point)
window.move(frame_gm.topLeft())
def __init__(self, attribute_name):
"""Descriptor that will emit a state_updated_signal at each update.
This accesses from the instance the attribute name prepended with an underscore (_).
"""
self._attribute_name = attribute_name
def __get__(self, instance, owner):
return getattr(instance, '_' + self._attribute_name)
def __set__(self, instance, value):
setattr(instance, '_' + self._attribute_name, value)
instance.state_updated_signal.emit(self._attribute_name)