PySide QInputDialog.getInt() 返回值?

1 投票
1 回答
1322 浏览
提问于 2025-04-30 14:37

文档上说这个函数会返回一个整数:https://pyside.github.io/docs/pyside/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getInt

但是当我运行下面的代码时:

year = QInputDialog.getInt(self, QApplication.applicationName(),
    "Enter the year.", QDate().currentDate().year()-1)
print("year = ", year)

... 我得到的是一个包含两个元素的元组:

('year = ', (2013, True))

这倒也没问题,但还是有点不同。我是不是漏掉了什么?

暂无标签

1 个回答

2

QInputDialog的静态成员会根据用户的操作来设置一个叫ok的参数(这是一个指针)。如果用户点击了“确定”,这个参数就会被设置为true;如果用户点击了“取消”,它就会被设置为false

在C++中,你需要这样做:

 bool ok;
 int year = QInputDialog::getInt(
                 this, QApplication::applicationName(),
                 tr("Enter the year"), QDate::currentDate().year() - 1,
                 minimum, maximum, 1, &ok);
 if (ok)
     ...

但是在Python中,这样修改参数的方式是非常不推荐的。因此,PyQt和PySide选择将所有的值一起返回,放在一个元组里。

总的来说,凡是Qt文档提到通过修改参数可以返回多个值的地方,你可以基本上认为PyQt和PySide会返回一个元组,而不是修改参数。

撰写回答