代码之家  ›  专栏  ›  技术社区  ›  JokerMartini

Pyside获取qspinbox中箭头按钮的宽度

  •  3
  • JokerMartini  · 技术社区  · 5 年前

    是否有方法确定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 回复  |  直到 5 年前
        1
  •  1
  •   eyllanesc RAHUL KUMAR    5 年前

    无需获取宽度,只需获取子控件以了解是否按了其中一个箭头按钮:

    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)