首页 > 解决方案 > 是否可以从 QPrintDialog 调用的 QPrinter 对话框中取消选中“打印到文件”?

问题描述

我正在尝试使用 QPrinterDialog 打印 pdf 文件,并禁用对话框中的“打印到文件”选项。

有一些方法可以启用/禁用此选项,但不能取消选中它。是否可以使用 qt 框架务实地取消选中此选项?

标签: pythonpyside2

解决方案


似乎“打印到文件”选项仅在您连接了打印机但目前我没有它时才会出现,所以我的解决方案没有经过测试。

一种可能的解决方案是使用文本名称过滤窗口的子项以获得 QCheckBox:

from PySide2 import QtCore, QtGui, QtWidgets, QtPrintSupport


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    printer = QtPrintSupport.QPrinter()
    dialog = QtPrintSupport.QPrintDialog(printer)

    def on_timeout():
        for checkbox in dialog.findChildren(QtWidgets.QCheckBox):
            print(
                "objectName: {}, text: {}".format(
                    checkbox.objectName(), checkbox.text()
                )
            )
            if checkbox.text() == "Print to file":
                checkbox.setCheckState(QtCore.Qt.Unchecked)

    QtCore.QTimer.singleShot(0, on_timeout)

    if dialog.exec_() == QtWidgets.QDialog.Accepted:
        painter = QtGui.QPainter(printer)
        painter.fillRect(printer.pageRect(), QtGui.QColor("salmon"))

推荐阅读