QMessageBox.Yes/QMessageBox.No 的值 [英] Values of QMessageBox.Yes/QMessageBox.No

查看:40
本文介绍了QMessageBox.Yes/QMessageBox.No 的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我学习了 PyQt5(对我来说看起来很复杂),我想知道为什么 QMessageBox.Yes(或 no)有一些特殊的价值,对我来说它是 16384.这就是我的意思:


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)

它打印 16384(如果您单击是)或 65536(如果您单击否),为什么不是 True 或 False?我知道我稍后可以将它与 QMessageBox.YesQMessageBox.No 进行比较,但我想知道这些魔法值来自哪里以及为什么使用它们?

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?

推荐答案

因为是和否不是唯一的选项.如果您想要 yes、no、cancel 和 abort(这对您的应用程序都有不同的含义)怎么办?你不能用一个布尔值来表示那些.

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!

所使用的特定值本身并没有什么特别之处,除了它们是 2 的幂(分别为 2^14 和 2^16),这允许它们使用按位或"组合成单个整数操作,然后使用按位与"从结果整数中提取.这是将选项标志组合到单个变量中的常用方法,因此您无需在每次添加选项时向函数/方法添加新参数(在无法完成可选方法参数的语言中很重要).如果您不知道,您已经在消息框构造函数中使用了按位或组合标志!

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!

这篇关于QMessageBox.Yes/QMessageBox.No 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆