简体   繁体   English

PyQt4:QSpinBox字符串

[英]PyQt4: QSpinBox strings

Is there a simple way to create a spinbox in PyQt4 whose varying values are strings? 有没有一种简单的方法可以在PyQt4中创建一个旋转框,其变化值是字符串? I want to create a spinbox which varies between 'low', 'medium' and 'high'. 我想创建一个在“低”,“中”和“高”之间变化的旋转框。 I've looked around and can't find anything that doesn't look very complicated. 我环顾四周,找不到看起来不太复杂的东西。 In Tkinter it might look trivially like: 在Tkinter中,它看起来很简单:

self.my_wordy_spinbox = Spinbox(parent, 
                                values = ['Medium', 'High', 'Low'],
                                textvariable = self.object_strength)

I noticed in the documentation it said "QSpinBox is designed to handle integers and discrete sets of values (eg, month names)" which I thought might lead to strings but I couldn't find any more on that. 我在文档中注意到它说“ QSpinBox设计用于处理整数和离散值集(例如,月份名称)”,我认为这可能会导致字符串,但我找不到更多信息。 I'm tempted to use a combobox instead but I feel that the spinbox would be more appropriate. 我很想使用组合框,但我觉得旋转框会更合适。

I don't really see how this would be in any way an improvement over a combo-box, especially if there's more than a few strings. 我真的看不出这对组合框有什么改进,特别是在字符串多的情况下。

However, if you really want it, you just need to subclass QSpinBox and reimplement textFromValue and valueFromText : 但是,如果确实需要, 则只需要继承 QSpinBox子类并重新实现textFromValuevalueFromText即可

class StringBox(QtGui.QSpinBox):
    def __init__(self, strings, parent=None):
        super(StringBox, self).__init__(parent)
        self.setStrings(strings)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings) - 1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM