代码出错位置是在子线程调用QtWidgets.QMessageBox.question报错的,如下
QObject::setParent: Cannot set parent, new parent is in a different thread
自己查了一下,说是不能在子线程中对UI进行操作,对UI的操作需要在主线程(UI线程)中进行。
那么怎么才能达成想要的询问框呢?
答案是win32api.MessageBox
需要import win32api,win32con
原定义如下:
'''
hWnd:指消息框父窗口句柄,为0或者null,则消息框没有父窗口
lpText:消息框提示的内容
lpCaption:消息框标题
uType:消息框的按钮样式和图标
'''
int MessageBox(HWND hWnd, // handle to owner window
LPCTSTR lpText, // text in message box
LPCTSTR lpCaption, // message box title
UINT uType // message box style
);
uType按钮如下:
MB_OK:默认值,一个确定按钮
MB_OKCANCEL: 确定、取消按钮
MB_YESNO: 是、否按钮
MB_ABORTRETRYIGNORE:终止,重试以及跳过三个按钮
MB_YESNOCANCEL:是,否以及取消三个按钮
MB_RETRYCANCEL:包含重试以及取消两个按钮
返回值判断:
IDYES:点击是
IDNO:点击否
IDOK:点击确认
IDCANCE:点击取消
IDABORT:点击终止
IDRETRY:点击重试
IDIGNORE:点击忽略
图标提示(可选择加该提示):
MB_ICONINFORMATION:蓝色i
MB_ICONASTERISK:蓝色i
MB_ICONQUESTION:蓝色?
MB_ICONWARNING:黄色!
MB_ICONEXCLAMATION:黄色!
MB_ICONSTOP:红色x
MB_ICONERROR:红色x
MB_ICONHAND:红色x
测试样例:
import win32con,win32api
if __name__ == '__main__':
reply = win32api.MessageBox(0, "hello world", "提示",
win32con.MB_YESNO | win32con.MB_ICONINFORMATION)
# reply = win32api.MessageBox(0, "hello world", "提示", win32con.MB_YESNO) 无图标提示
if reply == win32con.IDYES:
print("touch yes")
if reply == win32con.IDNO:
print("touch no")
结果如下:
点击【是(Y)】按钮窗口打印touch yes