簡體   English   中英

Python PyQt4如何使用QFileDialog打開圖像

[英]Python PyQt4 how to open image using QFileDialog

我必須編寫一個帶有從文件打開圖像選項的程序。 我必須使用QFileDialog並使用QPixmapQLabel顯示圖像。 我可以單獨使用它們,但無法合並使用。 我想我需要從dlg.selectedFiles獲取圖像名稱,但是我不知道如何選擇其中包含有用數據的時刻。 我是否需要在主程序中進行循環,並不斷檢查是否有要打開的圖像? 我可以使用openAction.triggered.connect(...)向我的標簽發送信號嗎?

from PyQt4 import QtGui
import sys

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        dlg = QtGui.QFileDialog(self)       
        openAction = QtGui.QAction('Open', self)  
        openAction.triggered.connect(dlg.open)     
        fileMenu.addAction(openAction)
        #label = QtGui.QLabel(self)
        #pixmap = QtGui.QPixmap('')
        #label.setPixmap(pixmap)

def main():
    app = QtGui.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()

if __name__ == '__main__':
    sys.exit(main()) 

您需要創建自己的插槽並將其連接到openAction信號。
__init__函數中執行以下操作:

openAction.triggered.connect(self.openSlot)  

在您的類MainWindow定義以下函數:

def openSlot(self):
    # This function is called when the user clicks File->Open.
    filename = QtGui.QFileDialog.getOpenFileName()
    print(filename)
    # Do your pixmap stuff here.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM