1. 程式人生 > >QT tableview控制元件Item中新增文字和控制元件

QT tableview控制元件Item中新增文字和控制元件

實現方法:

自定義tableview 的delegate

在paint函式中,將原來的option中的rect切分為 文字顯示 和 按鈕繪製兩部分;

在editorevent中,實現按鈕事件響應。

//繪製文字
intiTextRight=option.rect.right()-m_nWidth-10;
QStyleOptionViewItemNewoption=option;
Newoption.rect.setRight(iTextRight);//設定文字顯示的右邊界值
QStringelidetext=fm.elidedText(strShortMsg,Qt::ElideRight,Newoption.rect
.width()-10);//計算顯示的文字
painter->drawText(Newoption.rect,Qt::AlignHCenter|Qt::AlignVCenter,elidetext);
//繪製按鈕
intnX=option.rect.width()-m_nWidth-10;
intnY=(option.rect.height()-m_nHeight)/2;
QStyleOptionButtonbutton;
button.rect=QRect(option.rect.left()+nX,
option.rect.top()+nY,m_nWidth,m_nHeight);
button.state
|=QStyle::State_Enabled;
QWidget*pWidget;
pWidget=m_pOpenDetailButton.data();
button.text="詳情";
if(button.rect.contains(m_mousePoint))
{
if(m_nType==0)
{
button.state|=QStyle::State_MouseOver;
}
elseif(m_nType==1)
{
button.state|=QStyle::State_Sunken;
}
}
QApplication::style()->drawControl(QStyle::CE_PushButton
,&button,painter,pWidget);

遺留問題:此方法可以實現一行文字緊跟按鈕, 不能實現多行文字後新增按鈕。