我开始使用PyQt在Python中编写一个简单的文本编辑器,我遇到了这个问题:对于“新文档”按钮,我想打开一个新的空文本编辑器,无论第一个窗口发生了什么,它都会保持打开状态。问题是,我得到它以显示窗口的唯一方法是,如果我发送 self 作为参数(使其成为父项),这导致父项关闭时第二个窗口关闭。
这是我的构造函数:
class Main(QtGui.QMainWindow):
def __init__(self, ctrl, parent=None):
QtGui.QMainWindow.__init__(self, parent)
这是打开新窗口的方法:
def new(self):
repo = Repository()
ctrl = Controller(repo)
new_win = Main(ctrl)
new_win.show()
注意:当此处的代码不起作用时,它不会显示第二个窗口
编辑:决定我应该发布我的所有代码,所以在这里:
import sys
from PyQt4 import QtGui
from src.controller import Controller
from src.repository import Repository
class Main(QtGui.QMainWindow):
nr_of_instances = -1
def __init__(self, ctrl, parent=None):
QtGui.QMainWindow.__init__(self, parent)
Main.nr_of_instances += 1
#ui elements
self._toolbar = None
self._menuBar = None
self._file = None
self._edit = None
self._view = None
self._formatBar = None
self._statusBar = None
self._text = None
#actions
self._newAction = None
self._openAction = None
self._saveAction = None
self._saveAsAction = None
#
self._controller = ctrl
self.init_ui()
def init_ui(self):
self._text = QtGui.QTextEdit(self)
self.setCentralWidget(self._text)
self.init_toolbar()
self.init_formatBar()
self.init_menuBar()
self._statusBar = self.statusBar()
self.setGeometry(50+(50*Main.nr_of_instances), 100+(50*Main.nr_of_instances), 800, 400)
self.setWindowTitle("KekWriter")
@staticmethod
def new(self):
repo = Repository()
ctrl = Controller(repo)
spawn = Main(ctrl)
spawn.show()
def set_title(self):
if self._controller.get_file_name() != 0:
new_title = self.windowTitle().split(" - ")
new_title[0].strip()
self.setWindowTitle(new_title[0]+" - "+self._controller.get_file_name())
def open(self):
fn = QtGui.QFileDialog.getOpenFileName(self, 'Open File', ".")
self._controller.set_file_name(fn)
try:
if fn != '':
self._text.setText(self._controller.open())
self.set_title()
except UnicodeDecodeError as msg:
QtGui.QMessageBox.information(self, "Eroare!", "Tip de fisier invalid!")
def _save_as(self):
fn = QtGui.QFileDialog.getSaveFileName(self, 'Save File As', ".")
print(fn)
if fn != '':
self._controller.set_file_name(fn)
self._controller.save(self._text.toPlainText())
self.set_title()
def save(self):
fn = self._controller.get_file_name()
if fn == '':
self._save_as()
else:
self._controller.save(self._text.toPlainText())
self.set_title()
def init_toolbar(self):
self._newAction = QtGui.QAction(QtGui.QIcon("icons/new.png"), "New", self)
self._newAction.setStatusTip("Creates a new document")
self._newAction.setShortcut("Ctrl+N")
self._newAction.triggered.connect(self.new)
self._openAction = QtGui.QAction(QtGui.QIcon("icons/open.png"), "Open", self)
self._openAction.setStatusTip("Opens existing document")
self._openAction.setShortcut("Ctrl+O")
self._openAction.triggered.connect(self.open)
self._saveAction = QtGui.QAction(QtGui.QIcon("icons/save.png"), "Save", self)
self._saveAction.setStatusTip("Saves current document")
self._saveAction.setShortcut("Ctrl+S")
self._saveAction.triggered.connect(self.save)
self._saveAsAction = QtGui.QAction(QtGui.QIcon("icons/save_as.png"), "Save as", self)
self._saveAsAction.setStatusTip("Saves current document with another name")
self._saveAsAction.setShortcut("Ctrl+Shift+S")
self._saveAsAction.triggered.connect(self._save_as)
self._toolbar = self.addToolBar("Options")
self._toolbar.addAction(self._newAction)
self._toolbar.addAction(self._openAction)
self._toolbar.addAction(self._saveAction)
self._toolbar.addAction(self._saveAsAction)
self.addToolBarBreak()
def init_menuBar(self):
self._menuBar = self.menuBar()
self._file = self._menuBar.addMenu("File")
self._edit = self._menuBar.addMenu("Edit")
self._view = self._menuBar.addMenu("View")
#file
self._file.addAction(self._newAction)
self._file.addAction(self._openAction)
self._file.addAction(self._saveAction)
self._file.addAction(self._saveAsAction)
def init_formatBar(self):
self._formatBar = self.addToolBar("Format")
self.addToolBarBreak()
def main():
app = QtGui.QApplication(sys.argv)
repo = Repository()
ctrl = Controller(repo)
main = Main(ctrl)
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
答案 0 :(得分:3)
第二个窗口未显示的原因是窗口对象超出范围并被垃圾回收。您需要存储对第二个窗口的引用,该窗口在窗口关闭之前不会被删除。
我可以想到有几种方法可以做到这一点,但是你想要如何构建你的程序真的取决于你。
具有Main
的类属性,这是一个列表。因此,此列表对所有实例都是通用的,您可以在创建时将新实例附加到该列表。只要存在一个实例,就不应该对窗口进行垃圾收集(我认为)
最初不要实例化QMainWindow
,而是实例化一个将保存对windows的引用的类。创建新窗口时,将对该对象中新窗口的引用进行修复。
希望这能让您了解错误,以便以适合您程序布局的方式解决问题
有关如何执行选项2的粗略指导:
class WindowContainer(object):
def __init__(self):
self.window_list = []
self.add_new_window()
def add_new_window(self):
repo = Repository()
ctrl = Controller(repo)
spawn = Main(ctrl, self)
self.window_list.append(spawn)
spawn.show()
class Main(QtGui.QMainWindow):
def __init__(self, ctrl, window_container, parent=None):
QtGui.QMainWindow.__init__(self, parent)
...
self.window_container = window_container
...
...
def init_toolbar(self):
...
self._newAction.triggered.connect(self.window_container.add_new_window)
...
...
def main():
app = QtGui.QApplication(sys.argv)
# this variable will never go out of scope
window_container = WindowContainer()
sys.exit(app.exec_())
答案 1 :(得分:1)
我现在正在考虑解决此问题的最佳方法是创建一个继承自QApplication的类。在此类中创建一个列表,并存储对此列表中所有新创建的窗口的引用。
最小的工作示例:
from PyQt4.QtGui import *
import sys
class Application(QApplication):
def __init__(self, argv=None):
super(Application, self).__init__(argv)
self.windows = []
win = Window(self)
win.show()
self.windows.append(win)
class Window(QMainWindow):
def __init__(self, parentApp, parent=None):
super(Window, self).__init__(parent)
self.parentApp = parentApp
btn = QPushButton("New Window", self)
btn.clicked.connect(self.new)
def new(self):
win = Window(self.parentApp)
win.show()
self.parentApp.windows.append(win)
def closeEvent(self, event):
self.parentApp.windows.remove(self)
if __name__ == "__main__":
app = Application(sys.argv)
sys.exit(app.exec_())
答案 2 :(得分:0)
您可以拥有许多主窗口而无需在PyQt中指定父级而没有问题。只需运行此代码作为示例:
from PyQt5 import QtWidgets
import sys
class MainWindow(QtWidgets.QMainWindow):
pass
# App
q_app = QtWidgets.QApplication(sys.argv)
# Add many windows
main_window1 = MainWindow()
main_window1.show()
main_window2 = MainWindow()
main_window2.show()
# Run Qt app
sys.exit(q_app.exec_())
注意,对于PyQt4,只需将QtWidgets
替换为QtGui
。
答案 3 :(得分:-1)
我从未在python中使用过UI,但这段代码似乎有些错误:
Main
类 ctor (来自第一个代码段)有3个参数:self
,ctrl
和parent
。由于parent
是默认 arg (可能会丢失),因此在我们的案例中它几乎无关紧要。
方法代码假设我们处于同一类:new_win = Main()
不正确。它应该有3个参数:
self
)由python framework ctrl
并且必须由你自己提供(毕竟,你这样定义了类ctor)