Qt中如何设置默认打印机?Win10多打印机打印异常求助
Hey there! I see you're having trouble printing to non-default shared printers on Windows 10 while using Qt. Let's break down how to set a default printer in Qt, plus some other fixes that might solve your core problem without even needing to change the default.
1. Yes, Qt lets you set the system default printer
Starting from Qt 5.10, there's a built-in way to set the default printer system-wide using QPrinterInfo. Here's how you can do it:
// Get the printer info for your target shared printer // Make sure to use the full network path format: "\\\\ServerName\\SharedPrinterName" QPrinterInfo targetPrinter = QPrinterInfo::printerInfo("\\\\YourServer\\YourSharedPrinter"); if (targetPrinter.isValid()) { bool isSet = QPrinterInfo::setDefaultPrinter(targetPrinter); if (isSet) { qDebug() << "Successfully set default printer!"; } else { // Note: On Windows, this might require admin permissions qDebug() << "Failed to set default printer. Check if your app has admin rights."; } } else { qDebug() << "Target printer not found. Double-check the printer name/path."; }
- Important: This modifies the system-wide default printer, not just for your app. Also, Windows might block this if your app doesn't have administrative privileges.
2. But wait—you might not need to set the default
Your issue (only default shared printer works) often stems from incorrect printer naming or Qt not recognizing the shared printer properly. Let's troubleshoot that first:
- Verify the printer name format: On Windows 10, shared printers need to be referenced by their full network path, like
\\ServerName\PrinterShareName. If yourreadSettings()returns just the friendly display name (e.g., "HP LaserJet 1020"), Qt might not find it. Use the full path instead. - Check if Qt sees the printer: Enumerate all available printers to confirm your shared printer is in the list:
Compare the names here with what you're getting fromQList<QPrinterInfo> availablePrinters = QPrinterInfo::availablePrinters(); for (const QPrinterInfo& info : availablePrinters) { qDebug() << "Printer:" << info.printerName() << "| Default:" << info.isDefault(); }readSettings()—they need to match exactly. - Validate the printer object: In your code, after calling
printer_.setPrinterName(name.at(id)), add a check:
If it's invalid, your printer name is definitely the problem.qDebug() << "Attempting to use printer:" << printer_.printerName(); if (!printer_.isValid()) { qDebug() << "Printer is invalid! Name might be wrong."; return "printer not valid"; }
3. Quick tweaks to your existing code
A couple of small changes might help:
- After setting the printer name, ensure you're using the correct output format (you already have
NativeFormat, which is good). - The
printerState()check might not be reliable immediately after drawing. Instead, you could listen for theQPrinter::stateChangedsignal if you're using a non-blocking approach.
内容的提问来源于stack exchange,提问作者zohee
相关产品推荐
相关产品推荐

