views:

359

answers:

4

Im trying to do simple audio player, but I want use a image(icon) as a pushbutton.

A: 

Something like this, maybe?

import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

app = QApplication(sys.argv)
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
button = QPushButton()
layout.addWidget(button)
icon = QIcon("image.png")
button.setIcon(icon)
widget.show()
app.exec_()
Jesse Aldridge
yes it work, bu I don't wante a image inside the button, I want, a image as replacement of a button
Alquimista
+3  A: 

You can subclass QAbstractButton and make a button of your own. Here is a basic simple example:

import sys
from PyQt4.QtGui import *

class PicButton(QAbstractButton):
    def __init__(self, pixmap, parent=None):
        super(PicButton, self).__init__(parent)
        self.pixmap = pixmap

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(event.rect(), self.pixmap)

    def sizeHint(self):
        return self.pixmap.size()

app = QApplication(sys.argv)
window = QWidget()
layout = QHBoxLayout(window)

button = PicButton(QPixmap("image.png"))
layout.addWidget(button)

window.show()
sys.exit(app.exec_())

That's not a super easy way, but it gives you a lot of control. You can add second pixmap and draw it only when the mouse pointer is hover over button. You can change current stretching behavior to the centering one. You can make it to have not a rectangular shape and so on...

alex vasi
thank, i will read more abot subclassing QAbstractButton
Alquimista
A: 

Another option is to use stylesheets. Something like:

from PyQt4 import QtCore, QtGui
import os
...

path = os.getcwd()
self.myButton.setStyleSheet("background-image: url(" + path + "/myImage.png);")
swanson
A: 

I've seen that a lot of people have this problem and decided to write a proper example on how to fix it. You can find it here: An example on how to make QLabel clickable The solution in my post solves the problem by extending QLabel so that it emits the clicked() signal. The extended QLabel looks something like this:

class ExtendedQLabel(QLabel):

def __init(self, parent):
    QLabel.__init__(self, parent)

def mouseReleaseEvent(self, ev):
    self.emit(SIGNAL('clicked()'))

I hope this helps!

MikaelHalen