How to Use QPushButton/zh

From Qt Wiki
< How to Use QPushButton
Revision as of 12:22, 17 April 2015 by AutoSpider (talk | contribs) (Remove non-functioning "toc" command)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.


简体中文 English Български Spanish Русский

怎样使用QPushButton?

QPushButton概览

开发人员可以使用 QPushButton 来创建和操控按钮。这个类易于使用和被定制,所以它是Qt中最有用的类之一。一般来说,按钮只显示位于其上的文字,不过它也可以同时显示一个图标。

QPushButton继承自 QAbstractButton ,后者继承自 QWidget

信号

继承自QAbstractButton的

  • void clicked ( bool checked = false )
  • void pressed ()
  • void released ()
  • void toggled ( bool checked )

继承自QWidget的

  • void customContextMenuRequested ( const QPoint & pos )

继承自QObject的

  • void destroyed ( QObject * obj = 0 )

基本用法

文本

QPushButton的文本可以在按钮被创建时设置,也可以在之后使用 setText() 方法设置。使用 text() 方法来获得按钮当前的文本。

图标

同样的,QPushButton的图标可以在按钮被创建时设置,也可以在之后使用 setIcon() 方法设置。使用 icon() 方法来获得按钮当前的图标。

位置和大小的设置

使用 setGeometry() 方法来设置按钮的位置和大小。如果只是想修改按钮的大小,使用 resize() 方法来设置。

按钮的操控

当有事件发生时,QPushButton会发出信号。要操控按钮,把确切的信号和一个信号相连接:

 connect(m_button, SIGNAL (released()),this, SLOT (handleButton())); <code>

== 示例 ==

下面这个简单的代码片段演示了怎样创建和使用QPushButton它已经在Qt Symbian Simulator上通过了测试

你会看到一个QPushButton的实例被创建出来信号 '''released()''' 和槽 '''handleButton()''' 连接在一起它们用于改变按钮的文本和大小

=== mainwindow.h ===
  1. ifndef MAINWINDOW_H
  2. define MAINWINDOW_H
  1. include <QtGui/QMainWindow>
  2. include <QtGui/QPushButton>

namespace Ui {

class MainWindow;

}

class MainWindow : public QMainWindow {

Q_OBJECT

public:

explicit MainWindow(QWidget *parent = 0);
virtual ~MainWindow();

private slots:

void handleButton();

private:

QPushButton *m_button;

};

  1. endif // MAINWINDOW_H
=== mainwindow.cpp ===
  1. include "mainwindow.h"
  1. include <QtCore/QCoreApplication>

MainWindow::MainWindow(QWidget *parent)

: QMainWindow(parent)

{

// 创建按钮
m_button = new QPushButton("My Button", this);

// 设置按钮的大小和位置

m_button->setGeometry(QRect(QPoint(100, 100),
QSize(200, 50)));

// 把按钮发出的信号连接到确切的槽

connect(m_button, SIGNAL (released()), this, SLOT (handleButton()));

}

void MainWindow::handleButton() {

// 改变按钮的文本
m_button->setText("Example");

// 改变按钮的大小

m_button->resize(100,100);

}

MainWindow::~MainWindow() {

}

=== main.cpp ===
  1. include "mainwindow.h"
  1. include <QtGui/QApplication>

int main(int argc, char *argv[]) {

QApplication app(argc, argv);

MainWindow mainWindow;

mainWindow.showMaximized();
return app.exec();

}

参见

Qt Buttons

Basic Qt Programming Tutorial

欢迎讨论:

Qt 博客-wd007的专栏