【问题标题】:Construct QPushButton with QIcon alignleft and text center align使用 QIcon alignleft 和文本中心对齐构造 QPushButton
【发布时间】:2016-08-23 10:44:54
【问题描述】:

我想创建QPushButton 与QIcon 左对齐(默认不居中)和文本居中对齐。我不想使用样式表。我知道这可能会使用QPainter,但我无法做到。我几乎没有任何线索并尝试了这段代码:

void MyPushButton::paintEvent(QPaintEvent *)
{
    QStylePainter painter(this);
    QStyleOptionButton opt;
    initStyleOption(&opt);
    painter.drawItemPixmap(opt.rect, Qt::AlignLeft, opt.icon);
    painter.drawItemText(opt.rect, Qt::AlignCenter, palette(), 1, opt.text);
    painter.drawPrimitive(QStyle::PE_PanelButtonCommand, opt);
}

产生此错误消息

没有匹配函数调用'QStylePainter::drawItemPixmap(QRect&, Qt::AlignmentFlag, QIcon&)'painter.drawItemPixmap(opt.rect, Qt::AlignCenter, opt.icon);

上面的代码有什么问题?

【问题讨论】:

  • 我们还需要知道您在运行代码时实际发生了什么以及您不喜欢它的哪些地方。
  • this error code error: no matching function for call to 'QStylePainter::drawItemPixmap(QRect&, Qt::AlignmentFlag, QIcon&)'painter.drawItemPixmap(opt.rect, Qt::AlignCenter, opt.图标);
  • @mumulala 答案属于对问题的编辑,而不是评论:)
  • 显示的代码不足,无法了解问题所在。据我们所知,您在尺寸管理等方面错误地设置了您的小部件。如果没有完整的代码来编译、运行和演示问题,这个问题是无法回答的。
  • 一旦一个问题有了答案,你就不能从根本上改变它,以至于它会使那个答案无效。如果需要,请提出另一个问题。

标签: c++ qt qpainter qpushbutton


【解决方案1】:

你得到了

这个错误代码error: no matching function for call to 'QStylePainter::drawItemPixmap(QRect&, Qt::AlignmentFlag, QIcon&)'painter.drawItemPixmap(opt.rect, Qt::AlignCenter, opt.icon);

因为drawItemPixmap 绘制...一个像素图。不是图标。因此,您需要做的就是使用pixmap() 访问器获取图标像素图。

改变

painter.drawItemPixmap(opt.rect, Qt::AlignLeft, opt.icon);

到

// or whaever size you want
painter.drawItemPixmap(opt.rect, Qt::AlignLeft, opt.icon.pixmap(QSize(16,16))); 

【讨论】:

  • 感谢@Nicholas 的回复,我更改了代码,但没有产生任何错误,但图标和文本不可见。
  • @mumulala 就像 Kuba 说的那样,没有特定代码、输出图像和错误消息,我们无法复制问题,而且我们无能为力。
  • 如果我删除这条线painter.drawPrimitive(QStyle::PE_PanelButtonCommand, opt); QIcon 位于左侧,文本位于中间,但没有按钮行为。
  • @mumulala 要获得按钮行为,您必须单独绘制opt.state 的每个排列以及所有按钮功能。老实说,如果你只使用样式表,你会方式更好。它更简单、更灵活,编写的代码也更少。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
相关资源
最近更新 更多