请使用QT 编写一段点击按钮改变线段颜色的代码
以下是使用QT编写的点击按钮改变线段颜色的代码示例:
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QHBoxLayout>
#include <QPainter>
class LineColorWidget : public QWidget
{
public:
LineColorWidget(QWidget *parent = nullptr) : QWidget(parent), color(Qt::black) {}
void setColor(const QColor &color)
{
this->color = color;
update();
}
protected:
void paintEvent(QPaintEvent *event) override
{
Q_UNUSED(event)
QPainter painter(this);
painter.setPen(QPen(color, 2));
painter.drawLine(20, 20, width() - 20, height() - 20);
}
private:
QColor color;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget;
window->setWindowTitle("Line Color Example");
QPushButton *button = new QPushButton("Change Color");
LineColorWidget *lineWidget = new LineColorWidget;
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(lineWidget);
layout->addWidget(button);
window->setLayout(layout);
QObject::connect(button, &QPushButton::clicked, [&lineWidget]() {
QColor color = QColorDialog::getColor(lineWidget->palette().color(QPalette::WindowText), lineWidget);
if (color.isValid()) {
lineWidget->setColor(color);
}
});
window->show();
return app.exec();
}
在此示例中,我们创建了一个 LineColorWidget 类,它绘制一条线段并允许改变其颜色。setColor() 方法用于设置线段颜色,并调用 update() 方法以触发重绘。在 paintEvent() 方法中,我们使用 QPainter 绘制线段。
在 main() 函数中,我们创建了一个窗口和一个按钮。我们还创建了一个 HBoxLayout 布局,并将 LineColorWidget 和按钮添加到该布局中。我们使用 QColorDialog::getColor() 方法显示颜色对话框,并在选择颜色后将其设置为线段的新颜色。
最后,我们显示窗口并启动应用程序的事件循环。
原文地址: https://www.cveoy.top/t/topic/bBOl 著作权归作者所有。请勿转载和采集!