PySide获取QSpinBox箭头按钮的宽度

3
有没有方法可以确定qspinbox中箭头按钮的宽度? 我正在尝试重写上下文菜单事件,并且只有在用户右键单击箭头按钮时才希望发生自定义事件,否则我希望正常的上下文菜单出现。 目前,我只是硬编码了一个不理想的值20。
import sys
import os
from PySide import QtGui, QtCore

class MySpinner(QtGui.QSpinBox):
    def __init__(self, parent=None):
        super(MySpinner, self).__init__(parent)
        self.setAccelerated(False)
        self.setRange(-1000,1000)
        self.setSingleStep(1)
        self.setValue(300)

    def contextMenuEvent(self, event):
        if event.pos().x() > self.rect().right()-20:
            self.setValue(50)
            self.selectAll()
        else:
            super(self.__class__, self).contextMenuEvent(event)


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(300, 200)

        grid = QtGui.QVBoxLayout()
        grid.addWidget(MySpinner())
        content = QtGui.QWidget()
        content.setLayout(grid)
        self.setCentralWidget(content)



def main():
    app = QtGui.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
1个回答

1

不必获取宽度,只需获取SubControl即可知道箭头按钮是否被按下:

def contextMenuEvent(self, event):
    opt = QtGui.QStyleOptionSpinBox()
    self.initStyleOption(opt)
    opt.subControls = QtGui.QStyle.SC_All
    hoverControl = self.style().hitTestComplexControl(QtGui.QStyle.CC_SpinBox, opt, event.pos(), self)
    if hoverControl == QtGui.QStyle.SC_SpinBoxUp:
        print("up")
    elif hoverControl == QtGui.QStyle.SC_SpinBoxDown:
        print("down")
    else:
        super(self.__class__, self).contextMenuEvent(event)

如果您想获取每个子控件的QRect,则应使用
# up
rect_up = self.style().subControlRect(QtGui.QStyle.CC_SpinBox, opt, QtGui.QStyle.SC_SpinBoxUp, self)
# down
rect_down = self.style().subControlRect(QtGui.QStyle.CC_SpinBox, opt, QtGui.QStyle.SC_SpinBoxDown, self)

另一个选项:

def contextMenuEvent(self, event):
    opt = QtGui.QStyleOptionSpinBox()
    self.initStyleOption(opt)
    r = QtCore.QRect()
    for sc in (QtGui.QStyle.SC_SpinBoxUp, QtGui.QStyle.SC_SpinBoxDown):
        r= r.united(self.style().subControlRect(QtGui.QStyle.CC_SpinBox, opt, sc, self))
    if r.contains(event.pos()):
        print("arrow")
    else:
        super(self.__class__, self).contextMenuEvent(event)

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