如何在 QTabwidget 中保存文件?
How can I save file in QTabwidget?
那是我的代码,但我必须添加保存方法以在选项卡中保存文本。我该怎么做?
class Main(QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.initUi()
def initUi(self):
self.setWindowTitle("Text Editor")
self.resize(800, 600)
self.tab = QTabWidget(self)
self.setCentralWidget(self.tab)
self.tab.tabCloseRequested[int].connect(self.on_tab_close)
def addtab(self, content, fileName):
self.tab.addTab(QPlainTextEdit(str(content)), str(fileName))
只需保留对您创建的每个新编辑器的引用,而不是直接添加实例。
class Main(QMainWindow):
# ...
def initUi(self):
self.setWindowTitle("Text Editor")
self.resize(800, 600)
self.tab = QTabWidget(self)
self.setCentralWidget(self.tab)
self.tab.tabCloseRequested[int].connect(self.on_tab_close)
self.editors = []
def addtab(self, content, fileName):
editor = QPlainTextEdit(str(content))
self.tab.addTab(editor, str(fileName))
self.editors.append(editor)
def save(self):
index = self.tab.currentIndex()
if index < 0:
return
fileName, filter = QFileDialog.getSaveFileName(self, 'Save')
if fileName:
with open(fileName, 'w') as f:
f.write(self.editors[index].toPlainText())
那是我的代码,但我必须添加保存方法以在选项卡中保存文本。我该怎么做?
class Main(QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.initUi()
def initUi(self):
self.setWindowTitle("Text Editor")
self.resize(800, 600)
self.tab = QTabWidget(self)
self.setCentralWidget(self.tab)
self.tab.tabCloseRequested[int].connect(self.on_tab_close)
def addtab(self, content, fileName):
self.tab.addTab(QPlainTextEdit(str(content)), str(fileName))
只需保留对您创建的每个新编辑器的引用,而不是直接添加实例。
class Main(QMainWindow):
# ...
def initUi(self):
self.setWindowTitle("Text Editor")
self.resize(800, 600)
self.tab = QTabWidget(self)
self.setCentralWidget(self.tab)
self.tab.tabCloseRequested[int].connect(self.on_tab_close)
self.editors = []
def addtab(self, content, fileName):
editor = QPlainTextEdit(str(content))
self.tab.addTab(editor, str(fileName))
self.editors.append(editor)
def save(self):
index = self.tab.currentIndex()
if index < 0:
return
fileName, filter = QFileDialog.getSaveFileName(self, 'Save')
if fileName:
with open(fileName, 'w') as f:
f.write(self.editors[index].toPlainText())