Using C++ and Qt, how to calculate the width and height of some text in a certain font?
- User
Using C++ and Qt, how to calculate the width and height of some text in a certain font?
- Assistant
To calculate the width and height of text in a certain font using C++ and Qt, you can utilize the
QFontMetricsclass. Here's an example code snippet:#include <QCoreApplication> #include <QFontMetrics> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Create a font object with the desired font properties QFont font("Arial", 12); // Example font: Arial with size 12 // Create a QFontMetrics object with the font QFontMetrics fontMetrics(font); // Text to measure QString text = "Hello, World!"; // Calculate the width and height of the text int textWidth = fontMetrics.horizontalAdvance(text); int textHeight = fontMetrics.height(); // Output the results qDebug() << "Text Width:" << textWidth; qDebug() << "Text Height:" << textHeight; return a.exec(); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.