【问题标题】:PySide make QDialog appear in main windowPySide 使 QDialog 出现在主窗口中
【发布时间】:2016-03-31 17:40:07
【问题描述】:

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

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

我的代码(缩短):

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

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

问题:如何在不创建新的“任务栏标签”的情况下使对话框出现在主窗口中?

【问题讨论】:

  • 看到这个stackoverflow.com/a/9043996/4941927,可以帮助你
  • @Milor123 谢谢,我已经这样做了。该按钮使用self.mybutton.clicked.connect(self.myfunc) 连接。在myfunc 中,使用MessageBox("Title", "My message here") 调用对话框。有什么想法吗?
  • 除了创建一个类并在构造函数中完成所有工作没有多大意义之外(要么继承以扩展类,还是只创建一个函数?),您应该将新对话框的父级正确设置为主对话框,以使焦点和窗口分组正常工作。
  • @MatteoItalia 正如我所写,在我的真实代码中,对话框是从另一个函数调用的。我前段时间尝试设置父级,但这不起作用。你能告诉我如何设置QDialog 的父级吗?

标签: python qt pyqt pyside


【解决方案1】:

解决方案非常简单:将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)

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

【讨论】:

  • 你为什么复制我的答案?
【解决方案2】:

如果您将QDialog 的父级设置为窗口,它只会在任务栏上显示为一项。这通常是QMessageBox 的第一个参数。

class MessageBox:
    def __init__(self, parent, title, message):
        msg = QtGui.QMessageBox(parent)

另外,如果你真的想创建一个自定义对话框,你不妨从QDialog 继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2012-02-21
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多