c++ qpushbuttion clicked(bool) 使用例子
时间: 2023-11-22 20:56:58 浏览: 44
下面是一个简单的使用 `QPushButton` 的例子,当按钮被点击时,会弹出一个对话框:
```cpp
#include <QApplication>
#include <QPushButton>
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建一个按钮
QPushButton button("Click me!");
// 连接按钮的 clicked(bool) 信号到槽函数
QObject::connect(&button, &QPushButton::clicked, [&]() {
// 显示一个对话框
QMessageBox::information(nullptr, "Message", "Button clicked!");
});
// 显示按钮
button.show();
// 运行应用程序
return app.exec();
}
```
在上面的代码中,我们创建了一个 `QPushButton` 对象,并将其显示在屏幕上。然后,我们连接了按钮的 `clicked(bool)` 信号到一个匿名的 lambda 函数,该函数将弹出一个消息框。最后,我们运行了应用程序并进入事件循环。当用户点击按钮时,`clicked(bool)` 信号会被发射,槽函数会被调用,从而弹出消息框。
相关问题
c++ qpushbuttion clicked(bool) 传递bool参数的使用例子
QPushButton 的 clicked(bool) 信号是在按钮被单击时发射的,参数为一个 bool 类型的值,表示该按钮是否被选中。以下是一个简单的使用例子:
```cpp
#include <QPushButton>
#include <QMessageBox>
class MyWidget : public QWidget {
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
QPushButton *button1 = new QPushButton("Button 1", this);
connect(button1, &QPushButton::clicked, this, &MyWidget::onButton1Clicked);
QPushButton *button2 = new QPushButton("Button 2", this);
button2->setCheckable(true); // 设置该按钮为可选中状态
connect(button2, &QPushButton::clicked, this, &MyWidget::onButton2Clicked);
}
private slots:
void onButton1Clicked() {
QMessageBox::information(this, "Button 1", "Button 1 is clicked.");
}
void onButton2Clicked(bool checked) {
if (checked) {
QMessageBox::information(this, "Button 2", "Button 2 is checked.");
} else {
QMessageBox::information(this, "Button 2", "Button 2 is unchecked.");
}
}
};
```
上面的代码创建了两个 QPushButton 对象,其中第二个按钮被设置为可选中状态。当第一个按钮被单击时,会弹出一个对话框显示按钮 1 被单击;当第二个按钮被单击时,会根据该按钮是否被选中分别弹出不同的对话框。
qpushbuttion clicked(bool) 使用例子
QPushButton是Qt中的一个重要组件,用于创建按钮。clicked(bool)是QPushButton类中的一个信号,用于在按钮被点击时发出信号。以下是使用QPushButton的一个例子:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建一个按钮
button = QPushButton("Click me!", self)
# 设置按钮的位置和大小
button.setGeometry(50, 50, 100, 50)
# 连接按钮的clicked信号到槽函数
button.clicked.connect(self.on_button_clicked)
def on_button_clicked(self):
print("Button clicked")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在这个例子中,我们创建了一个名为“Click me!”的按钮,并将其添加到主窗口中。然后,我们使用setGeometry()函数设置按钮的位置和大小,并使用clicked信号将按钮连接到槽函数on_button_clicked()。当按钮被点击时,槽函数将被调用并输出“Button clicked”。