2014-01-24 64 views
0

我需要QSpinBox for unsigned int。所以我寫了簡單的課:如何刷新QAbstractSpinBox?

class UnsignedSpinBox : public QAbstractSpinBox { 
private: 
    uint32_t value = 0; 
    uint32_t minimum = 0; 
    uint32_t maximum = 100; 
private: 
    void stepBy(int steps) { 
    if (steps < 0 && (uint32_t)(-1 * steps) > value - minimum) 
     value = minimum; 
    else if (steps > 0 && maximum - value < (uint32_t)steps) 
     value = maximum; 
    else 
     value += steps; 
    lineEdit()->setText(QString::number(value)); 
    } 
    StepEnabled stepEnabled() const { 
    if (value < maximum && value > minimum) 
     return QAbstractSpinBox::StepUpEnabled | QAbstractSpinBox::StepDownEnabled; 
    else if (value < maximum) 
     return QAbstractSpinBox::StepUpEnabled; 
    else if (value > minimum) 
     return QAbstractSpinBox::StepDownEnabled; 
    else 
     return QAbstractSpinBox::StepNone; 
    } 
    QValidator::State validate(QString &input, int &) const { 
    if (input.isEmpty()) 
     return QValidator::Intermediate; 
    bool ok = false; 
    uint32_t validateValue = input.toUInt(&ok); 
    if (!ok || validateValue > maximum || validateValue < minimum) 
     return QValidator::Invalid; 
    else 
     return QValidator::Acceptable; 
    } 

public: 
    UnsignedSpinBox(QWidget* parent = 0) : QAbstractSpinBox(parent) { 
    lineEdit()->setText(QString::number(value)); 
    } 
    virtual ~UnsignedSpinBox() { } 
}; 

在gerenal它工作正常,但它有一個缺點。只有鼠標移動後,纔會刷新步驟按鈕(每秒調用一次功能stepEnabled)。因此,如果我保持向上翻頁,我的旋轉框將獲得最大值,並且這些步驟按鈕在我移動鼠標之前不會更改它們的狀態。或者,如果值爲0,則按下鍵盤上的向上或向上箭頭鍵將更改值和文本,但不會更改按鈕的狀態(向下按鈕仍處於禁用狀態)。此外,當價值==最大兩個按鈕都被禁用,雖然功能stepEnabled返回QAbstractSpinBox :: StepDownEnabled(我已經檢查過)。我究竟做錯了什麼?我如何強制QAbstractSpinBox正確繪製這些按鈕?

P.S.我使用Debian。但我不認爲這是重要的,因爲QSpinBox工作正常

回答

1

我認爲你的平臺上的Qt要麼太舊,要麼破壞。它在OS X上工作正常,在Qt 4.8.5和Qt 5.2.0上。

還有其他兩種解決方案:

  1. 如果你不關心全方位無符號整數,只需使用QSpinBox,並設置非負的最小值和最大值。就這樣。在具有32位int的平臺上,最大值爲int,值爲2^31-1,約爲最大值的uint的一半。您可以使用QDoubleSpinBox。在你關心的理智平臺上,double有超過32位的尾數,所以你可以將它轉換爲quint32而不會損失精度。

    如果您想確定,只需在代碼的任意位置添加static_assert(sizeof(double)>4)即可。

    如果擔心表現,那真的沒關係。計算以用戶輸入事件的速率執行:這是每秒幾十次雙操作。沒關係。

+0

我在Windows 7 Professional上試過這個類......這些按鈕根本不會被禁用(看起來在使用Qt時Windows上沒有這個功能)。我不想使用QDoubleSpinBox,因爲雙重計算比整數慢... 在Linux和Windows上,我使用Qt 5.2.0和Qt Creator 3.0.0。但專業文件包含行'greaterThan(QT_MAJOR_VERSION,4):QT + =部件' – user2717575

+0

你用C++ 11編譯我的代碼嗎? – user2717575

+0

@ user2717575:在這裏,C++ 11是無關緊要的。您在Windows *上使用的*風格可能不會使*按鈕被禁用時顯而易見。儘管如此,他們仍然殘疾。 –