如何重新启动 QApplication [英] How to restart an QApplication

查看:90
本文介绍了如何重新启动 QApplication的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在单击按钮时重新启动我的应用程序,但我遇到了一些问题.我试过两种方法:

I need to restart my application when a button is clicked, but I'm having some problems with it. I've tried two methods:

  1. 尝试了这个建议,它确实重新启动了应用程序,但我收到每个小部件的 Gtk_IS_INVISIBLE (widget) 错误,并且所有这些小部件在重新启动的应用程序中看起来都不同,外观非常旧"(类似于 TkInter 小部件).有没有办法解决这个错误?除此之外,该应用程序运行良好.

  1. Tried this suggestion and it indeed restarts the application, but I get a Gtk_IS_INVISIBLE (widget) error for every widget, and all of them look different in the restarted application, with a very "old" look (similar to TkInter widgets). Is there a way so solve this error? Besides this, the application works fine.

我也试过:

subprocess.Popen("/home/pi/pywork/pyqt/of2.py")
sys.exit(0)

如此处建议,但我收到以下错误:OSError: [Errno 13] 权限被拒绝.有没有办法覆盖这个被拒绝的权限?

as suggested here, but I get the following error: OSError: [Errno 13] Permission denied. Is there a way to override this denied permission?

它们似乎都不能正常工作.有没有办法修复其中的任何一个?您知道重新启动应用程序的替代方法吗?

None of them seem to work properly. Is there a way to fix any of them? Do you know an alternative method to restart the application?

推荐答案

第二种方法报错,因为文件不可执行.您可以解决这个问题,但使用相同的 python 可执行文件重新运行脚本可能更健壮.避免对脚本路径进行硬编码也是一个好主意.

The second method gives an error because the file is not executable. You could fix that, but it is probably more robust to just re-run the script using the same python executable. It would also be a good idea to avoid hard-coding the script path.

这是一个实现所有这些的简单演示脚本:

Here is a simple demo script that implements all that:

import sys, os, subprocess
from PyQt4 import QtCore, QtGui

FILEPATH = os.path.abspath(__file__)

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton(
            'Restart [PID: %d]' % QtGui.qApp.applicationPid(), self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        try:
            subprocess.Popen([sys.executable, FILEPATH])
        except OSError as exception:
            print('ERROR: could not restart aplication:')
            print('  %s' % str(exception))
        else:
            QtGui.qApp.quit()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 400, 100, 50)
    window.show()
    sys.exit(app.exec_())

这篇关于如何重新启动 QApplication的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆