Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt button click area (Non rectangular area)

I was working on a PySide interface for Maya and i was wondering if its possible to define a NON RECTANGULAR clickeable area for a button.

I tried using QPushButton and also extending a QLabel object to get button behavior but do you know if its possible to get a button containing a picture with alpha channel and use that alpha to define the click area for a button?

I'd appreciate a lot if you can guide me through how to solve this problem. Thanks in advance.

I've tried this...

from PySide import QtCore
from PySide import QtGui 

class QLabelButton(QtGui.QLabel):

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

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

class CustomButton(QtGui.QWidget):
    def __init__(self, parent=None, *args):
        super(CustomButton, self).__init__(parent)
        self.setMinimumSize(300, 350)
        self.setMaximumSize(300, 350)

        picture = __file__.replace('qbtn.py', '') + 'mario.png'
        self.button = QLabelButton(self)
        self.button.setPixmap(QtGui.QPixmap(picture))
        self.button.setScaledContents(True)

        self.connect(self.button, QtCore.SIGNAL('clicked()'), self.onClick)

    def onClick(self):
        print('Button was clicked')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = CustomButton()
    win.show()
    app.exec_()
    sys.exit()

mario.png

like image 413
Ramiro Tell Avatar asked Nov 21 '25 11:11

Ramiro Tell


1 Answers

This is the final code i get to solve my above question...

from PySide import QtCore 
from PySide import QtGui 


class QLabelButton(QtGui.QLabel):

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

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

class CustomButton(QtGui.QWidget):
    def __init__(self, parent=None, *args):
        super(CustomButton, self).__init__(parent)
        self.setMinimumSize(300, 350)
        self.setMaximumSize(300, 350)

        pixmap = QtGui.QPixmap('D:\mario.png')

        self.button = QLabelButton(self)
        self.button.setPixmap(pixmap)
        self.button.setScaledContents(True)
        self.button.setMask(pixmap.mask()) # THIS DOES THE MAGIC

        self.connect(self.button, QtCore.SIGNAL('clicked()'), self.onClick)

    def onClick(self):
        print('Button was clicked')
like image 113
Ramiro Tell Avatar answered Nov 23 '25 16:11

Ramiro Tell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!