给QListWidget的Item上添加了Label之后,怎样让item的高度自适应

 我来答
一骑当后
推荐于2016-05-17 · 知道合伙人数码行家
一骑当后
知道合伙人数码行家
采纳数:40298 获赞数:306448
网络、设备维护、电路、弱电检测。

向TA提问 私信TA
展开全部
Code Snippet
using System;
using System.Drawing;
using System.Windows.Forms;

namespace MyControls
{
/// <summary>
/// A label that supports vertical auto resizing.
/// </summary>
public class Label : System.Windows.Forms.Label
{
private bool bChanging = false;

private SizeF MeasureStringExtended(Graphics g, string text, Font font, int desWidth)
{
string tempString = text;
string workString = "";
string outputstring = "";
int npos = 1;
int sp_pos = 0;
int sp_pos1 = 0;
int sp_pos2 = 0;
int sp_pos3 = 0;
bool bNeeded = false;
int line = 0;
int nWidth = 0;

//get original size
SizeF size = g.MeasureString(text, font);

if (size.Width > desWidth)
{
while(tempString.Length > 0)
{
//Check for the last lane
if (npos > tempString.Length)
{
outputstring = outputstring + tempString;
line++;
break;
}
workString = tempString.Substring(0, npos);
//get the current width
nWidth = (int)g.MeasureString(workString, font).Width;
//check if we've got out of the destWidth
if (nWidth > desWidth)
{
//try to find a space

sp_pos1 = workString.LastIndexOf(" ");
sp_pos2 = workString.LastIndexOf(";");
sp_pos3 = workString.IndexOf("\r\n");
if (sp_pos3 > 0)
{
sp_pos = sp_pos3;
bNeeded = false;
}
else
{
if ((sp_pos2 > 0) && (sp_pos2 > sp_pos1))
{
sp_pos = sp_pos2;
bNeeded = true;
}
else if (sp_pos1 > 0)
{
sp_pos = sp_pos1;
bNeeded = true;
}
else
{
sp_pos = 0;
bNeeded = true;
}
}

if (sp_pos > 0)
{
//cut out the wrap lane we've found
outputstring = outputstring + tempString.Substring(0,sp_pos + 1);
if (bNeeded) outputstring = outputstring + "\r\n";
tempString = tempString.Substring((sp_pos + 1), tempString.Length - (sp_pos + 1));
line++;
npos = 0;
}
else //no space
{
outputstring = outputstring + tempString.Substring(0,npos + 1);
if (bNeeded) outputstring = outputstring + "\r\n";
tempString = tempString.Substring(npos, tempString.Length - npos);
line++;
npos = 0;
}
}
npos++;
}
}
else
{
outputstring = text;
}

SizeF returnSize = g.MeasureString(outputstring, font);
bChanging = true;
this.Text = outputstring;
bChanging = false;
return returnSize;
}

private void InitializeComponent()
{
bChanging = false;
}

protected override void OnTextChanged(EventArgs e)
{
if(!bChanging)
{
Bitmap bmp = new Bitmap(175,175);
Graphics graphics = Graphics.FromImage(bmp);
SizeF size = new SizeF();

size = MeasureStringExtended(graphics,this.Text,this.Font,175);
this.Height = (int)size.Height;
base.OnTextChanged (e);
}
}
}
}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式