简体   繁体   English

Qt:我应该使用哪个对象/项目来创建可点击图标

[英]Qt: Which object/item should I use to create clickable icons

I'm trying to write an editor for an rpg (Role Playing Game) (npc / quests / items etc.). 我正在尝试为rpg(角色扮演游戏)(npc /任务/物品等)编写编辑器。 I need to create an icon with a "white background" that represents the npc's image. 我需要创建一个带有“白色背景”的图标,该图标代表NPC的图像。 It should be clickable (when it's clicked, current selected npc's icon ID will be set according to the selection). 它应该是可单击的(单击时,将根据选择设置当前选定的npc的图标ID)。

I've managed to build a pop-up dialog to show all the icons, but couldn't manage to find a way to create clickable icons. 我设法建立了一个弹出对话框来显示所有图标,但是找不到设法创建可点击图标的方法。 Which class should I implement in order to get it working? 我应该实现哪个类才能使其正常工作?

Clickable icons can be achieved using either QPushButton or QToolButton : 可点击的图标可以使用QPushButtonQToolButton来实现:

QPushButton* button = new QPushButton;
button->setIcon(QIcon("/path/to/my/icon"));

I've done something similar but didn't want something that looked like a button, nor did I want to get into style overrides or special painting. 我做过类似的事情,但不想要看起来像按钮的东西,也不想进入样式替代或特殊绘画。 Instead, I created a ClickableLabel class that derives from QLabel. 相反,我创建了一个从QLabel派生的ClickableLabel类。

The pertinent part of the code is: 该代码的相关部分是:

class ClickableLabel : public QLabel
{
protected:

    virtual void mouseReleaseEvent (QMouseEvent *evt)
    {
        emit clicked (evt->button ());
    }

signals:

    void clicked (int button);

...rest of class definition...
}

You can adjust the signal parameters as desired. 您可以根据需要调整信号参数。

Clickable QLabel : https://wiki.qt.io/Clickable_QLabel 可点击的QLabel: https : //wiki.qt.io/Clickable_QLabel

Use with a QPixmap : http://doc.qt.io/qt-4.8/qlabel.html#pixmap-prop 与QPixmap一起使用: http : //doc.qt.io/qt-4.8/qlabel.html#pixmap-prop

Header

class ClickableLabel : public QLabel
{
Q_OBJECT
public:
    explicit ClickableLabel( const QString& text="", QWidget* parent=0 );
    ~ClickableLabel();
signals:
    void clicked();
protected:
    void mousePressEvent(QMouseEvent* event);
};

Source 资源

ClickableLabel::ClickableLabel(const QString& text, QWidget* parent)
    : QLabel(parent)
{
setText(text);
}

ClickableLabel::~ClickableLabel()
{
}

void ClickableLabel::mousePressEvent(QMouseEvent* event)
{
    emit clicked();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM