简体   繁体   中英

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.). I need to create an icon with a "white background" that represents the npc's image. It should be clickable (when it's clicked, current selected npc's icon ID will be set according to the selection).

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 :

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.

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

Use with a 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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