#include <QtGui>
Q_OBJECT
public:
Entry e;
e.label = label;
e.pos = pos;
QRect r
= fm.
boundingRect(label
);
r.translate(e.pos);
e.boundingBox = r;
e.selected = false;
m_entries << e;
update();
}
void removeEntry(int which) {
m_entries.removeAt(which);
update();
}
int indexAt
(QPoint pos
) const { for(int i=0; i< m_entries.count(); ++i) {
const Entry &e = m_entries.at(i);
if(e.boundingBox.contains(pos))
return i;
}
return -1;
}
protected:
foreach(Entry e, m_entries) {
p.save();
if(e.selected) {
p.setPen(Qt::red);
}
p.drawText(e.pos, e.label);
p.restore();
// p.save();
// p.setPen(Qt::red);
// p.drawRect(e.boundingBox);
// p.restore();
}
}
int idx = indexAt(me->pos());
if(idx < 0) return;
m_entries[idx].selected = !m_entries[idx].selected;
update();
}
private:
struct Entry {
bool selected;
};
QList<Entry> m_entries;
};
#include "main.moc"
int main(int argc, char **argv) {
Widget w;
w.show();
w.
addEntry("Home",
QPoint(100,
100));
w.
addEntry("School",
QPoint(300,
200));
w.
addEntry("Work",
QPoint(500,
20));
return app.exec();
}
#include <QtGui>
class Widget : public QWidget {
Q_OBJECT
public:
Widget(QWidget *parent = 0) : QWidget(parent) {}
void addEntry(QString label, QPoint pos) {
Entry e;
e.label = label;
e.pos = pos;
QFontMetrics fm = fontMetrics();
QRect r = fm.boundingRect(label);
r.translate(e.pos);
e.boundingBox = r;
e.selected = false;
m_entries << e;
update();
}
void removeEntry(int which) {
m_entries.removeAt(which);
update();
}
int indexAt(QPoint pos) const {
for(int i=0; i< m_entries.count(); ++i) {
const Entry &e = m_entries.at(i);
if(e.boundingBox.contains(pos))
return i;
}
return -1;
}
protected:
void paintEvent(QPaintEvent *pe) {
QPainter p(this);
foreach(Entry e, m_entries) {
p.save();
if(e.selected) {
p.setPen(Qt::red);
}
p.drawText(e.pos, e.label);
p.restore();
// p.save();
// p.setPen(Qt::red);
// p.drawRect(e.boundingBox);
// p.restore();
}
}
void mouseReleaseEvent(QMouseEvent *me) {
int idx = indexAt(me->pos());
if(idx < 0) return;
m_entries[idx].selected = !m_entries[idx].selected;
update();
}
private:
struct Entry {
QString label;
QPoint pos;
QRect boundingBox;
bool selected;
};
QList<Entry> m_entries;
};
#include "main.moc"
int main(int argc, char **argv) {
QApplication app(argc, argv);
Widget w;
w.show();
w.addEntry("Home", QPoint(100, 100));
w.addEntry("School", QPoint(300, 200));
w.addEntry("Work", QPoint(500, 20));
return app.exec();
}
To copy to clipboard, switch view to plain text mode
Bookmarks