class LongPythonThread(QObject): thread_finished = Signal(str) def __init__(self): super(LongPythonThread, self).__init__() def train_network(self, filter, file_name): filter.tf_learn(file_name) self.thread_finished.emit("Done")
class CometManagerProxy(QObject): def __init__(self, parent=None): super(CometManagerProxy, self).__init__(parent) dm = manager() dm.termTopicConnectionCountChanged.connect(self.termTopicConnectionCountChanged) termTopicConnectionCountChanged = Signal(int) termTopicConnectionCount = Property(int, lambda self: manager().termTopicConnectionCount(), notify=termTopicConnectionCountChanged)
class _LoggedPage(QWebPage): obj = [] # synchronous commandRecieved = Signal(str) helpNeeded = Signal(str) tabPressed = Signal(str) def javaScriptConsoleMessage(self, msg, line, source): l = msg.split(",") self.obj = l if msg[:3] == "TAB": self.tabPressed.emit(msg[3:]) elif msg[:3] == "CMD": if msg[3:7] == "help": self.helpNeeded.emit(msg[3:]) else: self.commandRecieved.emit(msg[3:]) print('JS: %s line %d: %s' % (source, line, msg))
class SpellAction(QAction): """ An Action which will change the selected word. """ correct = Signal(unicode) def __init__(self, *args): QAction.__init__(self, *args) self.triggered.connect(lambda: self.correct.emit(unicode(self.text())))
class _ExecThread(QThread): update = Signal(tuple) def __init__(self, func): QThread.__init__(self) self.func = func def run(self): output = self.func() self.update.emit(output)
class FadeToBlack(QObject): activeChanged = Signal(bool) rateChanged = Signal(int) def __init__(self): super(FadeToBlack, self).__init__() self.active = False self.rate = 25 def set_active(self, active): if self.active != active: self.active = active self.activeChanged.emit(active) def set_rate(self, rate): if self.rate != rate: self.rate = rate self.rateChanged.emit(rate)
class FiltersCombo(QComboBox): filter_query_selected = Signal(object) def __init__(self, parent, family): super(FiltersCombo, self).__init__(parent) self._family = family self._filters = [] self.activated.connect(self.emit_filter_query_selected) def current_filter(self): if 0 <= self.currentIndex() < len(self._filters): return self._filters[self.currentIndex()] else: return None def preselect(self, fq_id: int, emit_selection_signal: bool = True): if not self._filters: self.reload() for i in range(len(self._filters)): if self._filters[i].filter_query_id == fq_id: self.setCurrentIndex(i) if emit_selection_signal: self.filter_query_selected.emit(self._filters[i]) return # If the filter has been removed, then the configuration file # is not correct anymore. I could warn the user, but the problem # is that if I do it from here, then the warning might be # out of context (gui wise). So I prefer to fail silently. mainlog.warning("Unable to preselect filter id {}".format(fq_id)) if self._filters: self.setCurrentIndex(0) if emit_selection_signal: self.filter_query_selected.emit(self._filters[0]) @Slot() def reload(self): global dao global user_session mainlog.debug("Reloading filters for family {}".format(self._family)) self._filters = dao.filters_dao.usable_filters(user_session.user_id, self._family) self.clear() for fq in self._filters: mainlog.debug("Filter : {} {}".format(fq.name, fq.filter_query_id)) self.addItem(fq.name, fq.filter_query_id) @Slot(int) def emit_filter_query_selected(self, ndx): self.filter_query_selected.emit(self._filters[ndx])
class PublisherDialog(QDialog): if USE_MAEMO_5: switchRequested = Signal() def __init__(self, parent=None): QDialog.__init__(self, parent) self.ui = Ui_PublisherDialog() self.ui.setupUi(self) self.publisher = None if USE_MAEMO_5: switchButton = self.ui.buttonBox.addButton( self.tr('Switch'), QDialogButtonBox.ActionRole) switchButton.clicked.connect(self.switchRequested) self.ui.connectButton.clicked.connect(self.createNewObject) self.ui.intValue.valueChanged.connect(self.intValueChanged) self.ui.unsetIntButton.clicked.connect(self.unsetIntValue) self.ui.setStringButton.clicked.connect(self.setStringValue) self.ui.setByteArrayButton.clicked.connect(self.setByteArrayValue) self.createNewObject() def changeEvent(self, e): QDialog.changeEvent(self, e) if e.type() == QEvent.LanguageChange: self.ui.retranslateUi(self) def intValueChanged(self, value): self.publisher.setValue('intValue', value) def unsetIntValue(self): self.publisher.resetValue('intValue') def setStringValue(self): self.publisher.setValue('stringValue', self.ui.stringValue.text()) def setByteArrayValue(self): self.publisher.setValue('byteArrayValue', self.ui.byteArrayValue.text()) def createNewObject(self): if self.publisher: del self.publisher self.publisher = QValueSpacePublisher(QValueSpace.WritableLayer, self.ui.basePath.text()) if self.publisher.isConnected(): self.ui.setters.setEnabled(True) self.intValueChanged(self.ui.intValue.value()) self.setStringValue() self.setByteArrayValue() else: self.ui.setters.setEnabled(False)
class TouchSpinner(QWidget): valueChanged = Signal(int) def __init__(self, parent=None): super(TouchSpinner, self).__init__(parent) self._value = 50 self._max = 100 self._min = 0 layout = QHBoxLayout() self.btnMinus = ExpandingButton() self.btnMinus.setIcon(QIcon(":icons/list-remove")) self.btnMinus.setText("-") self.btnMinus.clicked.connect(lambda: self.setValue(self._value - 1)) layout.addWidget(self.btnMinus, 1) self.lblValue = QLabel(self.formattedValue(self._value)) self.lblValue.setAlignment(Qt.AlignHCenter) layout.addWidget(self.lblValue, 1) self.btnPlus = ExpandingButton() self.btnPlus.setIcon(QIcon(":icons/list-add")) self.btnPlus.setText("+") self.btnPlus.clicked.connect(lambda: self.setValue(self._value + 1)) layout.addWidget(self.btnPlus, 1) self.setLayout(layout) def setValue(self, value): if value > self._max: newValue = self._max elif value < self._min: newValue = self._min else: newValue = value if value != self._value: self._value = newValue self.valueChanged.emit(newValue) self.lblValue.setText(self.formattedValue(newValue)) self.btnPlus.setEnabled(self._value < self._max) self.btnMinus.setEnabled(self._value > self._min) def setMaximum(self, maxi): self._max = maxi def setMinimum(self, mini): self._min = mini def value(self): return self._value def formattedValue(self, value): return "{}".format(value)
class Wallpaper(QObject): def __init__(self, ): QObject.__init__(self) self._running = False @Slot(unicode, int, int) def setWallpaper(self, url, offset, width): self._set_running(True) self.thread = threading.Thread(target=self._setWallpaper, \ args=(url, offset, width)) self.thread.start() def _setWallpaper(self, url, offset, width): inStream = urllib2.urlopen(url) img = QImage.fromData(inStream.read()) img = img.scaledToHeight(854,Qt.SmoothTransformation) #offset = int(img.width() / 2) - 240 print 'offset:', offset, 'img.width', img.width(), 'width', width img = img.copy(offset, 0, 480, 854) img.save(WALLPATH) #Set in gconf import gconf gclient = gconf.client_get_default() gclient.set_string(GCONFKEY, '') gclient.set_string(GCONFKEY, \ WALLPATH) #Emit done signal self._set_running(False) self.done.emit() def _get_running(self): return self._running def _set_running(self, b): self._running = b self.on_running.emit() done = Signal() on_running = Signal() running = Property(bool, _get_running, _set_running, notify=on_running)
class WebBrowser(SkDraggableMainWindow): quitRequested = Signal() messageReceived = Signal(unicode) def __init__(self, parent=None): #WINDOW_FLAGS = ( # Qt.Window # | Qt.CustomizeWindowHint # | Qt.WindowTitleHint # | Qt.WindowSystemMenuHint # | Qt.WindowMinMaxButtonsHint # | Qt.WindowCloseButtonHint #) super(WebBrowser, self).__init__(parent) self.__d = _WebBrowser(self) skqss.class_(self, 'webkit') def showStatusMessage(self, t, type='message'): """ @param t unicode @param type 'message', 'warning', or 'error' """ self.statusBar().showMessage(text) def openDefaultPage(self): self.__d.newTabAfterCurrentWithBlankPage() def openUrls(self, urls): # [unicode url] for url in urls: self.__d.openUnknownAfterCurrent(url) #self.__d.openUrl(url) def loadTabs(self): # -> bool return self.__d.loadTabs() def closeEvent(self, e): ss = settings.global_() ss.setWindowWidth(self.width()) ss.setWindowHeight(self.height()) super(WebBrowser, self).closeEvent(e)
class TasksPool(QObject): startNextTaskSignal = Signal() allTasksCompleteSignal = Signal() def __init__(self): super(TasksPool, self).__init__() self.tasks_pool = [] self.process = QProcess() self.startNextTaskSignal.connect(self.execute_task) self.allTasksCompleteSignal.connect(self.tasks_complete) self.source = '' def add_task(self, command): self.tasks_pool.append(command) self.startNextTaskSignal.emit() def execute_task(self): print('Start next?') if self.process.isOpen(): self.process.waitForFinished() if not self.tasks_pool: self.allTasksCompleteSignal.emit() return self.process = QProcess() self.process.finished.connect( lambda *x: QTimer.singleShot(1000, self.startNextTaskSignal.emit)) self.process.setProcessChannelMode(QProcess.MergedChannels) self.process.readyRead.connect(self.process_output) next_task = self.tasks_pool.pop(0) print('NEXT TASK', next_task) self.process.start(next_task) def process_output(self): output = self.process.readAll() output = str(output).strip() if output: print(output) def tasks_complete(self): print('ALL TASKS COMPLETE')
class QUDevMonitorObserver(QObject, QUDevMonitorObserverMixin): """ An observer for device events integrating into the :mod:`PySide` mainloop. This class inherits :class:`~PySide.QtCore.QObject` to turn device events into Qt signals: >>> from pyudev import Context, Monitor >>> from pyudev.pyqt4 import QUDevMonitorObserver >>> context = Context() >>> monitor = Monitor.from_netlink(context) >>> monitor.filter_by(subsystem='input') >>> observer = QUDevMonitorObserver(monitor) >>> def device_connected(device): ... print('{0!r} added'.format(device)) >>> observer.deviceAdded.connect(device_connected) >>> monitor.start() This class is a child of :class:`~PySide.QtCore.QObject`. """ #: emitted upon arbitrary device events deviceEvent = Signal(text_type, Device) #: emitted, if a device was added deviceAdded = Signal(Device) #: emitted, if a device was removed deviceRemoved = Signal(Device) #: emitted, if a device was changed deviceChanged = Signal(Device) #: emitted, if a device was moved deviceMoved = Signal(Device) def __init__(self, monitor, parent=None): """ Observe the given ``monitor`` (a :class:`~pyudev.Monitor`): ``parent`` is the parent :class:`~PySide.QtCore.QObject` of this object. It is passed unchanged to the inherited constructor of :class:`~PySide.QtCore.QObject`. """ QObject.__init__(self, parent) self._setup_notifier(monitor, QSocketNotifier)
class outputStream(QObject): #set up a signal 'message' for transmitting stdout/stderr message = Signal(str) def __init__(self, parent=None): #standard __init__ super(outputStream, self).__init__(parent) def write(self, message): #send message to be printed in terminal window self.message.emit(str(message))
class Transition(QObject): changedProps = Signal() def __init__(self): super(Transition, self).__init__() self.rate = 1 def set_rate(self, rate): if self.rate != rate: self.rate = rate self.changedProps.emit()
class Scene(QObject): """Parent class for all Scene classes.""" causeChangeSignal = Signal(QObject) # For changes originating w/this scene changeSignal = Signal(QObject) # For changes applied to this scene def __init__(self): """Construct a Scene object.""" super(Scene, self).__init__() def announceChange(self): """This should be called whenever a Scene object is changed due to a user action. Example: When a user selects highlights. """ self.causeChangeSignal.emit(self) def acceptChanges(self): self.changeSignal.emit(self)
class HistogramWidget(QWidget, Ui_HistogramWindow): fourier_updated = Signal(np.ndarray) def __init__(self, parent_title, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self.setWindowTitle("{}'s Histogram".format(parent_title)) def update_histogram(self, image_array, cause): self.histogram.update(image_array)
class TradeLog(QObject): trade_added = Signal(QObject) trade_completed = Signal(QObject) def __init__(self): super().__init__() self.start_time = time.time() self.log = [] def add_trade(self, trade): self.trade_added.emit(trade) def complete_trade(self, trade): trade.complete_time = datetime.datetime.now() logging.info("Completed trade!") logging.debug("Start amount1: {} \t Remaining amount1: {}".format( str(trade.amount1), str(trade.remaining1))) self.log.append(trade) self.trade_completed.emit(trade)
class PassFilterDialog(Dialog, QDialog, ff.Ui_Dialog): mask_accepted = Signal(np.ndarray) updated = Signal(np.ndarray) mask = None def __init__(self, low=True, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.low = low self.horizontalSlider.valueChanged.connect(self.update_mask) self.buttonBox.rejected.connect(self._clear) self.buttonBox.accepted.connect(self._apply_mask) def update_mask(self, diam): diam = diam if not self.low else 99 - diam print(diam) max_dim = max(self.height, self.width) diam = max_dim * (diam / 100) self.mask = round_mask(diam, self.width, self.height, low=self.low) self.updated.emit(self.mask.copy())
class MTTFileList(QListView): """ Extend QListView for navigation """ selectionValidated = Signal() goToParentDirectory = Signal() def __init__(self, parent=None): super(MTTFileList, self).__init__(parent) self.filter_line = None def keyPressEvent(self, event): if event.key() == Qt.Key_F and event.modifiers() == Qt.ControlModifier: self.filter_line.setFocus() elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: self.selectionValidated.emit() elif event.key() == Qt.Key_Backspace: self.goToParentDirectory.emit() else: super(MTTFileList, self).keyPressEvent(event)
class CloseLabel(QLabel): closeSignal = Signal() def __init__(self): super(CloseLabel, self).__init__("Close") self.setStyleSheet("QLabel { color : white; }") def mousePressEvent(self, e): self.closeSignal.emit()
class Mixin(QObject): changed = Signal() def add_observer(self, slot): self.changed.connect(slot) def remove_observer(self, slot): self.changed.disconnect(slot) def on_change(self): self.changed.emit()
class OcrPopupBean(QObject): instance = None def __init__(self, parent=None): super(OcrPopupBean, self).__init__(parent) OcrPopupBean.instance = self dprint("pass") popupRequested = Signal(int, int, QObject, QObject, unicode, unicode) # x, y, imgobj, winobj, text, language
class ThreadRun(QThread): trigger = Signal() # trigger传输的内容是字符串 def __init__(self, parent=None): super(ThreadRun, self).__init__(parent) def setup(self): pass def run(self): self.trigger.emit()
class TextReader(QObject): ## Construction ## def __init__(self, parent=None): super(TextReader, self).__init__(parent) self.__d = _TextReader(self) pageBreakReceived = Signal() textReceived = Signal(unicode, unicode, long) # text, lang, timestamp translationReceived = Signal(unicode, unicode, unicode, long) # text, language, provider, timestamp ## Properties ## def userLanguage(self): return self.__d.language def setUserLanguage(self, value): self.__d.language = value #def encoding(self): return self.__d.encoding #def setEncoding(self, encoding): self.__d.encoding = encoding def gameLanguage(self): return self.__d.gameLanguage def setGameLanguage(self, value): self.__d.gameLanguage = value ## Actions ## def addText(self, text): d = self.__d if text == d.lastText: return d.lastText = text #if len(text) > defs.MIRAGE_MAX_TEXT_LENGTH: # growl.msg(my.tr("Game text is ignored for being too long")) #else: d.showText(text)
class OnlineThread(QThread): playRequested = Signal(object, unicode, str, str, float) # OnlineEngine, text, language, gender, time stopRequested = Signal(float) # time abortSignal = Signal() abortSignalRequested = Signal() def __init__(self, parent=None): super(OnlineThread, self).__init__(parent) self.__d = _OnlineThread() def run(self): """@reimp""" skwincom.coinit(threading=True) # critical to use WMP self.__d.run(self) self.exec_() def destroy(self): self.abortSignalRequested.emit() self.quit() #skwincom.couninit() # never invoked # Actions def requestPlay(self, engine, text, language, gender): # OnlineTask -> now = time() d = self.__d d.time = now if d.downloadCount > 0: self.abortSignalRequested.emit() self.playRequested.emit(engine, text, language, gender, now) def requestStop(self): d = self.__d now = time() d.time = now if d.downloadCount > 0: self.abortSignalRequested.emit() if d.playing: self.stopRequested.emit(now)
class GlobalFilter(QObject): """ Event filter for filtering events (i.e. key events) on main dialog and its children """ escapePressed = Signal() playKeyPressed = Signal() stopKeyPressed = Signal() muteKeyPressed = Signal() volumeUpKeyPressed = Signal() volumeDownKeyPressed = Signal() mouseWheel = Signal(int) def eventFilter(self, obj, event): """ Handles every event on filtered object and its children :param event: custom event :param obj: receiver :type event: PySide.QtCore.QEvent :type obj: PySide.QtCore.QObject :return: if the event needs to be filtered (eaten) :rtype : bool """ # --- KEY PRESS events ---- if event.type() is QEvent.KeyPress: modifier = QApplication.queryKeyboardModifiers( ) # get pressed modifier keys (ctrl, shift, alt, etc) # ESCAPE key if event.key() == Qt.Key_Escape: self.escapePressed.emit() # PLAY or SPACE key elif event.key() == Qt.Key_MediaPlay or event.key( ) == Qt.Key_Space: self.playKeyPressed.emit() # STOP key elif event.key() == Qt.Key_MediaStop: self.stopKeyPressed.emit() # CTRL + PLUS key pressed if event.key() == Qt.Key_Plus and modifier == Qt.ControlModifier: self.volumeUpKeyPressed.emit() return True # CTRL + MINUS key pressed if event.key() == Qt.Key_Minus and modifier == Qt.ControlModifier: self.volumeDownKeyPressed.emit() return True # CTRL + * key pressed if event.key( ) == Qt.Key_Asterisk and modifier == Qt.ControlModifier: self.muteKeyPressed.emit() return True return super(GlobalFilter, self).eventFilter(obj, event)
class SliderWidget(QWidget): """ SliderWidget """ valueChanged = Signal(int) def __init__(self): super(SliderWidget, self).__init__() self.label = QLabel() self.slider = QSlider(Qt.Horizontal) self.spinbox = QSpinBox() self.slider.valueChanged.connect(self.changedValue) self.spinbox.valueChanged.connect(self.changedValue) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setVerticalSpacing(0) layout.addWidget(self.label, 0, 0) layout.addWidget(self.slider, 0, 1) layout.addWidget(self.spinbox, 0, 2) self.setLayout(layout) def setName(self, name): """ Set the name for the slider """ self.label.setText(name) def setRange(self, range): """ Set the range for the value """ self.slider.setMinimum(range[0]) self.spinbox.setMinimum(range[0]) self.slider.setMaximum(range[1]) self.spinbox.setMaximum(range[1]) def setValue(self, value): """ Set the value for the slider and the spinbox """ self.slider.setValue(value) self.spinbox.setValue(value) def value(self): return self.slider.value() @Slot(int) def changedValue(self, value): self.setValue(value) self.valueChanged.emit(value)
class View(QDeclarativeView): def __init__(self): QDeclarativeView.__init__(self) self.setSource( QUrl.fromLocalFile(adjust_filename('bug_847.qml', __file__))) self.rootObject().setProperty('pythonObject', self) @Slot(int, int) def blubb(self, x, y): self.called.emit(x, y) called = Signal(int, int)
class HubOpenFile(QObject): def __init__(self): super(HubOpenFile, self).__init__() @Slot(str) def connect(self, config): txtFileName = QFileDialog.getOpenFileNames(None, "Open")[0] txtFileName = str(txtFileName).replace("[u'", '').replace("']", '') print(txtFileName) text = open(txtFileName).read() self.on_file_open_event.emit(text) @Slot(str) def disconnect(self, config): print(config) on_file_open_event = Signal(str) on_connect = Signal(str) on_disconnect = Signal(str)