首先,“它不起作用”并不意味着什么,如果你不说出你遇到了什么错误,就很难帮助你。那么,问题就很少了。
所有QObject派生类都是不可复制的,这意味着你不能这样做
QWidget a;
QWidget b;
b = a; // Wrong
您应该使用指针(或者也许是引用)。
QWidget a;
QWidget * b = new QWidget(...);
QWidget * c;
c = & a; // Ok
c = b; // Ok
那么你的connect
调用错误:
connect(&up, SIGNAL(clicked()), &up, SLOT(scrollUp()));
第三个参数是拥有槽的对象。up
是一个 QPushButton,它没有scrollUp()
插槽,是您的主窗口执行以下操作:
connect(&up, SIGNAL(clicked()), this, SLOT(scrollUp()));
(since connect
在 MainWindow 的构造函数中调用this
指向当前的 MainWindow 对象)。
同样在 C++ 中=
符号表示赋值,用于相等比较使用=='. And
sender` 是一个函数。
如果以正确的方式实施,您的方法应该有效:
class MainWindow: public QWidget
{
QScrollArea * scroll1;
QScrollArea * scroll2;
QWidget * view1;
QWidget * view2;
QPushButton * up1;
QPushButton * up2;
QPushButton * down1;
QPushButton * down2;
public:
MainWindow()
{
// Here initialize member variables.
...
connect(up1, SIGNAL(clicked()), this, SLOT(scrollUp()));
connect(up2, SIGNAL(clicked()), this, SLOT(scrollUp()));
connect(down1, SIGNAL(clicked()), this, SLOT(scrollDown()));
connect(down2, SIGNAL(clicked()), this, SLOT(scrollDown()));
}
public slots:
void scrollDown()
{
QScrollArea * area;
QWidget * view;
if(qobject_cast<QPushButton>(sender()) == down1) {
area = & scroll1;
view = & view1;
} else if(qobject_cast<QPushButton>(sender()) == down2) {
area = & scroll2;
view = & view2;
} else {
// Error.
}
// Now `area` and `view` point to the right widgets.
...
}
void scrollUp()
{
// The same as before.
}
};
另一种方法是将实际的滚动指令提取到单独的函数中:
class MainWindow: public QWidget
{
// Same variables as before
...
public:
MainWindow()
{
// Here initialize member variables.
...
connect(up1, SIGNAL(clicked()), this, SLOT(scrollUp1()));
connect(up2, SIGNAL(clicked()), this, SLOT(scrollUp2()));
connect(down1, SIGNAL(clicked()), this, SLOT(scrollDown1()));
connect(down2, SIGNAL(clicked()), this, SLOT(scrollDown2()));
}
public slots:
void scrollDown(QScrollArea * area, QWidget * view)
{
// Here you scroll over `area` and `view`.
}
void scrollDown1()
{
scrollDown(scroll1, area1);
}
void scrollDown2()
{
scrollDown(scroll2, area2);
}
// Again, the same for `scrollUp`.
};