Values of QMessageBox.Yes/QMessageBox.No

有些话、适合烂在心里 提交于 2021-01-27 21:23:20

问题



I learn PyQt5 (which looks quite complicated for me) and I am wondering why QMessageBox.Yes(or no) has some special value, for me it is 16384. That is what I mean:

from PyQt5 import QApplication, QWidget, QMessageBox

class App(QWidget):
    def message_box(self):
        resp = QMessageBox.question(self, 'foo', 'bar', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        print(resp)

It prints 16384 (if you click Yes) or 65536 (if you click No), why not True or False? I understand that I can compare it later to QMessageBox.Yes or QMessageBox.No, but I am wondering where are that magic values from and why they are used?


回答1:


Because yes and no are not the only options. What if you wanted yes, no, cancel and abort (which all had different meanings for your application)? You can't represent those with a single Boolean.

So instead it is common practice to use an integer. Of course remembering what each integer means is annoying, so they are stored in nicely named variables so your code stays readable!

There is nothing inherently special about the specific values used, other than the fact that they are powers of 2 (2^14 and 2^16 respectively) which allows they to be combined into a single integer using the "bitwise or" operation and then later extracted from the resultant integer using "bitwise and". This is a common way of combining option flags into a single variable so you don't need to add a new argument to a function/method every time you add an option (important in languages where optional method arguments can't be done). If you weren't aware, you already used the bitwise or to combine the flags in the message box constructor!




回答2:


If we look inside the QT documentation, we can read the following for the QMessageBox.question method's return value:

Returns the identity of the standard button that was clicked.

The identity for every standard button is an integer number, which is also specified by the documentation:

QMessageBox::Yes 0x00004000 QMessageBox::No 0x00010000

If we convert this hex values to decimals, we get 16384 and 65536.

why not True or False?

Because there are a lot more options here, there are a lot more standard buttons (ex. Ok, Open, Save, Cancel, etc.)

For more information you should read the documentation for QT: http://doc.qt.io/qt-5/qmessagebox.html (yes, it's for C++ but it is also applicable for the python wrapper)



来源:https://stackoverflow.com/questions/47984705/values-of-qmessagebox-yes-qmessagebox-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!