将文本编辑器嵌入到窗口小部件中

时间:2014-02-05 22:08:56

标签: python pyqt pyqt4

我创建了一个文本编辑程序,我想添加其他功能,如按钮。我需要将它嵌入到widget中(所以就像文本编辑器是gui的ontop一样,按钮也像一个面板)抱歉java参考,不知道pyqt4中有什么叫,但我不知道如何使用PQT4和Python 3.x执行此操作。 我想实现以下目标: ![在此输入图像说明] [1]

这是我的文本编辑器代码

#! /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)

        self.text = QtGui.QTextEdit(self)

        self.setCentralWidget(self.text)
        self.setGeometry(300,300,500,500)
        self.setWindowTitle('Pygame Simplified text editor')
        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()

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

由于你没有指定“另一个GUI”是什么,我将假设它是另一个PyQt4程序。在这种情况下,您所要做的就是让QMainWindow表现得像普通的小部件。

首先,更改Notepad.__init__以便它可以拥有父级:

class Notepad(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Notepad, self).__init__(parent)
        ...

然后调整window flags,使其不像顶级窗口那样:

class AnotherGUI(QtGui.QMainWindow):
    def __init__(self):
        super(AnotherGUI, self).__init__()
        self.notepad = Notepad(self)
        self.notepad.setWindowFlags(
            self.notepad.windowFlags() & ~QtCore.Qt.Window)
        self.button = QtGui.QPushButton('Submit', self)
        ...
相关问题