PyQt:如何防止窗口被多次打开

4

我写了以下简单的代码作为示例。它只是在点击按钮时打开一个新窗口。如果这个窗口已经存在于屏幕上,我找不到防止它重新打开的方法。我想要在窗口已经存在的情况下打开一个QDialog警告,并且主要是通过closeEvent方法向Mainwidget发送信号,说明新窗口已关闭。这将允许再次打开newWidget。

import sys
from PyQt4 import QtCore, QtGui

class NewWidget(QtGui.QWidget): 
    def __init__(self, parent=None):
        super(NewWidget,self).__init__(parent)

        self.lineEdit = QtGui.QLineEdit('new window',self)
        self.resize(200,50)
        self.show()

    def closeEvent(self,ev):

        self.Exit = QtGui.QMessageBox.question(self,
                  "Confirm Exit...",
                  "Are you sure you want to exit ?",
                  QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)
        ev.ignore()

        if self.Exit  == QtGui.QMessageBox.Yes:            
            ev.accept()     

class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MainWidget,self).__init__(parent)

        self.button = QtGui.QPushButton("button", self)
        self.button.clicked.connect(self.open_new)

    def open_new(self):

        self.new = NewWidget()

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    main = MainWidget()
    main.resize(200,50)
    main.move(app.desktop().screen().rect().center() - main.rect().center())
    main.show()
    sys.exit(app.exec_())
2个回答

4

我认为更好的解决方案是避免每次单击按钮时创建新窗口。

一个方法是将子窗口更改为QDialog:

class NewWidget(QtGui.QDialog):
...

将调整大小/显示行移动到open_new方法中:

class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        ...
        self._subwindow = None

    def open_new(self):
        if self._subwindow is None:
            self._subwindow = NewWidget(self)
            self._subwindow.resize(200, 50)
            # move it next to the main window
            pos = self.frameGeometry().topLeft()
            self._subwindow.move(pos.x() - 250, pos.y())
        self._subwindow.show()
        self._subwindow.activateWindow()

现在只有一个子窗口,每次按按钮时都会重新激活它。


3
太好了。我的问题的最终解决方案如下:
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
    ...
    self._subwindow = QtGui.Qdialog()

def open_new(self):
    if self.subwindow.isVisible() is False:
        self._subwindow = NewWidget(self)
        self._subwindow.resize(200, 50)
        # move it next to the main window
        pos = self.frameGeometry().topLeft()
        self._subwindow.move(pos.x() - 250, pos.y())
    self._subwindow.show()
    self._subwindow.activateWindow()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接