#include "chooselevelscene.h"
#include"qmenubar.h"
#include"qmenu.h"
#include"qaction.h"
#include"qpainter.h"
#include"qpixmap.h"
ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QMainWindow(parent)
{
QMenuBar *menuBar=new QMenuBar(this);
setMenuBar(menuBar);
QMenu *startMenu=menuBar->addMenu("开始");
QAction *quitAction=startMenu->addAction("退出");
connect(quitAction,&QAction::triggered,[=](){
this->close();
});
//返回按钮设置
MyPushButton * backBtn=new MyPushButton(":/res/BackButton.png",":/res/BackButtonSelected.png");
backBtn->setParent(this);
backBtn->move(this->width()-backBtn->width(),this->height()-backBtn->height());
}
void ChooseLevelScene::paintEvent(QPaintEvent *event)
{
//加载背景
QPixmap pix;
pix.load(":/res/PlayLevelSceneBg.png");
QPainter painter(this);
painter.drawPixmap(0,0,this->width(),this->height(),pix);
//加载标题
pix.load(":/res/Title.png");
pix=pix.scaled(pix.width()*1.5,pix.height()*1.5);
painter.drawPixmap(this->width()*0.5-pix.width()*0.5,50,pix.width(),pix.height(),pix);
}
qt中设置返回按钮,但是不显示
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
关注引自免费微信小程序:皆我百晓生
从你提供的代码来看,你创建了一个
MyPushButton对象,并尝试将其添加到窗口上作为返回按钮。然而,你没有提供MyPushButton类的定义,这可能是导致按钮不显示的原因之一。此外,确保按钮在窗口上的正确显示,还需要检查几个关键点:- 信号与槽连接:确认
MyPushButton是否正确地继承了QPushButton或类似基类,并且其点击事件是否能被正确捕获。 - 位置和大小:你设置了按钮的位置为窗口的右下角(
this->width()-backBtn->width(),this->height()-backBtn->height()),这通常是可以的,但要确保窗口的尺寸足够大,以便可以看到按钮。
为了帮助你解决问题,这里是一个可能的解决方案,包括一个简单的
MyPushButton类定义示例以及如何在构造函数中正确地初始化和显示它:#include <QPushButton> #include <QPixmap> class MyPushButton : public QPushButton { public: MyPushButton(const QString &normalImg, const QString &pressedImg, QWidget *parent = nullptr) : QPushButton(parent), normalImgPath(normalImg), pressedImgPath(pressedImg) {} protected: void paintEvent(QPaintEvent *event) override { QPushButton::paintEvent(event); QPainter painter(this); QPixmap pixmap; if (this->underMouse()) { pixmap.load(pressedImgPath); } else { pixmap.load(normalImgPath); } painter.drawPixmap(0, 0, pixmap); } private: QString normalImgPath; QString pressedImgPath; }; // 在你的构造函数中 ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QMainWindow(parent) { ... // 返回按钮设置 MyPushButton *backBtn = new MyPushButton(":/res/BackButton.png", ":/res/BackButtonSelected.png", this); backBtn->move(this->width() - backBtn->width(), this->height() - backBtn->height()); backBtn->show(); // 确保按钮可见 } // 如果你需要在paintEvent中重绘按钮,可以这样做: void ChooseLevelScene::paintEvent(QPaintEvent *event) { QMainWindow::paintEvent(event); ... // 无需在paintEvent中重新绘制按钮,因为按钮有自己的paintEvent处理 }上述代码中,
MyPushButton类继承自QPushButton,并覆盖了paintEvent方法来使用图片而非默认样式绘制按钮。在ChooseLevelScene构造函数中,我们创建了MyPushButton实例,并通过调用show()方法确保按钮在窗体上是可见的。如果你的
MyPushButton类已经包含了这些功能,请检查是否有其他因素阻止按钮的显示,例如按钮的父窗口是否已经显示,或者窗口的大小是否足以包含按钮。解决 无用评论 打赏 举报 编辑记录- 信号与槽连接:确认