1

基本上我想要的是:

  1. 在主窗口中显示一个小部件,其中包含一个打开 QFileDialog 的按钮
  2. 选择文件时,包含按钮的小部件应切换到新的小部件,该小部件显示基于文件内容的一些可视化。

open_file()在下面的代码示例中,这意味着从方法中调用showFileSelectionDialog()方法。

问题是如何做到这一点?我尝试在初始化小部件时将父级作为参数,然后将按钮连接到 self.parent.open_file。但这变得复杂,我不喜欢小部件被硬编码为主窗口的子窗口。

据我所知,更好的方法是Communicate()用来发出事件。但是后来我不知道如何获取文件名信息的open_file()方法。

#Code greatly inspired by the ZetCode PySide tutorial (http://zetcode.com/gui/pysidetutorial/)

import sys
from PySide import QtGui

class MainApplicationWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainApplicationWindow, self).__init__()

        self.initUI()

    def initUI(self):

        self.setWindowTitle('<Application title>')
        self.setCentralWidget(FileSelectWidget())
        self.statusBar()

        self.resize(250, 200)
        self.center()
        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def open_file(self, file_name):
        f = open(file_name, 'r')
        with f:
            data = f.read()
            #TODO: Do something with the data and visualize it!
            print data

class FileSelectWidget(QtGui.QWidget):

    def __init__(self):
        super(FileSelectWidget, self).__init__()

        self.initUI()

    def initUI(self):

        selectLogFilesButton = QtGui.QPushButton('Select log files', self)
        selectLogFilesButton.clicked.connect(self.showFileSelectionDialog)

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch()
        hbox.addWidget(selectLogFilesButton)
        hbox.addStretch()

        vbox = QtGui.QVBoxLayout()
        vbox.addStretch()
        vbox.addLayout(hbox)
        vbox.addStretch()

        self.setLayout(vbox)

    def showFileSelectionDialog(self):

        file_name, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')


def main():

    app = QtGui.QApplication(sys.argv)
    window = MainApplicationWindow()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
4

1 回答 1

2

该类FileSelectWidget应该定义一个可以连接到open_file插槽的自定义信号。

为此,请确保导入 QtCore 模块,然后像这样定义自定义信号:

class FileSelectWidget(QtGui.QWidget):
    fileSelected = QtCore.Signal(object)

然后在选择文件时发出信号:

    def showFileSelectionDialog(self):
        file_name, _ = QtGui.QFileDialog.getOpenFileName(
                           self, 'Open file', '/home')
        if file_name:
            self.fileSelected.emit(file_name)

最后,将信号连接到插槽:

    widget = FileSelectWidget()
    widget.fileSelected.connect(self.open_file)
    self.setCentralWidget(widget)
于 2013-11-12T19:08:41.883 回答