PyQt 按钮点击区域(非矩形区域)

3
我正在为Maya设计一个PySide界面,想知道是否可能定义一个非矩形点击区域的按钮。我尝试使用QPushButton,并扩展QLabel对象以获取按钮行为,但您是否知道是否可以获得包含带Alpha通道的图片的按钮,并使用该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


注意:picture = file.replace('qbtn.py', '') + 'mario.png'是指Python文件的名称,以获取与.py文件位于同一文件夹中的png文件的相对路径。 - Ramiro Tell
2个回答

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

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

嗨,Brendan,谢谢你的回复。最终我找到了解决方案,只需要再加一行代码。 - Ramiro Tell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接