如何在PyQt中制作双箭头按钮

时间:2019-05-23 03:41:30

标签: python pyqt pyqt4

我正在尝试制作这样的按钮

enter image description here

当前,我可以使用Qt::LeftArrow中的Qt::RightArrowsetArrowType()创建中间的两个按钮(向右或向左)。在docs中,似乎只有5种可能的类型。如果未内置此功能,如何制作自定义双箭头按钮?

现在我有这个

enter image description here

from PyQt4 import QtCore, QtGui
import sys

class PanningButton(QtGui.QToolButton):
    """Custom button with click, short/long press, and auto-repeat functionality"""

    def __init__(self):
        QtGui.QToolButton.__init__(self)
        self.setArrowType(QtCore.Qt.LeftArrow)
        # Enable auto repeat on button hold
        self.setAutoRepeat(True)
        # Initial delay in ms before auto-repetition kicks in
        self.setAutoRepeatDelay(700)
        # Length of auto-repetition
        self.setAutoRepeatInterval(500)
        self.clicked.connect(self.buttonClicked)
        self._state = 0

    def buttonClicked(self):
        # Panning
        if self.isDown():
            if self._state == 0:
                self._state = 1
                self.setAutoRepeatInterval(50)
        # Mouse release
        elif self._state == 1:
            self._state = 0
            self.setAutoRepeatInterval(125)

def pressed():
    global counter
    counter += 1
    print(counter)

if __name__ == '__main__':
    app = QtGui.QApplication([])

    counter = 0
    panning_button = PanningButton()
    panning_button.clicked.connect(pressed)

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

1 个答案:

答案 0 :(得分:2)

有几种选择:

  • 使用Qt图标,在这种情况下,您可以使用QStyle的standardIcon()
from PyQt4 import QtCore, QtGui


class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button1 = QtGui.QToolButton()
        button1.setIcon(
            button1.style().standardIcon(QtGui.QStyle.SP_MediaSeekBackward)
        )

        button2 = QtGui.QToolButton()
        button2.setArrowType(QtCore.Qt.LeftArrow)

        button3 = QtGui.QToolButton()
        button3.setArrowType(QtCore.Qt.RightArrow)

        button4 = QtGui.QToolButton()
        button4.setIcon(
            button1.style().standardIcon(QtGui.QStyle.SP_MediaSeekForward)
        )

        lay = QtGui.QHBoxLayout(self)
        for btn in (button1, button2, button3, button4):
            lay.addWidget(btn)


if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

enter image description here

  • 使用QPainter创建图标
def create_icon():
    pixmap = QtGui.QPixmap(QtCore.QSize(128, 128))
    pixmap.fill(QtCore.Qt.transparent)
    painter = QtGui.QPainter(pixmap)
    # draw icon
    painter.end()
    return QtGui.QIcon(pixmap)
  • 使用由图像编辑器(例如photoshop,coreldraw,gimp等)创建的图标。

恕我直言,最简单的解决方案是最后一种情况,因为在第一种情况下,您仅限于Qt提供的功能,在第二种情况下,它可能会不必要地变得复杂,但是第三种情况是最佳选择。