label_9->setStyleSheet(QString("QLabel { background-image: url(%1);background-color: rgb(231, 231, 231);border-radius: 5px; }").arg(imagePath)); ui->label_9->setFixedSize(48, 48); ui->la...-Go服务器开发" />

ZBLOG

imagePath =currentPath + "/img/kaoshi.png"; ui->label_9->setStyleSheet(QString("QLabel { background-image: url(%1);background-color: rgb(231, 231, 231);border-radius: 5px; }").arg(imagePath)); ui->label_9->setFixedSize(48, 48); ui->la...

在 Qt 中,使用样式表设置背景图像时,图片通常会根据控件的大小进行缩放和定位。为了让图片在 QLabel 控件中居中显示,你可以通过以下几种方式实现:

方法一:使用 QLabel::setPixmap()

最直接的方法是使用 QLabelsetPixmap() 方法,并通过调整 QLabel 的对齐方式来确保图像居中。

QString imagePath = currentPath + "/img/kaoshi.png";
QPixmap pixmap(imagePath);
pixmap = pixmap.scaled(ui->label_9->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
ui->label_9->setPixmap(pixmap);
ui->label_9->setAlignment(Qt::AlignCenter); // 设置 QLabel 对齐方式为居中

方法二:继续使用样式表并调整属性

如果你希望继续使用样式表的方式来设置背景图像,可以尝试以下方法,但请注意,这可能需要更多的手动控制以获得正确效果:

  1. 确保标签有足够的大小。
  2. 使用 background-position 属性(可行性依赖于具体环境)。
QString imagePath = currentPath + "/img/kaoshi.png";
ui->label_9->setStyleSheet(QString("QLabel { background-image: url(%1); background-color: rgb(231, 231, 231); border-radius: 5px; }").arg(imagePath));
ui->label_9->setFixedSize(48, 48);
ui->label_9->setAlignment(Qt::AlignCenter); // 这行不一定有效,因为背景图片可能不遵循对齐

注意:在某些情况下,Qt 样式表中的背景图像可能不会尊重对齐属性,因此建议采用第一种方法。

方法三:自定义绘制

如果前两种方法无法满足需求,可以选择重写绘制事件,自己手动绘制图像,从而精确控制其位置:

class CustomLabel : public QLabel {
    Q_OBJECT

public:
    CustomLabel(QWidget *parent = nullptr) : QLabel(parent) {}

protected:
    void paintEvent(QPaintEvent *event) override {
        QLabel::paintEvent(event);
        QPainter painter(this);

        QString imagePath = currentPath + "/img/kaoshi.png";
        QPixmap pixmap(imagePath);
        
        QSize size = this->size();
        QRect rect((size.width() - pixmap.width()) / 2,
                    (size.height() - pixmap.height()) / 2,
                    pixmap.width(),
                    pixmap.height());

        painter.drawPixmap(rect, pixmap);
    }
};

然后用这个自定义标签代替原来的标签。这样你就可以准确地将图像居中绘制。

总结

对于大多数情况,第一种或第三种方法是最推荐的。希望这些建议能帮助到你!如果还有其他问题,请随时问我。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:label_9->setStyleSheet(QString("QLabel { background-image: url(%1);background-color: rgb(231, 231, 231);border-radius: 5px; }").arg(imagePath)); ui->label_9->setFixedSize(48, 48); ui->la...">https://golang.0voice.com/?id=21343

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?