2016-02-16 55 views
3

我正在为Maya创建一个PySide接口,我想知道是否有可能为一个按钮定义一个非矩形可点击区域。PyQt按钮点击区域(非矩形区域)

我尝试使用QPushButton也延伸QLabel对象来获取按钮的行为,但你知道,如果它能够得到含alpha通道图片的按钮,并使用字母来定义的点击区域的按钮

如果你能指导我如何解决这个问题,我会很感激。 在此先感谢。

我已经试过这...

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文件的名称,以获取位于.py文件的同一文件夹中的png文件的相对路径。 –

回答

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