我正在尝试为我的程序添加选项卡但是到目前为止它还没有工作;标签显示但超过菜单栏,我不知道为什么。这是我的代码:
#! /usr/bin/python
import sys
import os
from PyQt4 import QtGui
class Notepad(QtGui.QMainWindow):
def __init__(self):
super(Notepad, self).__init__()
self.initUI()
def initUI(self):
newAction = QtGui.QAction('New', self)
newAction.setShortcut('Ctrl+N')
newAction.setStatusTip('Create new file')
newAction.triggered.connect(self.newFile)
saveAction = QtGui.QAction('Save', self)
saveAction.setShortcut('Ctrl+S')
saveAction.setStatusTip('Save current file')
saveAction.triggered.connect(self.saveFile)
openAction = QtGui.QAction('Open', self)
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open a file')
openAction.triggered.connect(self.openFile)
closeAction = QtGui.QAction('Close', self)
closeAction.setShortcut('Ctrl+Q')
closeAction.setStatusTip('Close Notepad')
closeAction.triggered.connect(self.close)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(newAction)
fileMenu.addAction(saveAction)
fileMenu.addAction(openAction)
fileMenu.addAction(closeAction)
tab_widget = QtGui.QTabWidget(self) # add tab
tab1 = QtGui.QWidget()
tab_widget.addTab(tab1, "Main")
self.text = QtGui.QTextEdit(tab_widget)
self.setCentralWidget(self.text)
self.setGeometry(300,300,300,300)
self.setWindowTitle('Notepad')
self.show()
def newFile(self):
self.text.clear()
def saveFile(self):
filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', os.getenv('HOME'))
f = open(filename, 'w')
filedata = self.text.toPlainText()
f.write(filedata)
f.close()
def openFile(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
f = open(filename, 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
def main():
app = QtGui.QApplication(sys.argv)
notepad = Notepad()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
我试图获取它,因此选项卡包含文本框。任何帮助都会很棒。
答案 0 :(得分:3)
不要在initUI
中创建文本小部件,而是使用newFile
和openFile
方法创建它,然后将其添加到tab_widget
(同时保存引用tab_wiget
中的initUI
,以便稍后访问它。例如:
def openFile(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))[0]
with open(filename, 'r') as f:
filedata = f.read()
text_widget = QtGui.QTextEdit(self.tab_widget)
text_widget.setText(filedata)
self.tab_widget.addTab(text_widget, os.path.basename(filename))