2016-02-16 1 views
3

Я работал над интерфейсом PySide для Maya, и мне было интересно узнать, можно ли его определить для NON RECTANGULAR clickeable area для кнопки.Область щелчка кнопки PyQt (не прямоугольная область)

Я попытался с помощью QPushButton, а также расширение объекта QLabel, чтобы получить поведение кнопки, но вы знаете, если его можно получить кнопку, содержащее изображение с альфа-каналом и использовать этот альфа для определения области щелчка для кнопки?

Буду признателен, если вы можете помочь мне решить, как решить эту проблему. Спасибо заранее.

Я попытался это ...

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

+0

. Примечание: картинка = __file __ заменить ('qbtn.py', '') + «Марио .png ' ссылается на имя файла python, чтобы получить относительный путь для файла png, который находится в той же папке файла .py. –

ответ

0

Вы можете сделать это, ловя прессы/события отпускания и проверку положения щелчка со значением пикселя в чтобы решить, должен ли виджет издавать щелчок или нет.

class CustomButton(QWidget): 

    def __init__(self, parent, image): 
     super(CustomButton, self).__init__(parent) 
     self.image = image 

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

    def mouseReleaseEvent(self, event): 
     # Position of click within the button 
     pos = event.pos() 
     # Assuming button is the same exact size as image 
     # get the pixel value of the click point. 
     pixel = self.image.alphaChannel().pixel(pos) 

     if pixel: 
      # Good click, pass the event along, will trigger a clicked signal 
      super(CustomButton, self).mouseReleaseEvent(event) 
     else: 
      # Bad click, ignore the event, no click signal 
      event.ignore() 
+0

Привет, Брендан, спасибо за ваш ответ. Наконец, я получил решение, еще одну строку кода. –

3

Это окончательный код я получаю решить мой вопрос выше ...

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')