Skip to content

Instantly share code, notes, and snippets.

@jcelerier
Created October 19, 2022 16:21
Show Gist options
  • Save jcelerier/f76e3ee55037675db559e5062f7bd5bf to your computer and use it in GitHub Desktop.
Save jcelerier/f76e3ee55037675db559e5062f7bd5bf to your computer and use it in GitHub Desktop.
#include <QAction>
#include <QApplication>
#include <QLineEdit>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QTableWidget>
#include <QVBoxLayout>
struct Form : QWidget {
Form() {
button.setEnabled(false);
table.setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
table.setRowCount(2);
table.setColumnCount(1);
auto item1 = new QTableWidgetItem;
item1->setText("Item 1");
table.setItem(0, 0, item1);
auto item2 = new QTableWidgetItem;
item2->setText("Item 2");
table.setItem(1, 0, item2);
layout.addWidget(&line_edit);
layout.addWidget(&button);
layout.insertWidget(0, &table);
show();
init();
}
void init() {
connect(&button, &QPushButton::clicked, this, [this] {
const auto text = line_edit.text();
QMessageBox::information(
this, "Example", QString("Text: \"%1\". Congratulations!").arg(text));
});
connect(&line_edit, &QLineEdit::textEdited, this,
[this] { button.setEnabled(!line_edit.text().isEmpty()); });
connect(&table, &QTableWidget::currentItemChanged, this,
[](QTableWidgetItem *current, QTableWidgetItem *previous) {
if (previous) {
auto font = previous->font();
font.setBold(false);
previous->setFont(font);
}
if (current) {
auto font = current->font();
font.setBold(true);
current->setFont(font);
}
});
connect(&table, &QTableWidget::customContextMenuRequested, this,
&Form::on_table_context_menu_requested);
}
void on_table_context_menu_requested(QPoint pos) {
auto global_pos = table.viewport()->mapToGlobal(pos);
QMenu menu;
menu.addAction("Fake action 1");
menu.addAction("Fake action 2");
QAction action3{"Real action"};
menu.addAction(&action3);
QAction *action = menu.exec(global_pos);
auto message = [&]() -> QString {
if (!action) {
return "No action selected!";
} else if (action == &action3) {
return "Real action selected!";
} else {
return QString("Fake action selected (%1)").arg(action->text());
}
}();
QMessageBox::information(this, "Example", message);
}
QVBoxLayout layout{this};
QLineEdit line_edit;
QPushButton button{"Start"};
QTableWidget table;
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Form f;
return a.exec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment