python - PySide 使 QDialog 出现在主窗口中

标签 python qt pyqt pyside

我创建了一个应用程序,它有一个主窗口并且可以打开一个对话框(问题、错误等)。我没有使用 QMessageBox.warning()QMessageBox.question() 等,因为我想稍微自定义一下对话框。

但是每次我打开一个新对话框时,Windows 任务栏中(我使用的是 Windows 10)都会打开一个新的“选项卡”,这有点烦人。

enter image description here

我的代码(缩短):

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_())

注意:通常,该对话框是从菜单或按钮调用的。

问题:如何使对话框出现在主窗口中而不创建新的“任务栏选项卡”?

最佳答案

解决方案非常简单:将QMainWindow的引用传递给QDialog的构造函数即可完成工作,例如:

class MessageBox(QtGui.QDialog):
    def __init__(self, parent, title, message, icon="info"):
        super(MessageBox, self).__init__(parent)
        ...

然后从继承自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)

也许这对任何人都有帮助!

关于python - PySide 使 QDialog 出现在主窗口中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36340134/

相关文章:

python - 按字母顺序对 .txt 文件进行排序时出现问题(删除了一行)?

block 内的 python 异常处理

python - 将 Python 中的 float 转换为科学数字

c++ - 从 QGLPixelBuffer 获取深度缓冲区

python - 如何检查当前窗口中是否打开了上下文菜单或下拉列表?

python - pyqt Qtextbrowser 更新

python - 如何删除 pyside/pyqt 中 ui 组件的属性?

python - 如何在根据目标地址发送消息之前确定源地址?

c++ - 用于散点图的排序浮点 vector (C++/QCustomPlot)

python - 确定 PyQt 是否在 Maya 中运行