我最近没有做太多Qt开发,但如果我没记错的话,你可以在自己的事件循环中调用QApplication::processEvents()(而不是通过QApplication::exec()启动Qt主循环)
编辑:我利用一个缓慢的周日早晨的机会来试驾/了解PyQt(Qt 的 Python 绑定)并在下面拼凑出一个概念验证代码.用基于QApplication::processEvents() 的自定义事件循环替换对QApplication::exec() 的调用似乎可以工作。
我还快速查看了simpleeventloop.cpp 和tpclient-cpptext main.cpp。从外观上看,在SimpleEventLoop::runEventLoop() 的主循环中的某处添加QApplication::processEvents() 应该没问题。要将其添加到主循环中,我可能会将lines 106 through 117 中select() 函数的tv 间隔替换为
tv.tv_sec = 0;
tv.tv_usec = 10000; // run processEvents() every 0.01 seconds
app->processEvents();
并将line 89 中的签名更改为void SimpleEventLoop::runEventLoop(QApplication *app)。将您常用的 Qt 内容添加到您的客户端实现中应该没问题(您替换 tpclient-cpptext main.cpp)
不过,看起来像个 hack。我可能会从这样的事情开始。我认为您将TPSocket 和计时器包装在Qt 各自概念中以便将它们与QAbstractEventDispatcher 一起转发到QEventLoop 的想法是更好的长期解决方案。那么您的runEventLoop() 只需调用QApplication::exec() 就足够了。但我之前从未使用过QAbstractEventDispatcher,所以请以我的 cmets 为准。
import sys
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
# Global variable used as a quick and dirty way to notify my
# main event loop that the MainWindow has been exited
APP_RUNNING = False
class SampleMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self)
global APP_RUNNING
APP_RUNNING = True
# main window
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Test')
self.statusBar().showMessage('Ready')
# exit action (assumes that the exit icon from
# http://upload.wikimedia.org/wikipedia/commons/b/bc/Exit.png
# is saved as Exit.png in the same folder as this file)
exitAction = QtGui.QAction(QtGui.QIcon('Exit.png')
,'Exit'
,self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
self.connect(exitAction
,QtCore.SIGNAL('triggered()')
,QtCore.SLOT('close()'))
# main menu
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
# toolbar
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
# text editor
textEdit = QtGui.QTextEdit()
self.setCentralWidget(textEdit)
#tool tip
textEdit.setToolTip('Enter some text')
QtGui.QToolTip.setFont(QtGui.QFont('English', 12))
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self
,'Message'
,"Are you sure?"
,QtGui.QMessageBox.Yes
,QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
global APP_RUNNING
APP_RUNNING = False
else:
event.ignore()
# main program
app = QtGui.QApplication(sys.argv)
testWindow = SampleMainWindow()
testWindow.show()
# run custom event loop instead of app.exec_()
while APP_RUNNING:
app.processEvents()
# sleep to prevent that my "great" event loop eats 100% cpu
time.sleep(0.01)