我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用PyQt5.QtCore.pyqtSignal()。
def import_pyqt5(): """ Import PyQt5 ImportErrors rasied within this function are non-recoverable """ import sip from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # Join QtGui and QtWidgets for Qt4 compatibility. QtGuiCompat = types.ModuleType('QtGuiCompat') QtGuiCompat.__dict__.update(QtGui.__dict__) QtGuiCompat.__dict__.update(QtWidgets.__dict__) api = QT_API_PYQT5 return QtCore, QtGuiCompat, QtSvg, api
def start_playing(self, filename): class QtPlaybin(Playbin, QtCore.QObject): eos = QtCore.pyqtSignal() def end_of_stream(self): self.eos.emit() def create_video_sink(self, name): if platform.system() == 'Darwin': # default (gl) sink does not play well with GstOverlay, at least not when using Qt return Gst.ElementFactory.make('osxvideosink', name) elif platform.system() == 'Linux': # Same for the default on Linux... return Gst.ElementFactory.make('xvimagesink', name) return super().create_video_sink(name) self.playbin = QtPlaybin(win_id=self.winId()) self.playbin.eos.connect(self.close) yield from self.playbin.play(filename)
def _pyqt5(): import PyQt5.Qt from PyQt5 import QtCore, QtWidgets, uic _remap(QtCore, "Signal", QtCore.pyqtSignal) _remap(QtCore, "Slot", QtCore.pyqtSlot) _remap(QtCore, "Property", QtCore.pyqtProperty) _add(PyQt5, "__binding__", PyQt5.__name__) _add(PyQt5, "load_ui", lambda fname: uic.loadUi(fname)) _add(PyQt5, "translate", lambda context, sourceText, disambiguation, n: ( QtCore.QCoreApplication(context, sourceText, disambiguation, n))) _add(PyQt5, "setSectionResizeMode", QtWidgets.QHeaderView.setSectionResizeMode) _maintain_backwards_compatibility(PyQt5) return PyQt5
def __init__(self): """ Initialise class """ QtWidgets.QWidget.__init__(self) self.setupUi(self) output.PPTevents.updateSlide = self.powerpointSlides.setCurrentRow self.contentControls.setCurrentIndex(0) # TODO not implemented """ self.mediaProgressSeek.setMouseTracking(True) self.mediaProgressSeek.leaveEvent=self.seekMouse self.mediaProgressSeek.mouseMoveEvent=self.seekMouse self.mediaProgressSeek.mouseReleaseEvent=lambda e: output.seek(e.x()/self.mediaProgressSeek.width()) """ # Update video scrubber position class ProgressBarUpdater(QtCore.QThread): tick = QtCore.pyqtSignal(int) def run(self): while True: self.sleep(1) self.tick.emit(oncue.lib.utils.confine(int(output.VLCposition() * 1000), 0, 1000)) self.mediaProgressBarThread = ProgressBarUpdater() self.mediaProgressBarThread.tick.connect( lambda value: self.mediaProgressBar.setValue(value) or self.mediaProgressBar.repaint())
def import_pyqt5(): """ Import PyQt5 ImportErrors raised within this function are non-recoverable """ from PyQt5 import QtGui, QtCore, QtSvg # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot return QtCore, QtGui, QtSvg, QT_API_PYQT5
def pyqt5(): import PyQt5.Qt from PyQt5 import QtCore, uic remap(QtCore, "Signal", QtCore.pyqtSignal) remap(QtCore, "Slot", QtCore.pyqtSlot) remap(QtCore, "Property", QtCore.pyqtProperty) add(PyQt5, "__wrapper_version__", __version__) add(PyQt5, "__binding__", "PyQt5") add(PyQt5, "__binding_version__", QtCore.PYQT_VERSION_STR) add(PyQt5, "__qt_version__", QtCore.QT_VERSION_STR, safe=False) add(PyQt5, "__added__", __added__) add(PyQt5, "__remapped__", __remapped__) add(PyQt5, "__modified__", __modified__) add(PyQt5, "load_ui", lambda fname: uic.loadUi(fname)) return PyQt5
def __init__(self): QMainWindow.__init__(self) #show_msg = pyqtSignal() self.ui = Ui_MainWindow() self.ui.setupUi(self) list_of_items = {'Osdagpage': 0, 'connectionpage': 1, 'tensionpage': 2, 'compressionpage': 3, 'flexuralpage': 4} self.ui.myStackedWidget.setCurrentIndex(list_of_items['Osdagpage']) self.ui.btn_connection.clicked.connect(lambda: self.change_desgin_page(list_of_items['connectionpage'], list_of_items['Osdagpage'])) self.ui.myListWidget.currentItemChanged.connect(self.change_desgin_page) self.ui.btn_start.clicked.connect(self.show_design_connection) self.ui.btn_beamCol.clicked.connect(self.unavailable) self.ui.btn_compression.clicked.connect(self.unavailable) self.ui.btn_flexural.clicked.connect(self.unavailable) self.ui.btn_truss.clicked.connect(self.unavailable) self.ui.btn_2dframe.clicked.connect(self.unavailable) self.ui.btn_3dframe.clicked.connect(self.unavailable) self.ui.btn_groupdesign.clicked.connect(self.unavailable) self.ui.btn_tension.clicked.connect(self.unavailable) self.ui.btn_plate.clicked.connect(self.unavailable) self.ui.comboBox_help.setCurrentIndex(0) self.ui.comboBox_help.currentIndexChanged.connect(self.selection_change)
def test_selection_calculation_of_wlc_returns_correct_results(self): from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import QObject class PM(QObject): def callwithmyid(self, id): pass heres_a_curve_signal = pyqtSignal(object) pm=PM() class testData: id = "P2" requestingcurve="boo" years=100 cons=200000*.32 r=3 A=.022 lunits=c.METERS N0=0.081 length=300 age=20 cost=1.0*1.e6*length/1000. pd=testData() wlcthread=WLCThread(pm, pd) wlcthread.do_the_job() self.assertAlmostEqual(wlcthread.result.damagecost[50],102579,delta=10000) self.assertAlmostEqual(wlcthread.result.renewalcost[50],68000,delta=1000)
def transmitter(function, data_format): if data_format: _, types = zip(*data_format) else: types = [] cls = type('QtTransmitter', (_QtTransmitter,), dict(signal=pyqtSignal(*types))) return cls(function, data_format)
def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors rasied within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if not check_version(QtCore.PYQT_VERSION_STR, '4.7'): raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api
def initThumbs(self) -> None: framesize = self.parent.videoService.framesize() thumbsize = QSize(VideoService.ThumbSize.TIMELINE.value.height() * (framesize.width() / framesize.height()), VideoService.ThumbSize.TIMELINE.value.height()) positions, frametimes = [], [] thumbs = int(math.ceil((self.rect().width() - (self.offset * 2)) / thumbsize.width())) for pos in range(thumbs): val = QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), (thumbsize.width() * pos) - self.offset, self.rect().width() - (self.offset * 2)) positions.append(val) positions[0] = 1000 [frametimes.append(self.parent.delta2QTime(msec).toString(self.parent.timeformat)) for msec in positions] class ThumbWorker(QObject): completed = pyqtSignal(list) def __init__(self, media: str, times: list, size: QSize): super(ThumbWorker, self).__init__() self.media = media self.times = times self.size = size @pyqtSlot() def generate(self): frames = list() [frames.append(VideoService.captureFrame(self.media, frame, self.size)) for frame in self.times] self.completed.emit(frames) self.thumbsThread = QThread(self) self.thumbsWorker = ThumbWorker(self.parent.currentMedia, frametimes, thumbsize) self.thumbsWorker.moveToThread(self.thumbsThread) self.thumbsThread.started.connect(self.parent.sliderWidget.setLoader) self.thumbsThread.started.connect(self.thumbsWorker.generate) self.thumbsThread.finished.connect(self.thumbsThread.deleteLater, Qt.DirectConnection) self.thumbsWorker.completed.connect(self.buildTimeline) self.thumbsWorker.completed.connect(self.thumbsWorker.deleteLater, Qt.DirectConnection) self.thumbsWorker.completed.connect(self.thumbsThread.quit, Qt.DirectConnection) self.thumbsThread.start()
def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors raised within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if not check_version(QtCore.PYQT_VERSION_STR, '4.7'): raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api
def _pyqt5(): import PyQt5.Qt from PyQt5 import QtCore, QtWidgets, uic _remap(QtCore, "Signal", QtCore.pyqtSignal) _remap(QtCore, "Slot", QtCore.pyqtSlot) _remap(QtCore, "Property", QtCore.pyqtProperty) _add(QtCompat, "__binding__", PyQt5.__name__) _add(QtCompat, "__binding_version__", PyQt5.QtCore.PYQT_VERSION_STR) _add(QtCompat, "__qt_version__", PyQt5.QtCore.QT_VERSION_STR) _add(QtCompat, "load_ui", lambda fname: uic.loadUi(fname)) _add(QtCompat, "translate", QtCore.QCoreApplication.translate) _add(QtCompat, "setSectionResizeMode", QtWidgets.QHeaderView.setSectionResizeMode) _maintain_backwards_compatibility(PyQt5) return PyQt5
def parseFeed(self): """ Parse the news feed and start the news scrolling. """ class FeedParser(QThread): msignal = pyqtSignal(str) def run(self): """ Threaded code. """ try: LOG.debug('parsing RSS feeds from: %s', B3_RSS) feed = feedparser.parse(B3_RSS) except Exception, e: LOG.warning('could not parse RSS feed from %s: %s', B3_RSS, e) else: feedlist = [] for item in feed['entries']: feeddate = ' '.join(item['published'].split(' ')[1:4]) feedlist.append('[%(DATE)s] %(TEXT)s' % dict(DATE=feeddate, TEXT=item['title'])) self.msignal.emit(' - '.join(feedlist)) self.qthread = FeedParser(self) self.qthread.msignal.connect(self.setMarqueeText) self.qthread.finished.connect(self.start) self.qthread.start()
def __init__(self): super(LogSender, self).__init__() if not hasattr(self, 'logsender_signal'): LogSender.logsender_signal = pyqtSignal(object)
def init_ui(self): # self.setGeometry(300, 300, 300, 220) self.center() self.setWindowTitle('Kiosk') # self.setWindowIcon(QIcon('web.png')) self.show() # programName("calc.exe"); # QStringList arguments; # process_ptr = QProcess(self); # process_ptr.conn # QObject.connect(process_ptr, pyqtSignal(self, name="closeEmitApp()"), process_ptr, pyqtSlot(self, name="close()")) # process_ptr.start("calc.exe", []) # self.createWindowContainer() program = "calc.exe" arguments = [] layout = QVBoxLayout() myProcess = QProcess(self) myProcess.setProgram(program) myProcess.setArguments(arguments) # myProcess. self.show() window = QWindow.fromWinId(self.winId()) container = self.createWindowContainer(window) # container. container.show() myProcess.setParent(window) myProcess.start() pid = myProcess.pid() print("PID:",int(pid)) LPWinProcInfo = ctypes.POINTER(WinProcInfo) lp = ctypes.cast(int(myProcess.pid()), LPWinProcInfo) print(lp.contents.dwProcessID) win32w = QWindow.fromWinId(pid) win32w.setFlags(Qt.FramelessWindowHint) widg = QWidget.createWindowContainer(win32w) # widget. #widget.setW layout.addWidget(widg) self.setLayout(layout) myProcess.waitForFinished()
def _loop_worker(stream, func, args, buffer_len, kill_signal, show_window=False, pyqt_signal=None): """Call `func(*args)` each time `stream._eeg_data` increases by `buffer_len`. Parameters ---------- stream : rteeg.EEGStream Stream of EEG data or event markers. func : function The function to be called everytime the length of the buffer reaches `buffer_len`. args : tuple Arguments to pass to `func`. buffer_len : int, float The duration of the buffer in seconds. kill_signal If `show_window` is False, `kill_signal` must be threading.Event. If `show_window` is True, `kill_signal` must be QThread method. show_window : bool Whether or not PyQt window is shown. If True, will emit `pyqt_signal` to refresh PyQt window. pyqt_signal : pyqt.QtCore.pyqtSignal Signal which, when emitted, will change text on the PyQt window. """ sleep_time = 0.001 # Time to sleep between buffer_len queries. t_zero = local_clock() if show_window: while not kill_signal: t_one = stream.data[-1][-1] if t_one - t_zero >= buffer_len: t_zero = t_one # Refresh PyQt window with the str that `func` returns. pyqt_signal.emit(func(*args)) time.sleep(sleep_time) else: while not kill_signal.is_set(): t_one = stream.data[-1][-1] if t_one - t_zero >= buffer_len: t_zero = t_one func(*args) time.sleep(sleep_time)
def _extract_from_wiki(self): title = self.title_line_edit.text() if title: page = self.page_combo_box.currentText() wikipedia.set_lang(self.lang_combo_box.currentText()) self.load_progressbar.setMinimum(0) self.load_progressbar.setMaximum(0) class ProgressThread(QThread, QWidget): content_link_arrived = pyqtSignal([list]) content_text_arrived = pyqtSignal(['QString']) content_image_arrived = pyqtSignal([list, 'QString']) error_occurred = pyqtSignal() valid_images = [] def run(self): try: wiki = wikipedia.page(title=title) f = open('templates/template.html') if page == 'Content': self.content_text_arrived.emit(wiki.content) elif page == 'Images': print(wiki.images) self.des_dir = Preferences.output_path + '/' + title self.valid_images = [] if not os.path.exists(self.des_dir): print(self.des_dir) os.mkdir(self.des_dir) for i in wiki.images: if PurePath(i).suffix in Preferences.valid_image_formats: print(i) print(self.des_dir) wget.download(i, out=self.des_dir) self.valid_images.append(i) self.content_image_arrived.emit(self.valid_images, self.des_dir) elif page == 'Summary': self.content_text_arrived.emit(wiki.summary) elif page == 'Images Links': self.content_link_arrived.emit(wiki.images) elif page == 'References Links': self.content_link_arrived.emit(wiki.references) except: self.error_occurred.emit() self.progress_thread = ProgressThread() self.progress_thread.content_link_arrived.connect(self.set_content_link) self.progress_thread.content_text_arrived.connect(self.set_content_text) self.progress_thread.content_image_arrived.connect(self.set_content_image) self.progress_thread.error_occurred.connect(self.handle_error_occurred) self.progress_thread.start() else: self.content_text_browser.clear() self.content_text_browser.setEnabled(False)
def checkupdate(self): """ Initialize a Thread which deals with the update check. UI update is then handled through signals. """ class UpdateCheck(QThread): msignal = pyqtSignal(str) # update message def run(self): """ Threaded code. """ sleep(2) LOG.info('retrieving update data from remote server: %s', URL_B3_LATEST_VERSION) try: jsondata = urllib2.urlopen(URL_B3_LATEST_VERSION, timeout=4).read() versioninfo = json.loads(jsondata) except urllib2.URLError, err: self.msignal.emit('ERROR: could not connect to the update server: %s' % err.reason) LOG.error('could not connect to the update server: %s', err.reason) except IOError, err: self.msignal.emit('ERROR: could not read data: %s' % err) LOG.error('could not read data: %s', err) except Exception, err: self.msignal.emit('ERROR: unknown error: %s' % err) LOG.error('ERROR: unknown error: %s', err) else: self.msignal.emit('parsing data') sleep(1.5) channels = versioninfo['B3']['channels'] if self.parent().channel not in channels: self.msignal.emit('ERROR: unknown channel \'%s\': expecting (%s)' % (self.parent().channel, ', '.join(channels.keys()))) LOG.error('unknown channel \'%s\': expecting (%s)', self.parent().channel, ', '.join(channels.keys())) else: try: latestversion = channels[self.parent().channel]['latest-version'] except KeyError: self.msignal.emit('ERROR: could not get latest B3 version for channel: %s' % self.parent().channel) LOG.error('could not get latest B3 version for channel: %s', self.parent().channel) else: if B3version(b3.__version__) < B3version(latestversion): try: url = versioninfo['B3']['channels'][self.parent().channel]['url'] except KeyError: url = B3_WEBSITE self.msignal.emit('update available: <a href="%s">%s</a>' % (url, latestversion)) LOG.info('update available: %s - %s', url, latestversion) else: self.msignal.emit('no update available') LOG.info('no update available') self.qthread = UpdateCheck(self) self.qthread.msignal.connect(self.update_message) self.qthread.finished.connect(self.finished) self.qthread.start()
def _pyqt4(): # Attempt to set sip API v2 (must be done prior to importing PyQt4) import sip try: sip.setapi("QString", 2) sip.setapi("QVariant", 2) sip.setapi("QDate", 2) sip.setapi("QDateTime", 2) sip.setapi("QTextStream", 2) sip.setapi("QTime", 2) sip.setapi("QUrl", 2) except AttributeError: raise ImportError # PyQt4 < v4.6 except ValueError: # API version already set to v1 raise ImportError import PyQt4.Qt from PyQt4 import QtCore, QtGui, uic _remap(PyQt4, "QtWidgets", QtGui) _remap(QtCore, "Signal", QtCore.pyqtSignal) _remap(QtCore, "Slot", QtCore.pyqtSlot) _remap(QtCore, "Property", QtCore.pyqtProperty) _remap(QtCore, "QItemSelection", QtGui.QItemSelection) _remap(QtCore, "QStringListModel", QtGui.QStringListModel) _remap(QtCore, "QItemSelectionModel", QtGui.QItemSelectionModel) _remap(QtCore, "QSortFilterProxyModel", QtGui.QSortFilterProxyModel) _remap(QtCore, "QAbstractProxyModel", QtGui.QAbstractProxyModel) try: from PyQt4 import QtWebKit _remap(PyQt4, "QtWebKitWidgets", QtWebKit) except ImportError: # QtWebkit is optional in Qt , therefore might not be available pass _add(PyQt4, "QtCompat", self) _add(PyQt4, "__binding__", PyQt4.__name__) _add(PyQt4, "load_ui", lambda fname: uic.loadUi(fname)) _add(PyQt4, "translate", lambda context, sourceText, disambiguation, n: ( QtCore.QCoreApplication(context, sourceText, disambiguation, None, n))) _add(PyQt4, "setSectionResizeMode", QtGui.QHeaderView.setResizeMode) _maintain_backwards_compatibility(PyQt4) return PyQt4
def pyqt4(): # Attempt to set sip API v2 (must be done prior to importing PyQt4) import sip try: sip.setapi("QString", 2) sip.setapi("QVariant", 2) sip.setapi("QDate", 2) sip.setapi("QDateTime", 2) sip.setapi("QTextStream", 2) sip.setapi("QTime", 2) sip.setapi("QUrl", 2) except AttributeError: raise ImportError # PyQt4 < v4.6 except ValueError: # API version already set to v1 raise ImportError import PyQt4.Qt from PyQt4 import QtCore, QtGui, uic remap(PyQt4, "QtWidgets", QtGui) remap(QtCore, "Signal", QtCore.pyqtSignal) remap(QtCore, "Slot", QtCore.pyqtSlot) remap(QtCore, "Property", QtCore.pyqtProperty) remap(QtCore, "QItemSelection", QtGui.QItemSelection) remap(QtCore, "QStringListModel", QtGui.QStringListModel) remap(QtCore, "QItemSelectionModel", QtGui.QItemSelectionModel) remap(QtCore, "QSortFilterProxyModel", QtGui.QSortFilterProxyModel) remap(QtCore, "QAbstractProxyModel", QtGui.QAbstractProxyModel) try: from PyQt4 import QtWebKit remap(PyQt4, "QtWebKitWidgets", QtWebKit) except ImportError: # QtWebkit is optional in Qt , therefore might not be available pass add(PyQt4, "__wrapper_version__", __version__) add(PyQt4, "__binding__", "PyQt4") add(PyQt4, "__binding_version__", QtCore.PYQT_VERSION_STR) add(PyQt4, "__qt_version__", QtCore.QT_VERSION_STR) add(PyQt4, "__added__", __added__) add(PyQt4, "__remapped__", __remapped__) add(PyQt4, "__modified__", __modified__) add(PyQt4, "load_ui", lambda fname: uic.loadUi(fname)) return PyQt4
def _pyqt4(): # Attempt to set sip API v2 (must be done prior to importing PyQt4) import sip try: sip.setapi("QString", 2) sip.setapi("QVariant", 2) sip.setapi("QDate", 2) sip.setapi("QDateTime", 2) sip.setapi("QTextStream", 2) sip.setapi("QTime", 2) sip.setapi("QUrl", 2) except AttributeError: raise ImportError # PyQt4 < v4.6 except ValueError: # API version already set to v1 raise ImportError import PyQt4.Qt from PyQt4 import QtCore, QtGui, uic _remap(PyQt4, "QtWidgets", QtGui) _remap(QtCore, "Signal", QtCore.pyqtSignal) _remap(QtCore, "Slot", QtCore.pyqtSlot) _remap(QtCore, "Property", QtCore.pyqtProperty) _remap(QtCore, "QItemSelection", QtGui.QItemSelection) _remap(QtCore, "QStringListModel", QtGui.QStringListModel) _remap(QtCore, "QItemSelectionModel", QtGui.QItemSelectionModel) _remap(QtCore, "QSortFilterProxyModel", QtGui.QSortFilterProxyModel) _remap(QtCore, "QAbstractProxyModel", QtGui.QAbstractProxyModel) try: from PyQt4 import QtWebKit _remap(PyQt4, "QtWebKitWidgets", QtWebKit) except ImportError: "QtWebkit is optional in Qt , therefore might not be available" _add(QtCompat, "__binding__", PyQt4.__name__) _add(QtCompat, "__binding_version__", PyQt4.QtCore.PYQT_VERSION_STR) _add(QtCompat, "__qt_version__", PyQt4.QtCore.QT_VERSION_STR) _add(QtCompat, "load_ui", lambda fname: uic.loadUi(fname)) _add(QtCompat, "setSectionResizeMode", QtGui.QHeaderView.setResizeMode) # PySide2 differs from Qt4 in that Qt4 has one extra argument # which is always `None`. The lambda arguments represents the PySide2 # interface, whereas the arguments passed to `.translate` represent # those expected of a Qt4 binding. _add(QtCompat, "translate", lambda context, sourceText, disambiguation, n: QtCore.QCoreApplication.translate(context, sourceText, disambiguation, QtCore.QCoreApplication.CodecForTr, n)) _maintain_backwards_compatibility(PyQt4) return PyQt4