本文整理汇总了Python中PyQt5.QtCore.QEventLoop.exec_方法的典型用法代码示例。如果您正苦于以下问题:Python QEventLoop.exec_方法的具体用法?Python QEventLoop.exec_怎么用?Python QEventLoop.exec_使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QEventLoop
的用法示例。
在下文中一共展示了QEventLoop.exec_方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MatrixDialog
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
class MatrixDialog(WindowModalDialog):
def __init__(self, parent):
super(MatrixDialog, self).__init__(parent)
self.setWindowTitle(_("Trezor Matrix Recovery"))
self.num = 9
self.loop = QEventLoop()
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(MATRIX_RECOVERY))
grid = QGridLayout()
grid.setSpacing(0)
self.char_buttons = []
for y in range(3):
for x in range(3):
button = QPushButton('?')
button.clicked.connect(partial(self.process_key, ord('1') + y * 3 + x))
grid.addWidget(button, 3 - y, x)
self.char_buttons.append(button)
vbox.addLayout(grid)
self.backspace_button = QPushButton("<=")
self.backspace_button.clicked.connect(partial(self.process_key, Qt.Key_Backspace))
self.cancel_button = QPushButton(_("Cancel"))
self.cancel_button.clicked.connect(partial(self.process_key, Qt.Key_Escape))
buttons = Buttons(self.backspace_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
for y in range(3):
self.char_buttons[3 * y + 1].setEnabled(self.num == 9)
def is_valid(self, key):
return key >= ord('1') and key <= ord('9')
def process_key(self, key):
self.data = None
if key == Qt.Key_Backspace:
self.data = '\010'
elif key == Qt.Key_Escape:
self.data = 'x'
elif self.is_valid(key):
self.char_buttons[key - ord('1')].setFocus()
self.data = '%c' % key
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_matrix(self, num):
self.num = num
self.refresh()
self.loop.exec_()
示例2: f2
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def f2():
future = ac.start(em2.g, lambda x: x, QThread.currentThread())
# The doneSignal won't be processed without an event loop. A
# thread pool doesn't create one, so make our own to run ``g``.
qe = QEventLoop()
future._signalInvoker.doneSignal.connect(qe.exit)
qe.exec_()
示例3: waitForSignal
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def waitForSignal(signal, message="", timeout=0):
"""Waits (max timeout msecs if given) for a signal to be emitted.
It the waiting lasts more than 2 seconds, a progress dialog is displayed
with the message.
Returns True if the signal was emitted.
Return False if the wait timed out or the dialog was canceled by the user.
"""
loop = QEventLoop()
dlg = QProgressDialog(minimum=0, maximum=0, labelText=message)
dlg.setWindowTitle(appinfo.appname)
dlg.setWindowModality(Qt.ApplicationModal)
QTimer.singleShot(2000, dlg.show)
dlg.canceled.connect(loop.quit)
if timeout:
QTimer.singleShot(timeout, dlg.cancel)
stop = lambda: loop.quit()
signal.connect(stop)
loop.exec_()
signal.disconnect(stop)
dlg.hide()
dlg.deleteLater()
return not dlg.wasCanceled()
示例4: _processPendingEvents
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def _processPendingEvents():
"""Process pending application events."""
# Create an event loop to run in. Otherwise, we need to use the
# QApplication main loop, which may already be running and therefore
# unusable.
qe = QEventLoop()
# Create a single-shot timer. Could use QTimer.singleShot(),
# but can't cancel this / disconnect it.
timer = QTimer()
timer.setSingleShot(True)
timer.timeout.connect(qe.quit)
timer.start(1)
# Wait for an emitted signal.
qe.exec_()
# Clean up: don't allow the timer to call qe.quit after this
# function exits, which would produce "interesting" behavior.
timer.stop()
# Stopping the timer may not cancel timeout signals in the
# event queue. Disconnect the signal to be sure that loop
# will never receive a timeout after the function exits.
timer.timeout.disconnect(qe.quit)
示例5: AppDecorator
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
class AppDecorator(QObject):
documentWasCreatedSignal = pyqtSignal(object) # doc
documentWindowWasCreatedSignal = pyqtSignal(object, object) # doc, window
def __init__(self,argv):
self.qApp = QApplication(argv)
super(AppDecorator, self).__init__()
from cadnano.gui.views.preferences import Preferences
self.prefs = Preferences()
#icon = QIcon(ICON_PATH)
#self.qApp.setWindowIcon(icon)
self.document_controllers = set() # Open documents
self.active_document = None
self.vh = {} # Newly created VirtualHelix register here by idnum.
self.vhi = {}
self.partItem = None
global decode
global Document
global DocumentController
from cadnano.gui.views.pathview import pathstyles as styles
styles.setFontMetrics()
# def prefsClicked(self):
# self.prefs.showDialog()
def exec_(self):
if hasattr(self, 'qApp'):
mainWindow = MainWindow()
mainWindow.show()
self.mainEventLoop = QEventLoop()
self.mainEventLoop.exec_()
示例6: send
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def send(params):
url = self.formatUrl(endpoint, params)
request = QNetworkRequest(url)
headers['User-Agent'] = 'Divi QGIS Plugin/%s' % PLUGIN_VERSION
QgsMessageLog.logMessage(str(headers), 'DIVI')
for key, value in headers.items():
request.setRawHeader(key.encode('utf-8'), value.encode('utf-8'))
if method == 'delete':
reply = manager.sendCustomRequest(request, 'DELETE'.encode('utf-8'), data)
else:
if not data:
reply = getattr(manager, method)(request)
elif isinstance(data, QHttpMultiPart) == True:
reply = getattr(manager, method)(request, data)
elif isinstance(data, str) == True:
reply = getattr(manager, method)(request, data.encode('utf-8'))
loop = QEventLoop()
reply.uploadProgress.connect(self.uploadProgress)
reply.downloadProgress.connect(self.downloadProgress)
reply.metaDataChanged.connect(self.metaDataChanged)
#reply.error.connect(self._error)
reply.finished.connect(loop.exit)
self.abort_sig.connect( reply.abort )
loop.exec_()
self.abort_sig.disconnect( reply.abort )
return reply
示例7: __init__
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
class CallbackFuture:
def __init__(self,
# A CallbackManager instance to register with.
callbackManager,
# _`callbackToWrap`: The callback function to (optionally) invoke, which this future will wrap.
callbackToWrap):
self.callbackManager = callbackManager
self._callbackToWrap = callbackToWrap
self._state = CallbackFutureState.READY
self._shouldInvokeCallback = True
self._qEventLoop = None
# Return the callback wrapper for this future and mark it as waiting.
def callback(self):
assert self._state == CallbackFutureState.READY, 'A callback may only be obtained once.'
self._state = CallbackFutureState.WAITING
self.callbackManager.add(self)
return self._callbackWrapper
# The callback wrapper. Update state, then invoke the wrapped callback.
def _callbackWrapper(self, *args, **kwargs):
assert self._state == CallbackFutureState.WAITING
self._state = CallbackFutureState.COMPLETE
self.callbackManager.remove(self)
# If waiting for the callback, stop!
if self._qEventLoop:
self._qEventLoop.quit()
if self._shouldInvokeCallback:
self._callbackToWrap(*args, **kwargs)
def skipCallback(self):
assert self._state == CallbackFutureState.WAITING, 'Only callbacks being waited for may be skipped.'
self._shouldInvokeCallback = False
# Wait until the wrapped callback is completed (invoked or skipped).
def waitForCallback(self):
assert self._state == CallbackFutureState.WAITING, 'Only callbacks being waited for may be skipped.'
# Run events until the callback is invoked.
self._qEventLoop = QEventLoop()
self._qEventLoop.exec_()
self._qEventLoop = None
assert self._state == CallbackFutureState.COMPLETE
示例8: terminate
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def terminate(self):
# Only run this once.
if self._isAlive:
self._isAlive = False
self._terminate()
# Waiting for the thread or thread pool to shut down may have
# placed completed jobs in this thread's queue. Process them now to
# avoid any surprises (terminated `_AsyncAbstractController`_
# instances still invoke callbacks, making it seem that the
# terminate didn't fully terminate. It did, but still leaves g_
# callbacks to be run in the event queue.)
el = QEventLoop(self.parent())
QTimer.singleShot(0, el.exit)
el.exec_()
# Delete the `QObject <http://doc.qt.io/qt-5/qobject.html>`_
# underlying this class, which disconnects all signals.
sip.delete(self)
示例9: __execJavaScript
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def __execJavaScript(self, script):
"""
Private function to execute a JavaScript function Synchroneously.
@param script JavaScript script source to be executed
@type str
@return result of the script
@rtype depending upon script result
"""
from PyQt5.QtCore import QEventLoop
loop = QEventLoop()
resultDict = {"res": None}
def resultCallback(res, resDict=resultDict):
if loop and loop.isRunning():
resDict["res"] = res
loop.quit()
self.previewView.page().runJavaScript(
script, resultCallback)
loop.exec_()
return resultDict["res"]
示例10: CadnanoQt
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
#.........这里部分代码省略.........
if self.argns.interactive:
print("Welcome to cadnano's debug mode!")
print("Some handy locals:")
print("\ta\tcadnano.app() (the shared cadnano application object)")
print("\td()\tthe last created Document")
def d():
return self._document
print("\tw()\tshortcut for d().controller().window()")
def w():
return self._document.controller().window()
print("\tp()\tshortcut for d().selectedInstance().reference()")
def p():
return self._document.selectedInstance().reference()
print("\tpi()\tthe PartItem displaying p()")
def pi():
part_instance = self._document.selectedInstance()
return w().pathroot.partItemForPart(part_instance)
print("\tvh(i)\tshortcut for p().reference().getStrandSets(i)")
def strandsets(id_num):
return p().reference().getStrandSets(id_num)
print("\tvhi(i)\tvirtualHelixItem displaying vh(i)")
def vhi(id_num):
partitem = pi()
return partitem.vhItemForIdNum(id_num)
print("\tquit()\tquit (for when the menu fails)")
print("\tgraphicsItm.findChild() see help(pi().findChild)")
interact('', local={'a': self, 'd': d, 'w': w,
'p': p, 'pi': pi, 'vhi': vhi,
})
# end def
def exec_(self):
if hasattr(self, 'qApp'):
self.main_event_loop = QEventLoop()
self.main_event_loop.exec_()
def destroyApp(self):
""" Destroy the QApplication.
Do not set `self.qApp = None` in this method.
Do it external to the CadnanoQt class
"""
global decodeFile
global Document
global DocumentController
# print("documentWasCreatedSignal", self.documentWasCreatedSignal)
if self.document_controllers:
self.documentWasCreatedSignal.disconnect(self.wirePrefsSlot)
decodeFile = None
Document = None
DocumentController = None
self.document_controllers.clear()
self.qApp.quit()
# end def
def ignoreEnv(self):
return os.environ.get('CADNANO_IGNORE_ENV_VARS_EXCEPT_FOR_ME', False)
def createDocument(self, base_doc=None):
global DocumentController
# print("CadnanoQt createDocument begin")
default_file = self.argns.file or os.environ.get('CADNANO_DEFAULT_DOCUMENT', None)
if default_file is not None and base_doc is not None:
default_file = os.path.expanduser(default_file)
default_file = os.path.expandvars(default_file)
dc = DocumentController(base_doc)
# logger.info("Loading cadnano file %s to base document %s", default_file, base_doc)
decodeFile(default_file, document=base_doc)
dc.setFileName(default_file)
print("Loaded default document: %s" % (default_file))
else:
doc_ctrlr_count = len(self.document_controllers)
# logger.info("Creating new empty document...")
if doc_ctrlr_count == 0: # first dc
# dc adds itself to app.document_controllers
dc = DocumentController(base_doc)
elif doc_ctrlr_count == 1: # dc already exists
dc = list(self.document_controllers)[0]
dc.newDocument() # tell it to make a new doucment
# print("CadnanoQt createDocument done")
return dc.document()
def prefsClicked(self):
self.prefs.showDialog()
def wirePrefsSlot(self, document):
self.prefs.document = document
示例11: CadnanoQt
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
class CadnanoQt(QObject):
dontAskAndJustDiscardUnsavedChanges = False
documentWasCreatedSignal = pyqtSignal(object) # doc
documentWindowWasCreatedSignal = pyqtSignal(object, object) # doc, window
def __init__(self, argv):
"""Create the application object
"""
self.argns, unused = util.parse_args(argv, use_gui=True)
# util.init_logging(self.argns.__dict__)
# logger.info("CadnanoQt initializing...")
if argv is None:
argv = sys.argv
self.argv = argv
# print("initializing new CadnanoQt", type(QCoreApplication.instance()))
if QCoreApplication.instance() is None:
self.qApp = QApplication(argv)
assert(QCoreApplication.instance() is not None)
self.qApp.setOrganizationDomain("cadnano.org")
else:
self.qApp = qApp
super(CadnanoQt, self).__init__()
# print("initialized new CadnanoQt")
from cadnano.views.preferences import Preferences
self.prefs = Preferences()
self.icon = icon = QIcon(ICON_PATH1)
icon.addFile(ICON_PATH2, QSize(256, 256))
icon.addFile(ICON_PATH3, QSize(48, 48))
self.qApp.setWindowIcon(icon)
self.main_event_loop = None
self.cnmain_windows: set = set() # Open documents
self.active_document = None
self._document = None
self.documentWasCreatedSignal.connect(self.wirePrefsSlot)
# end def
def document(self) -> DocT:
return self._document
# end def
def finishInit(self):
global decodeFile
global Document
global CNMainWindow
from cadnano.document import Document
from cadnano.fileio.decode import decodeFile
from cadnano.views.cnmainwindow import CNMainWindow
from cadnano.views.pathview import pathstyles as styles
styles.setFontMetrics()
doc = Document()
self._document = self.createDocument(base_doc=doc)
if os.environ.get('CADNANO_DISCARD_UNSAVED', False) and not self.ignoreEnv():
self.dontAskAndJustDiscardUnsavedChanges = True
self.dontAskAndJustDiscardUnsavedChanges = True
# end def
def exec_(self):
if hasattr(self, 'qApp'):
self.main_event_loop = QEventLoop()
self.main_event_loop.exec_()
def destroyApp(self):
"""Destroy the QApplication.
Do not set `self.qApp = None` in this method.
Do it external to the CadnanoQt class
"""
global decodeFile
global Document
global CNMainWindow
# print("documentWasCreatedSignal", self.documentWasCreatedSignal)
if len(self.cnmain_windows) > 0:
self.documentWasCreatedSignal.disconnect(self.wirePrefsSlot)
decodeFile = None
Document = None
CNMainWindow = None
self.cnmain_windows.clear()
self.qApp.quit()
# end def
def ignoreEnv(self):
return os.environ.get('CADNANO_IGNORE_ENV_VARS_EXCEPT_FOR_ME', False)
def createDocument(self, base_doc: DocT = None):
global CNMainWindow
# print("CadnanoQt createDocument begin")
default_file = self.argns.file or os.environ.get('CADNANO_DEFAULT_DOCUMENT', None)
if default_file is not None and base_doc is not None:
default_file = os.path.expanduser(default_file)
default_file = os.path.expandvars(default_file)
dw = CNMainWindow(base_doc)
self.cnmain_windows.add(dw)
# logger.info("Loading cadnano file %s to base document %s", default_file, base_doc)
decodeFile(default_file, document=base_doc)
dw.setFileName(default_file)
print("Loaded default document: %s" % (default_file))
else:
#.........这里部分代码省略.........
示例12: ConverterThread
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
#.........这里部分代码省略.........
core.config()['Sphinx']['OutputPath']]
# Invoke it.
try:
# Clear the log at the beginning of a Sphinx build.
self.logWindowClear.emit()
cwd = core.config()['Sphinx']['ProjectPath']
# If the command line is already a string (advanced mode), just print it.
# Otherwise, it's a list that should be transformed to a string.
if isinstance(htmlBuilderCommandLine, str):
htmlBuilderCommandLineStr = htmlBuilderCommandLine
else:
htmlBuilderCommandLineStr = ' '.join(htmlBuilderCommandLine)
self.logWindowText.emit('{} : {}\n\n'.format(cwd,
htmlBuilderCommandLineStr))
# Run Sphinx, reading stdout in a separate thread.
self._qe = QEventLoop()
# Sphinx will output just a carriage return (0x0D) to simulate a
# single line being updated by build status and the build
# progresses. Without universal newline support here, we'll wait
# until the build is complete (with a \n\r) to report any build
# progress! So, enable universal newlines, so that each \r will be
# treated as a separate line, providing immediate feedback on build
# progress.
popen = open_console_output(htmlBuilderCommandLine, cwd=cwd,
universal_newlines=True)
# Perform reads in an event loop. The loop is exit when all reads
# have completed. We can't simply start the _stderr_read thread
# here, because calls to self._qe_exit() will be ignored until
# we're inside the event loop.
QTimer.singleShot(0, lambda: self._popen_read(popen))
self._qe.exec_()
except OSError as ex:
return (
'Failed to execute HTML builder:\n'
'{}\n'.format(str(ex)) +
'Go to Settings -> Settings -> CodeChat to set HTML'
' builder configurations.')
return self._stderr
# Read from stdout (in this thread) and stderr (in another thread),
# so that the user sees output as the build progresses, rather than only
# producing output after the build is complete.
def _popen_read(self, popen):
# Read are blocking; we can't read from both stdout and stderr in the
# same thread without possible buffer overflows. So, use this thread to
# read from and immediately report progress from stdout. In another
# thread, read all stderr and report that after the build finishes.
self._ac.start(None, self._stderr_read, popen.stderr)
# Read a line of stdout then report it to the user immediately.
s = popen.stdout.readline()
while s:
self.logWindowText.emit(s.rstrip('\n'))
s = popen.stdout.readline()
self._SphinxInvocationCount += 1
# I would expect the following code to do the same thing. It doesn't:
# instead, it waits until Sphinx completes before returning anything.
# ???
#
# .. code-block: python
# :linenos:
#
示例13: Kiwoom
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
#.........这里部分代码省略.........
data.append(value)
# TODO: DB에 저장
self.log.debug(data)
except Exception as e:
self.log.error('{}'.format(e))
def on_receive_chejan_data(self, gubun, item_cnt, fid_list):
print("gubun: ", gubun)
print(self.GetChejanData(9203))
print(self.GetChejanData(302))
print(self.GetChejanData(900))
print(self.GetChejanData(901))
def get_codelist_by_market(self, market):
func = 'GetCodeListByMarket("%s")' % market
codes = self.dynamicCall(func)
return codes.split(';')
###############################################################
# 메서드 정의: 로그인 관련 메서드 #
###############################################################
def comm_connect(self):
"""
로그인을 시도합니다.
수동 로그인일 경우, 로그인창을 출력해서 로그인을 시도.
자동 로그인일 경우, 로그인창 출력없이 로그인 시도.
"""
self.dynamicCall("CommConnect()")
self.login_loop = QEventLoop()
self.login_loop.exec_()
def get_connect_state(self):
"""
현재 접속상태를 반환합니다.
반환되는 접속상태는 아래와 같습니다.
0: 미연결, 1: 연결
:return: int
"""
ret = self.dynamicCall("GetConnectState()")
return ret
def get_login_info(self, tag, is_connect_state=False):
"""
사용자의 tag에 해당하는 정보를 반환한다.
tag에 올 수 있는 값은 아래와 같다.
ACCOUNT_CNT: 전체 계좌의 개수를 반환한다.
ACCNO: 전체 계좌 목록을 반환한다. 계좌별 구분은 ;(세미콜론) 이다.
USER_ID: 사용자 ID를 반환한다.
USER_NAME: 사용자명을 반환한다.
GetServerGubun: 접속서버 구분을 반환합니다.(0: 모의투자, 그외: 실서버)
:param tag: string
:param is_connect_state: bool - 접속상태을 확인할 필요가 없는 경우 True로 설정.
:return: string
"""
if not is_connect_state:
if not self.get_connect_state():
raise KiwoomConnectError()
示例14: Kiwoom
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
#.........这里部分代码省略.........
"""
주문 접수/확인 수신시 이벤트
주문요청후 주문접수, 체결통보, 잔고통보를 수신할 때 마다 호출됩니다.
:param gubun: string - 체결구분('0': 주문접수/주문체결, '1': 잔고통보, '3': 특이신호)
:param itemCnt: int - fid의 갯수
:param fidList: string - fidList 구분은 ;(세미콜론) 이다.
"""
fids = fidList.split(';')
print("[receiveChejanData]")
print("gubun: ", gubun, "itemCnt: ", itemCnt, "fidList: ", fidList)
print("========================================")
print("[ 구분: ", self.getChejanData(913) if '913' in fids else '잔고통보', "]")
for fid in fids:
print(FidList.CHEJAN[int(fid)] if int(fid) in FidList.CHEJAN else fid, ": ", self.getChejanData(int(fid)))
print("========================================")
###############################################################
# 메서드 정의: 로그인 관련 메서드 #
###############################################################
def commConnect(self):
"""
로그인을 시도합니다.
수동 로그인일 경우, 로그인창을 출력해서 로그인을 시도.
자동 로그인일 경우, 로그인창 출력없이 로그인 시도.
"""
self.dynamicCall("CommConnect()")
self.loginLoop = QEventLoop()
self.loginLoop.exec_()
def getConnectState(self):
"""
현재 접속상태를 반환합니다.
반환되는 접속상태는 아래와 같습니다.
0: 미연결, 1: 연결
:return: int
"""
state = self.dynamicCall("GetConnectState()")
return state
def getLoginInfo(self, tag, isConnectState=False):
"""
사용자의 tag에 해당하는 정보를 반환한다.
tag에 올 수 있는 값은 아래와 같다.
ACCOUNT_CNT: 전체 계좌의 개수를 반환한다.
ACCNO: 전체 계좌 목록을 반환한다. 계좌별 구분은 ;(세미콜론) 이다.
USER_ID: 사용자 ID를 반환한다.
USER_NAME: 사용자명을 반환한다.
GetServerGubun: 접속서버 구분을 반환합니다.("1": 모의투자, 그외(빈 문자열포함): 실서버)
:param tag: string
:param isConnectState: bool - 접속상태을 확인할 필요가 없는 경우 True로 설정.
:return: string
"""
if not isConnectState:
if not self.getConnectState():
示例15: waitForSignal
# 需要导入模块: from PyQt5.QtCore import QEventLoop [as 别名]
# 或者: from PyQt5.QtCore.QEventLoop import exec_ [as 别名]
def waitForSignal(sender, senderSignal, timeoutMs, expectedSignalParams=None):
""" Wait up to timeoutMs after calling sender() for senderSignal
to be emitted.
It returns True if the senderSignal was emitted; otherwise,
it returns False. If expectedSignalParams is not None, it
is compared against the parameters emitted by the senderSignal.
This function was inspired by http://stackoverflow.com/questions/2629055/qtestlib-qnetworkrequest-not-executed/2630114#2630114.
"""
# Create a single-shot timer. Could use QTimer.singleShot(),
# but can't cancel this / disconnect it.
timer = QTimer()
timer.setSingleShot(True)
# Create an event loop to run in. Otherwise, we need to use the
# QApplication main loop, which may already be running and therefore
# unusable.
qe = QEventLoop()
# Create a slot which receives a senderSignal with any number
# of arguments. Check the arguments against their expected
# values, if requested, storing the result in senderSignalArgsWrong[0].
# (I can't use senderSignalArgsWrong = True/False, since
# non-local variables cannot be assigned in another scope).
senderSignalArgsWrong = []
def senderSignalSlot(*args):
# If the senderSignal args should be checked and they
# don't match, then they're wrong. In all other cases,
# they're right.
senderSignalArgsWrong.append(
(expectedSignalParams is not None) and
(expectedSignalParams != args))
# We received the requested signal, so exit the event loop.
qe.exit()
# Connect both signals to a slot which quits the event loop.
senderSignal.connect(senderSignalSlot)
timer.timeout.connect(qe.quit)
# Start the sender and the timer and at the beginning of the event loop.
# Just calling sender() may cause signals emitted in sender
# not to reach their connected slots.
QTimer.singleShot(0, sender)
timer.start(timeoutMs)
# Catch any exceptions which the EventLoop would otherwise catch
# and not re-raise.
exceptions = []
def excepthook(type_, value, tracebackObj):
exceptions.append((value, tracebackObj))
oldExcHook = sys.excepthook
sys.excepthook = excepthook
# Wait for an emitted signal.
qe.exec_()
# If an exception occurred in the event loop, re-raise it.
if exceptions:
value, tracebackObj = exceptions[0]
raise value.with_traceback(tracebackObj)
# Clean up: don't allow the timer to call app.quit after this
# function exits, which would produce "interesting" behavior.
ret = timer.isActive()
timer.stop()
# Stopping the timer may not cancel timeout signals in the
# event queue. Disconnect the signal to be sure that loop
# will never receive a timeout after the function exits.
# Likewise, disconnect the senderSignal for the same reason.
senderSignal.disconnect(senderSignalSlot)
timer.timeout.disconnect(qe.quit)
# Restore the old exception hook
sys.excepthook = oldExcHook
return ret and senderSignalArgsWrong and (not senderSignalArgsWrong[0])