簡體   English   中英

在Qt GUI(Python)中按下按鈕時顯示圖像

[英]Display an image when pressing a button in Qt GUI (Python)

我在Qt Creator中繪制了一個GUI,帶有一個按鈕,一個滑塊和一些標簽。

我正在嘗試的是:按下按鈕后,在終端上打印並在標簽中修改滑塊的值並顯示圖像。 正如許多網頁所建議的那樣,我正在嘗試使用pixmap方法將圖像顯示到標簽中。 這是我的全部代碼(GUI的結構在導入的mainwindow.ui文件中)

import sys
from PyQt4 import QtCore, QtGui, uic

qtCreatorFile = "mainwindow.ui"

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class myownGUI(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)


        #button
        self.Do_button.clicked.connect(self.action)

        #slider
        self.SLIDER.valueChanged[int].connect(self.SLIDER_update)

        #"global" variable init. by callback
        self.SLIDER_update()


    #The button callback
    def action(self):
        print "DOING ACTION!"
        print self.Slider
        #trying to display the image in the Image_label
        image = QtGui.QImage(QtGui.QImageReader(":/images/test.png").read())
        self.Image_label.setPixmap(QtGui.QPixmap(image))
        #self.Image_label.show() #unuseful command?


    #Slider update callback
    def SLIDER_update(self):
        self.Slider= self.SLIDER.value()
        if (self.Slider % 2 == 0): #even 
            self.Slider = self.Slider + 1
        self.Slider_label.setText(str(self.Slider))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = myownGUI()
    window.show()
    sys.exit(app.exec_())

該代碼運行,它不會顯示任何錯誤,但不會顯示圖像。 我嘗試了JPG和PNG圖像。 當圖像位於同一文件夾中時,我也嘗試了簡單的圖像名稱。

我的代碼有什么問題? 還有另一種在GUI中使用QT顯示圖像的方法(使用python)嗎?

先感謝您

使用:Ubuntu 14.04 / Qt版本4.8.6

我嘗試閱讀堆棧溢出中的所有類似問題。 看來我的問題重復了,但沒有一個答案似乎可以解決我的問題。

編輯 :使用PRMoureu的語法 ,當圖像是同一文件夾時也可以使用,例如

 image = QtGui.QImage(QtGui.QImageReader("./test.png").read())

現在將顯示圖像,並且僅需重新縮放。

您應該使用其他路徑語法調用該圖像:

image = QtGui.QImage(QtGui.QImageReader("./images/test.png").read())

要么

image = QtGui.QImage(QtGui.QImageReader("images/test.png").read())

暫無
暫無

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

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