PySide 使 QDialog 出现在主窗口中 [英] PySide make QDialog appear in main window
问题描述
我创建了一个应用程序,它有一个主窗口并且可以打开一个对话框(问题、错误等).我没有使用 QMessageBox.warning()
或 QMessageBox.question()
等等,因为我想稍微自定义一下对话框.
I've created an app which has an main window and the possibility to open an dialog (question, error and so on). I'm not using QMessageBox.warning()
or QMessageBox.question()
and so on because I wanted to customize the dialogs a bit.
但是每次我打开一个新对话框时,都会在 Windows 任务栏中(我使用的是 Windows 10)打开一个新的选项卡",这有点烦人.
But every time I open a new Dialog, in the Windows task bar (I'm working on Windows 10) a new 'tab' is opened, which is a little bit annoying.
我的代码(缩短):
from PySide import QtCore, QtGui
import sys
class MessageBox:
def __init__(self, title, message):
msg = QtGui.QMessageBox()
flags = QtCore.Qt.Dialog
flags |= QtCore.Qt.CustomizeWindowHint
flags |= QtCore.Qt.WindowTitleHint
msg.setWindowFlags(flags)
msg.setWindowTitle(title)
msg.setText(message)
msg.exec_()
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.show()
MessageBox("Title", "My message here")
if __name__ == "__main__":
app = QtGui.QApplication([])
window = MainWindow()
sys.exit(app.exec_())
注意:通常,对话框是从菜单或按钮调用的.
Note: Normally, the dialog is called from an menu or button.
问题:如何在不创建新的任务栏选项卡"的情况下使对话框出现在主窗口中?
Question: How can I make the dialog appear in the main window without creating a new 'task bar tab'?
推荐答案
解决方案非常简单:将 QMainWindow
的引用传递给 QDialog
的构造函数即可完成工作,例如:
The solution was quite simple: Passing an reference of QMainWindow
to the constructor of QDialog
will do the job, e.g:
class MessageBox(QtGui.QDialog):
def __init__(self, parent, title, message, icon="info"):
super(MessageBox, self).__init__(parent)
...
然后从继承自 QMainWindow
的类调用对话框:
and then calling the dialog from an class that inherits from QMainWindow
:
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
#connect button with function, e.g.:
mybutton.clicked.connect(self.open_dialog)
def open_dialog(self):
MessageBox(self)
也许这对任何人都有帮助!
Maybe this helps anyone!
这篇关于PySide 使 QDialog 出现在主窗口中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!