簡體   English   中英

來自主要Gui模塊外部的PyQt5中斷關閉事件

[英]PyQt5 Interrupt Close Event from Outside the Main Gui Module

我使用Qt Designer構建我的GUI,並使用pyuic5將它們轉換為py文件。 我的最終目標是在變量== 1時中斷用戶關閉程序,並向他們顯示“您確定要關閉嗎?” 鍵入對話框。 如果所述變量== 0,則只需正常關閉程序即可。

我已經看到了許多有關如何執行此操作的示例,但是所有這些示例都需要在GUI模塊中編輯代碼。 我將pyuic5創建的gui.py文件導入到我的主腳本中,在該腳本中我完成了對按鈕,行編輯等的所有連接。這樣做是為了在任何時候都可以使用Qt Designer更新GUI,而不會影響程序功能。 。

是否可以從導入了Qt Designer的GUI模塊的主腳本中執行此操作?

我的主要腳本的結構示例:

import philipsControlGui
import sys

def main():
    MainWindow.show()
    sys.exit(app.exec_())

def test():
    print('test')

# Main window setup
app = philipsControlGui.QtWidgets.QApplication(sys.argv)
MainWindow = philipsControlGui.QtWidgets.QMainWindow()
ui = philipsControlGui.Ui_MainWindow()
ui.setupUi(MainWindow)

# Main window bindings
ui.onButton.clicked.connect(test)
### Can I insert something here to do: if user closes the window... do something else instead?

if __name__ == "__main__":
    main()

您應該從導入的gui創建一個子類,以便可以重新實現closeEvent方法:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from philipsControlGui import Ui_MainWindow

class MainWindow(QtWidgets.QMainWindow):    
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setUpUi(self)
        self.ui.onButton.clicked.connect(self.test)
        self._check_close = True

    def test(self):
        print('test')
        self._check_close = not self._check_close

    def closeEvent(self, event):
        if self._check_close:
            result = QtWidgets.QMessageBox.question(
                self, 'Confirm Close', 'Are you sure you want to close?',
                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
            if result == QtWidgets.QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

def main():
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':

    main()

如果設計中有特定的“ ExitButton”,則應該能夠將其連接到主代碼中並創建一個彈出對話框。 您將必須導入QtCore / QtGui組件。 我總是直接編寫我的GUI(涉及到這些事情,QtDesigner很痛苦),所以我假設是這樣的:

 from PyQt4.QtGui import *
 from PyQt4.QtCore import *

[YOUR CODE]

ui.ExitButton.clicked.connect(Exit)

def Exit():

  msg = QMessageBox()
  msg.setIcon(QMessageBox.Information)

  msg.setText("Are you sure you want to close this window?")
  msg.setWindowTitle("MessageBox demo")
  msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
  msg.buttonClicked.connect(msgbtn)
  retval = msg.exec_()
  print "value of pressed message box button:", retval

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM