connect()中slot定义的变迁
随着C++的演进, 代码的写作方式也会发生变化.
这是Qt5之前的时代的Demo里面的写法, 当需要将slot函数作为参数传递的时候, 使用的是SLOT()
宏.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| fontColorToolButton->setMenu(createColorMenu(SLOT(textColorChanged()), Qt::black)); ... fillColorToolButton->setMenu(createColorMenu(SLOT(itemColorChanged()), Qt::white)); ...
QMenu *MainWindow::createColorMenu(const char *slot, QColor defaultColor) { ... QMenu *colorMenu = new QMenu(this); for (int i = 0; i < colors.count(); ++i) { QAction *action = new QAction(names.at(i), this); action->setData(colors.at(i)); action->setIcon(createColorIcon(colors.at(i))); connect(action, SIGNAL(triggered()), this, slot); ... colorMenu->addAction(action); } return colorMenu; }
|
而在进入Qt6时代后, 基于C++17, 官方Demo也悄然发生了改变:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| fillColorToolButton = new QToolButton; fillColorToolButton->setPopupMode(QToolButton::MenuButtonPopup); fillColorToolButton->setMenu(createColorMenu(&MainWindow::itemColorChanged, Qt::white)); ... lineColorToolButton->setMenu(createColorMenu(&MainWindow::lineColorChanged, Qt::black));
template<typename PointerToMemberFunction> QMenu *MainWindow::createColorMenu(const PointerToMemberFunction &slot, QColor defaultColor) { colors << Qt::black << Qt::white << Qt::red << Qt::blue << Qt::yellow; QStringList names; names << tr("black") << tr("white") << tr("red") << tr("blue") << tr("yellow");
QMenu *colorMenu = new QMenu(this); for (int i = 0; i < colors.count(); ++i) { QAction *action = new QAction(names.at(i), this); action->setData(colors.at(i)); action->setIcon(createColorIcon(colors.at(i))); connect(action, &QAction::triggered, this, slot); colorMenu->addAction(action); if (colors.at(i) == defaultColor) colorMenu->setDefaultAction(action); } return colorMenu; }
|