2015-08-20 46 views
-4

這是我第一週做Qt,所以如果我不瞭解基本知識,請原諒我。在下面代碼的註釋部分,我想編寫處理QInputDialog上取消按鈕的代碼。如何處理用戶按下QInputDialog中的取消按鈕?

#include <QtWidgets> 

int main (int argc, char* argv[]) {    
    QApplication app(argc, argv);     
    QTextStream cout(stdout);      
    int answer; 

    do { 
    int celciusArg = 0; 
    int farenheit; 
    celciusArg = QInputDialog::getInt(0, "Celcius Calculator", 
     "Convert this number to Farenheit:", 1); 

    // I'd like to say here: 
    // if (user clicked cancel) 
    //  then (close the widget) 

    cout << "User entered: " << celciusArg 
     << endl; 
    farenheit = celciusArg * 1.8 + 32; 

    QString response = QString("%1 degrees celcius is %2 degrees farenheit .\n%3") 
     .arg(celciusArg).arg(farenheit)  /* Each %n is replaced with an arg() value. */ 
     .arg("Convert another temperature?"); /* Long statements can continue on multiple lines, as long as they are broken on token boundaries. */ 
    answer = QMessageBox::question(0, "Play again?", response, 
     QMessageBox::Yes| QMessageBox::No); /* Bitwise or of two values. */ 
    } while (answer == QMessageBox::Yes); 
    return EXIT_SUCCESS; 
} 
+0

沒有測試但也許連接'''拒絕'''從對話框到處理函數的信號? – cen

+0

雖然這個問題是相當基礎的,但它確實包含了完整的源代碼 - 所以對此提問者非常讚賞。降價是相當沒有根據的恕我直言。 –

回答

2

更改爲

bool ok; 
celciusArg = QInputDialog::getInt(0, "Celcius Calculator", 
    "Convert this number to Farenheit:", 0, 0, 100, 1, &ok); 

if (ok) 
    //pressed ok 
else 
    //pressed cancel 

第一零爲默認值,第二個是最低值,100應該是最大值和1是遞增/遞減,如果你想獲得從-100℃至200℃的溫度從30℃開始,你必須使用

celciusArg = QInputDialog::getInt(0, "Celcius Calculator", 
    "Convert this number to Farenheit:", 30, -100, 200, 1, &ok); 
+0

這很有趣。另一個問題是,當我們有'QInputDialog :: getInt()'爲什麼有一個範圍解析運算符?我唯一見過它的時候就是當你爲一個類定義成員函數的時候。 – mdemont

+0

因爲'getInt'是'QInputDialog'類的靜態成員 – gengisdave

3

閱讀文檔,幫助了很多:

如果ok是非空的* ok將在用戶按下OK時設置爲true,如果用戶按下Cancel按鈕則設置爲false。該對話框的父代是父代。該對話框將是模式並使用小部件標誌。

完整的原型是:

int QInputDialog::getInt(QWidget * parent, const QString & title, const QString & label, int value = 0, int min = -2147483647, int max = 2147483647, int step = 1, bool * ok = 0, Qt::WindowFlags flags = 0) 

所以在這裏你只需要使用bool * ok

bool isOkPressed{}; 
int celciusArg = 0; 
int farenheit; 
celciusArg = QInputDialog::getInt(0, "Celcius Calculator", 
    "Convert this number to Farenheit:", 1, -2147483647, 2147483647, 1, &isOkPressed); 

if (isOkPressed) { 
    // here you go 
} 

QInputDialog::getInt() documentation

相關問題