查看字体的位置

import java.awt.*;
import javax.swing.*;
import java.awt.font.*;
import java.awt.geom.*;
public class FrontTest {


public static void main(String[] args) {
// TODO Auto-generated method stub


EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame=new FontFrame();
frame.setTitle("FontTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}


}




class FontFrame extends JFrame
{
public FontFrame()
{
add(new FontComponent());
pack();
}
}




class FontComponent extends JComponent
{
private static final int DEFAULT_WIDTH=300;
private static final int DEFAULT_HEIGHT=200;

public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
String message="Hello World!";
Font f=new Font("Serif",Font.BOLD,36);
g2.setFont(f);

FontRenderContext context=g2.getFontRenderContext();
Rectangle2D bounds=f.getStringBounds(message, context);

double x=(getWidth()-bounds.getWidth())/2;
double y=(getHeight()-bounds.getHeight())/2;

double ascent=-bounds.getY();
double baseY=y+ascent;

g2.drawString(message, (int)x, (int)baseY);//注意这里的基地线

g2.setPaint(Color.LIGHT_GRAY);

g2.draw(new Line2D.Double(x, baseY,x+bounds.getWidth(),baseY));

Rectangle2D rect=new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight());
g2.draw(rect);
}

public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);
}
}
`QPlainTextEdit`是Qt库中的一个控件,主要用于显示和编辑纯文本。如果你想要查看它所使用的字体格式以及输出字符串,你可以通过以下步骤操作: 1. 首先,你需要获取到`QPlainTextEdit`实例。假设你有一个名为`textEditor`的对象,你可以这样做: ```python QPlainTextEdit textEditor = ...; // 初始化并获取到文本编辑器对象 ``` 2. 要查看当前字体格式,你可以检查它的样式信息。`QPlainTextEdit`不直接提供获取字体格式的属性,但你可以间接地通过`document()`方法获取其对应的`QTextDocument`,然后访问文档的样式信息。例如: ```python QTextDocument document = textEditor.document(); const QTextCharFormat& currentFormat = document.currentCharFormat(); // 获取字体、大小、颜色等信息 QString fontName = currentFormat.font().family(); int fontSize = currentFormat.font().pointSize(); QColor textColor = currentFormat.foreground().color(); ``` 3. 输出字符串时,通常你在`setPlainText()`方法中添加文本内容,但它不会影响已存在的格式,除非你在插入的位置改变了格式。如果需要直接输出格式化的字符串,可以创建一个`QTextCursor`并在文档中移动,设置相应的格式后再插入文本。 ```python QTextCursor cursor(document); cursor.insertText("这是一段带格式的文本"); cursor.setFont(QFont("Arial", 14)); // 设置字体和大小 cursor.setTextColor(Qt::red); // 设置颜色 cursor.movePosition(QTextCursor::End); // 移动到末尾 document.mergeCurrentCharFormat(cursor.block().position()); // 应用格式 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值