开发者

PyQt - is it possible to run two applications?

开发者 https://www.devze.com 2023-03-09 01:06 出处:网络
Two files. Each runs new window and works by itself. I need to run them both. When I run first.pyw, only one (second) window is shown.

Two files. Each runs new window and works by itself. I need to run them both.

When I run first.pyw, only one (second) window is shown.

Is it possible two run them both?

first.pyw:

import sys
from PyQt4.QtGui import *
import second

class first(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle('first')

app = QApplication(sys.argv)
firstApp = first()
firstApp.show()
sys.exit(app.exec_())

second.pyw:

import sys
from PyQt4.QtGui import *

class second(QWidget):
    def __init__(self, pare开发者_Python百科nt=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle('second')

app2 = QApplication(sys.argv)
secondApp = second()
secondApp.show()
sys.exit(app2.exec_())

How can I run two applications that are in different modules?


The accepted answer is essentially right, but there are cases where you want to run multiple QApplications one after the other, e.g. :

  • Unit tests
  • A command-line tool that shouldn't require a running X server (hence no QApplication on startup), but can optionally show a window if the user's system supports it

I ended up using the multiprocessing module to start each QApplication in a separate process, so that each one is independent from the others.

from multiprocessing import Queue, Process
class MyApp(Process):

   def __init__(self):
       self.queue = Queue(1)
       super(MyApp, self).__init__()

   def run(self):
       app = QApplication([])
       ...
       self.queue.put(return_value)

app1 = MyApp()
app1.start()
app1.join()
print("App 1 returned: " + app1.queue.get())

app2 = MyApp()
app2.start()
app2.join()
print("App 2 returned: " + app1.queue.get())


You can only run a single application at a time, although your application can have multiple top-level windows. The QCoreApplication docs say that:

...there should be exactly one QCoreApplication object.

This also holds true for QApplication as it derives from QCoreApplication. You can get access to that application through the QCoreApplication.instance() method or the qApp macro in C++.

What do you expect to get out of having two different applications running? Instead, you could have each module provide a top-level window that then gets displayed by the application launcher.


You import second. Hence it is interpreted before you even reach the definition of class first. As the last line of second.pyw is sys.exit, nothing behind it can be executed.

0

精彩评论

暂无评论...
验证码 换一张
取 消